SemaDecl.cpp 676 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425
  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/NonTrivialTypeVisitor.h"
  25. #include "clang/AST/StmtCXX.h"
  26. #include "clang/Basic/Builtins.h"
  27. #include "clang/Basic/PartialDiagnostic.h"
  28. #include "clang/Basic/SourceManager.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  31. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  32. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  33. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  34. #include "clang/Sema/CXXFieldCollector.h"
  35. #include "clang/Sema/DeclSpec.h"
  36. #include "clang/Sema/DelayedDiagnostic.h"
  37. #include "clang/Sema/Initialization.h"
  38. #include "clang/Sema/Lookup.h"
  39. #include "clang/Sema/ParsedTemplate.h"
  40. #include "clang/Sema/Scope.h"
  41. #include "clang/Sema/ScopeInfo.h"
  42. #include "clang/Sema/SemaInternal.h"
  43. #include "clang/Sema/Template.h"
  44. #include "llvm/ADT/SmallString.h"
  45. #include "llvm/ADT/Triple.h"
  46. #include <algorithm>
  47. #include <cstring>
  48. #include <functional>
  49. using namespace clang;
  50. using namespace sema;
  51. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  52. if (OwnedType) {
  53. Decl *Group[2] = { OwnedType, Ptr };
  54. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  55. }
  56. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  57. }
  58. namespace {
  59. class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
  60. public:
  61. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
  62. bool AllowTemplates = false,
  63. bool AllowNonTemplates = true)
  64. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  65. AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
  66. WantExpressionKeywords = false;
  67. WantCXXNamedCasts = false;
  68. WantRemainingKeywords = false;
  69. }
  70. bool ValidateCandidate(const TypoCorrection &candidate) override {
  71. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  72. if (!AllowInvalidDecl && ND->isInvalidDecl())
  73. return false;
  74. if (getAsTypeTemplateDecl(ND))
  75. return AllowTemplates;
  76. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  77. if (!IsType)
  78. return false;
  79. if (AllowNonTemplates)
  80. return true;
  81. // An injected-class-name of a class template (specialization) is valid
  82. // as a template or as a non-template.
  83. if (AllowTemplates) {
  84. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  85. if (!RD || !RD->isInjectedClassName())
  86. return false;
  87. RD = cast<CXXRecordDecl>(RD->getDeclContext());
  88. return RD->getDescribedClassTemplate() ||
  89. isa<ClassTemplateSpecializationDecl>(RD);
  90. }
  91. return false;
  92. }
  93. return !WantClassName && candidate.isKeyword();
  94. }
  95. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  96. return llvm::make_unique<TypeNameValidatorCCC>(*this);
  97. }
  98. private:
  99. bool AllowInvalidDecl;
  100. bool WantClassName;
  101. bool AllowTemplates;
  102. bool AllowNonTemplates;
  103. };
  104. } // end anonymous namespace
  105. /// Determine whether the token kind starts a simple-type-specifier.
  106. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  107. switch (Kind) {
  108. // FIXME: Take into account the current language when deciding whether a
  109. // token kind is a valid type specifier
  110. case tok::kw_short:
  111. case tok::kw_long:
  112. case tok::kw___int64:
  113. case tok::kw___int128:
  114. case tok::kw_signed:
  115. case tok::kw_unsigned:
  116. case tok::kw_void:
  117. case tok::kw_char:
  118. case tok::kw_int:
  119. case tok::kw_half:
  120. case tok::kw_float:
  121. case tok::kw_double:
  122. case tok::kw__Float16:
  123. case tok::kw___float128:
  124. case tok::kw_wchar_t:
  125. case tok::kw_bool:
  126. case tok::kw___underlying_type:
  127. case tok::kw___auto_type:
  128. return true;
  129. case tok::annot_typename:
  130. case tok::kw_char16_t:
  131. case tok::kw_char32_t:
  132. case tok::kw_typeof:
  133. case tok::annot_decltype:
  134. case tok::kw_decltype:
  135. return getLangOpts().CPlusPlus;
  136. case tok::kw_char8_t:
  137. return getLangOpts().Char8;
  138. default:
  139. break;
  140. }
  141. return false;
  142. }
  143. namespace {
  144. enum class UnqualifiedTypeNameLookupResult {
  145. NotFound,
  146. FoundNonType,
  147. FoundType
  148. };
  149. } // end anonymous namespace
  150. /// Tries to perform unqualified lookup of the type decls in bases for
  151. /// dependent class.
  152. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  153. /// type decl, \a FoundType if only type decls are found.
  154. static UnqualifiedTypeNameLookupResult
  155. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  156. SourceLocation NameLoc,
  157. const CXXRecordDecl *RD) {
  158. if (!RD->hasDefinition())
  159. return UnqualifiedTypeNameLookupResult::NotFound;
  160. // Look for type decls in base classes.
  161. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  162. UnqualifiedTypeNameLookupResult::NotFound;
  163. for (const auto &Base : RD->bases()) {
  164. const CXXRecordDecl *BaseRD = nullptr;
  165. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  166. BaseRD = BaseTT->getAsCXXRecordDecl();
  167. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  168. // Look for type decls in dependent base classes that have known primary
  169. // templates.
  170. if (!TST || !TST->isDependentType())
  171. continue;
  172. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  173. if (!TD)
  174. continue;
  175. if (auto *BasePrimaryTemplate =
  176. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
  177. if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
  178. BaseRD = BasePrimaryTemplate;
  179. else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
  180. if (const ClassTemplatePartialSpecializationDecl *PS =
  181. CTD->findPartialSpecialization(Base.getType()))
  182. if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
  183. BaseRD = PS;
  184. }
  185. }
  186. }
  187. if (BaseRD) {
  188. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  189. if (!isa<TypeDecl>(ND))
  190. return UnqualifiedTypeNameLookupResult::FoundNonType;
  191. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  192. }
  193. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  194. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  195. case UnqualifiedTypeNameLookupResult::FoundNonType:
  196. return UnqualifiedTypeNameLookupResult::FoundNonType;
  197. case UnqualifiedTypeNameLookupResult::FoundType:
  198. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  199. break;
  200. case UnqualifiedTypeNameLookupResult::NotFound:
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. return FoundTypeDecl;
  207. }
  208. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  209. const IdentifierInfo &II,
  210. SourceLocation NameLoc) {
  211. // Lookup in the parent class template context, if any.
  212. const CXXRecordDecl *RD = nullptr;
  213. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  214. UnqualifiedTypeNameLookupResult::NotFound;
  215. for (DeclContext *DC = S.CurContext;
  216. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  217. DC = DC->getParent()) {
  218. // Look for type decls in dependent base classes that have known primary
  219. // templates.
  220. RD = dyn_cast<CXXRecordDecl>(DC);
  221. if (RD && RD->getDescribedClassTemplate())
  222. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  223. }
  224. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  225. return nullptr;
  226. // We found some types in dependent base classes. Recover as if the user
  227. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  228. // lookup during template instantiation.
  229. S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
  230. ASTContext &Context = S.Context;
  231. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  232. cast<Type>(Context.getRecordType(RD)));
  233. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  234. CXXScopeSpec SS;
  235. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  236. TypeLocBuilder Builder;
  237. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  238. DepTL.setNameLoc(NameLoc);
  239. DepTL.setElaboratedKeywordLoc(SourceLocation());
  240. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  241. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  242. }
  243. /// If the identifier refers to a type name within this scope,
  244. /// return the declaration of that type.
  245. ///
  246. /// This routine performs ordinary name lookup of the identifier II
  247. /// within the given scope, with optional C++ scope specifier SS, to
  248. /// determine whether the name refers to a type. If so, returns an
  249. /// opaque pointer (actually a QualType) corresponding to that
  250. /// type. Otherwise, returns NULL.
  251. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  252. Scope *S, CXXScopeSpec *SS,
  253. bool isClassName, bool HasTrailingDot,
  254. ParsedType ObjectTypePtr,
  255. bool IsCtorOrDtorName,
  256. bool WantNontrivialTypeSourceInfo,
  257. bool IsClassTemplateDeductionContext,
  258. IdentifierInfo **CorrectedII) {
  259. // FIXME: Consider allowing this outside C++1z mode as an extension.
  260. bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
  261. getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
  262. !isClassName && !HasTrailingDot;
  263. // Determine where we will perform name lookup.
  264. DeclContext *LookupCtx = nullptr;
  265. if (ObjectTypePtr) {
  266. QualType ObjectType = ObjectTypePtr.get();
  267. if (ObjectType->isRecordType())
  268. LookupCtx = computeDeclContext(ObjectType);
  269. } else if (SS && SS->isNotEmpty()) {
  270. LookupCtx = computeDeclContext(*SS, false);
  271. if (!LookupCtx) {
  272. if (isDependentScopeSpecifier(*SS)) {
  273. // C++ [temp.res]p3:
  274. // A qualified-id that refers to a type and in which the
  275. // nested-name-specifier depends on a template-parameter (14.6.2)
  276. // shall be prefixed by the keyword typename to indicate that the
  277. // qualified-id denotes a type, forming an
  278. // elaborated-type-specifier (7.1.5.3).
  279. //
  280. // We therefore do not perform any name lookup if the result would
  281. // refer to a member of an unknown specialization.
  282. if (!isClassName && !IsCtorOrDtorName)
  283. return nullptr;
  284. // We know from the grammar that this name refers to a type,
  285. // so build a dependent node to describe the type.
  286. if (WantNontrivialTypeSourceInfo)
  287. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  288. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  289. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  290. II, NameLoc);
  291. return ParsedType::make(T);
  292. }
  293. return nullptr;
  294. }
  295. if (!LookupCtx->isDependentContext() &&
  296. RequireCompleteDeclContext(*SS, LookupCtx))
  297. return nullptr;
  298. }
  299. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  300. // lookup for class-names.
  301. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  302. LookupOrdinaryName;
  303. LookupResult Result(*this, &II, NameLoc, Kind);
  304. if (LookupCtx) {
  305. // Perform "qualified" name lookup into the declaration context we
  306. // computed, which is either the type of the base of a member access
  307. // expression or the declaration context associated with a prior
  308. // nested-name-specifier.
  309. LookupQualifiedName(Result, LookupCtx);
  310. if (ObjectTypePtr && Result.empty()) {
  311. // C++ [basic.lookup.classref]p3:
  312. // If the unqualified-id is ~type-name, the type-name is looked up
  313. // in the context of the entire postfix-expression. If the type T of
  314. // the object expression is of a class type C, the type-name is also
  315. // looked up in the scope of class C. At least one of the lookups shall
  316. // find a name that refers to (possibly cv-qualified) T.
  317. LookupName(Result, S);
  318. }
  319. } else {
  320. // Perform unqualified name lookup.
  321. LookupName(Result, S);
  322. // For unqualified lookup in a class template in MSVC mode, look into
  323. // dependent base classes where the primary class template is known.
  324. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  325. if (ParsedType TypeInBase =
  326. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  327. return TypeInBase;
  328. }
  329. }
  330. NamedDecl *IIDecl = nullptr;
  331. switch (Result.getResultKind()) {
  332. case LookupResult::NotFound:
  333. case LookupResult::NotFoundInCurrentInstantiation:
  334. if (CorrectedII) {
  335. TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
  336. AllowDeducedTemplate);
  337. TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
  338. S, SS, CCC, CTK_ErrorRecovery);
  339. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  340. TemplateTy Template;
  341. bool MemberOfUnknownSpecialization;
  342. UnqualifiedId TemplateName;
  343. TemplateName.setIdentifier(NewII, NameLoc);
  344. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  345. CXXScopeSpec NewSS, *NewSSPtr = SS;
  346. if (SS && NNS) {
  347. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  348. NewSSPtr = &NewSS;
  349. }
  350. if (Correction && (NNS || NewII != &II) &&
  351. // Ignore a correction to a template type as the to-be-corrected
  352. // identifier is not a template (typo correction for template names
  353. // is handled elsewhere).
  354. !(getLangOpts().CPlusPlus && NewSSPtr &&
  355. isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
  356. Template, MemberOfUnknownSpecialization))) {
  357. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  358. isClassName, HasTrailingDot, ObjectTypePtr,
  359. IsCtorOrDtorName,
  360. WantNontrivialTypeSourceInfo,
  361. IsClassTemplateDeductionContext);
  362. if (Ty) {
  363. diagnoseTypo(Correction,
  364. PDiag(diag::err_unknown_type_or_class_name_suggest)
  365. << Result.getLookupName() << isClassName);
  366. if (SS && NNS)
  367. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  368. *CorrectedII = NewII;
  369. return Ty;
  370. }
  371. }
  372. }
  373. // If typo correction failed or was not performed, fall through
  374. LLVM_FALLTHROUGH;
  375. case LookupResult::FoundOverloaded:
  376. case LookupResult::FoundUnresolvedValue:
  377. Result.suppressDiagnostics();
  378. return nullptr;
  379. case LookupResult::Ambiguous:
  380. // Recover from type-hiding ambiguities by hiding the type. We'll
  381. // do the lookup again when looking for an object, and we can
  382. // diagnose the error then. If we don't do this, then the error
  383. // about hiding the type will be immediately followed by an error
  384. // that only makes sense if the identifier was treated like a type.
  385. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  386. Result.suppressDiagnostics();
  387. return nullptr;
  388. }
  389. // Look to see if we have a type anywhere in the list of results.
  390. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  391. Res != ResEnd; ++Res) {
  392. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
  393. (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
  394. if (!IIDecl ||
  395. (*Res)->getLocation().getRawEncoding() <
  396. IIDecl->getLocation().getRawEncoding())
  397. IIDecl = *Res;
  398. }
  399. }
  400. if (!IIDecl) {
  401. // None of the entities we found is a type, so there is no way
  402. // to even assume that the result is a type. In this case, don't
  403. // complain about the ambiguity. The parser will either try to
  404. // perform this lookup again (e.g., as an object name), which
  405. // will produce the ambiguity, or will complain that it expected
  406. // a type name.
  407. Result.suppressDiagnostics();
  408. return nullptr;
  409. }
  410. // We found a type within the ambiguous lookup; diagnose the
  411. // ambiguity and then return that type. This might be the right
  412. // answer, or it might not be, but it suppresses any attempt to
  413. // perform the name lookup again.
  414. break;
  415. case LookupResult::Found:
  416. IIDecl = Result.getFoundDecl();
  417. break;
  418. }
  419. assert(IIDecl && "Didn't find decl");
  420. QualType T;
  421. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  422. // C++ [class.qual]p2: A lookup that would find the injected-class-name
  423. // instead names the constructors of the class, except when naming a class.
  424. // This is ill-formed when we're not actually forming a ctor or dtor name.
  425. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  426. auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
  427. if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
  428. FoundRD->isInjectedClassName() &&
  429. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  430. Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
  431. << &II << /*Type*/1;
  432. DiagnoseUseOfDecl(IIDecl, NameLoc);
  433. T = Context.getTypeDeclType(TD);
  434. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  435. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  436. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  437. if (!HasTrailingDot)
  438. T = Context.getObjCInterfaceType(IDecl);
  439. } else if (AllowDeducedTemplate) {
  440. if (auto *TD = getAsTypeTemplateDecl(IIDecl))
  441. T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  442. QualType(), false);
  443. }
  444. if (T.isNull()) {
  445. // If it's not plausibly a type, suppress diagnostics.
  446. Result.suppressDiagnostics();
  447. return nullptr;
  448. }
  449. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  450. // constructor or destructor name (in such a case, the scope specifier
  451. // will be attached to the enclosing Expr or Decl node).
  452. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
  453. !isa<ObjCInterfaceDecl>(IIDecl)) {
  454. if (WantNontrivialTypeSourceInfo) {
  455. // Construct a type with type-source information.
  456. TypeLocBuilder Builder;
  457. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  458. T = getElaboratedType(ETK_None, *SS, T);
  459. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  460. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  461. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  462. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  463. } else {
  464. T = getElaboratedType(ETK_None, *SS, T);
  465. }
  466. }
  467. return ParsedType::make(T);
  468. }
  469. // Builds a fake NNS for the given decl context.
  470. static NestedNameSpecifier *
  471. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  472. for (;; DC = DC->getLookupParent()) {
  473. DC = DC->getPrimaryContext();
  474. auto *ND = dyn_cast<NamespaceDecl>(DC);
  475. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  476. return NestedNameSpecifier::Create(Context, nullptr, ND);
  477. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  478. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  479. RD->getTypeForDecl());
  480. else if (isa<TranslationUnitDecl>(DC))
  481. return NestedNameSpecifier::GlobalSpecifier(Context);
  482. }
  483. llvm_unreachable("something isn't in TU scope?");
  484. }
  485. /// Find the parent class with dependent bases of the innermost enclosing method
  486. /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
  487. /// up allowing unqualified dependent type names at class-level, which MSVC
  488. /// correctly rejects.
  489. static const CXXRecordDecl *
  490. findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
  491. for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
  492. DC = DC->getPrimaryContext();
  493. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  494. if (MD->getParent()->hasAnyDependentBases())
  495. return MD->getParent();
  496. }
  497. return nullptr;
  498. }
  499. ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
  500. SourceLocation NameLoc,
  501. bool IsTemplateTypeArg) {
  502. assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
  503. NestedNameSpecifier *NNS = nullptr;
  504. if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
  505. // If we weren't able to parse a default template argument, delay lookup
  506. // until instantiation time by making a non-dependent DependentTypeName. We
  507. // pretend we saw a NestedNameSpecifier referring to the current scope, and
  508. // lookup is retried.
  509. // FIXME: This hurts our diagnostic quality, since we get errors like "no
  510. // type named 'Foo' in 'current_namespace'" when the user didn't write any
  511. // name specifiers.
  512. NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  513. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  514. } else if (const CXXRecordDecl *RD =
  515. findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
  516. // Build a DependentNameType that will perform lookup into RD at
  517. // instantiation time.
  518. NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  519. RD->getTypeForDecl());
  520. // Diagnose that this identifier was undeclared, and retry the lookup during
  521. // template instantiation.
  522. Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
  523. << RD;
  524. } else {
  525. // This is not a situation that we should recover from.
  526. return ParsedType();
  527. }
  528. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  529. // Build type location information. We synthesized the qualifier, so we have
  530. // to build a fake NestedNameSpecifierLoc.
  531. NestedNameSpecifierLocBuilder NNSLocBuilder;
  532. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  533. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  534. TypeLocBuilder Builder;
  535. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  536. DepTL.setNameLoc(NameLoc);
  537. DepTL.setElaboratedKeywordLoc(SourceLocation());
  538. DepTL.setQualifierLoc(QualifierLoc);
  539. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  540. }
  541. /// isTagName() - This method is called *for error recovery purposes only*
  542. /// to determine if the specified name is a valid tag name ("struct foo"). If
  543. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  544. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  545. /// cases in C where the user forgot to specify the tag.
  546. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  547. // Do a tag name lookup in this scope.
  548. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  549. LookupName(R, S, false);
  550. R.suppressDiagnostics();
  551. if (R.getResultKind() == LookupResult::Found)
  552. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  553. switch (TD->getTagKind()) {
  554. case TTK_Struct: return DeclSpec::TST_struct;
  555. case TTK_Interface: return DeclSpec::TST_interface;
  556. case TTK_Union: return DeclSpec::TST_union;
  557. case TTK_Class: return DeclSpec::TST_class;
  558. case TTK_Enum: return DeclSpec::TST_enum;
  559. }
  560. }
  561. return DeclSpec::TST_unspecified;
  562. }
  563. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  564. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  565. /// then downgrade the missing typename error to a warning.
  566. /// This is needed for MSVC compatibility; Example:
  567. /// @code
  568. /// template<class T> class A {
  569. /// public:
  570. /// typedef int TYPE;
  571. /// };
  572. /// template<class T> class B : public A<T> {
  573. /// public:
  574. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  575. /// };
  576. /// @endcode
  577. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  578. if (CurContext->isRecord()) {
  579. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  580. return true;
  581. const Type *Ty = SS->getScopeRep()->getAsType();
  582. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  583. for (const auto &Base : RD->bases())
  584. if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  585. return true;
  586. return S->isFunctionPrototypeScope();
  587. }
  588. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  589. }
  590. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  591. SourceLocation IILoc,
  592. Scope *S,
  593. CXXScopeSpec *SS,
  594. ParsedType &SuggestedType,
  595. bool IsTemplateName) {
  596. // Don't report typename errors for editor placeholders.
  597. if (II->isEditorPlaceholder())
  598. return;
  599. // We don't have anything to suggest (yet).
  600. SuggestedType = nullptr;
  601. // There may have been a typo in the name of the type. Look up typo
  602. // results, in case we have something that we can suggest.
  603. TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
  604. /*AllowTemplates=*/IsTemplateName,
  605. /*AllowNonTemplates=*/!IsTemplateName);
  606. if (TypoCorrection Corrected =
  607. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  608. CCC, CTK_ErrorRecovery)) {
  609. // FIXME: Support error recovery for the template-name case.
  610. bool CanRecover = !IsTemplateName;
  611. if (Corrected.isKeyword()) {
  612. // We corrected to a keyword.
  613. diagnoseTypo(Corrected,
  614. PDiag(IsTemplateName ? diag::err_no_template_suggest
  615. : diag::err_unknown_typename_suggest)
  616. << II);
  617. II = Corrected.getCorrectionAsIdentifierInfo();
  618. } else {
  619. // We found a similarly-named type or interface; suggest that.
  620. if (!SS || !SS->isSet()) {
  621. diagnoseTypo(Corrected,
  622. PDiag(IsTemplateName ? diag::err_no_template_suggest
  623. : diag::err_unknown_typename_suggest)
  624. << II, CanRecover);
  625. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  626. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  627. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  628. II->getName().equals(CorrectedStr);
  629. diagnoseTypo(Corrected,
  630. PDiag(IsTemplateName
  631. ? diag::err_no_member_template_suggest
  632. : diag::err_unknown_nested_typename_suggest)
  633. << II << DC << DroppedSpecifier << SS->getRange(),
  634. CanRecover);
  635. } else {
  636. llvm_unreachable("could not have corrected a typo here");
  637. }
  638. if (!CanRecover)
  639. return;
  640. CXXScopeSpec tmpSS;
  641. if (Corrected.getCorrectionSpecifier())
  642. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  643. SourceRange(IILoc));
  644. // FIXME: Support class template argument deduction here.
  645. SuggestedType =
  646. getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
  647. tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
  648. /*IsCtorOrDtorName=*/false,
  649. /*WantNontrivialTypeSourceInfo=*/true);
  650. }
  651. return;
  652. }
  653. if (getLangOpts().CPlusPlus && !IsTemplateName) {
  654. // See if II is a class template that the user forgot to pass arguments to.
  655. UnqualifiedId Name;
  656. Name.setIdentifier(II, IILoc);
  657. CXXScopeSpec EmptySS;
  658. TemplateTy TemplateResult;
  659. bool MemberOfUnknownSpecialization;
  660. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  661. Name, nullptr, true, TemplateResult,
  662. MemberOfUnknownSpecialization) == TNK_Type_template) {
  663. diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
  664. return;
  665. }
  666. }
  667. // FIXME: Should we move the logic that tries to recover from a missing tag
  668. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  669. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  670. Diag(IILoc, IsTemplateName ? diag::err_no_template
  671. : diag::err_unknown_typename)
  672. << II;
  673. else if (DeclContext *DC = computeDeclContext(*SS, false))
  674. Diag(IILoc, IsTemplateName ? diag::err_no_member_template
  675. : diag::err_typename_nested_not_found)
  676. << II << DC << SS->getRange();
  677. else if (isDependentScopeSpecifier(*SS)) {
  678. unsigned DiagID = diag::err_typename_missing;
  679. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  680. DiagID = diag::ext_typename_missing;
  681. Diag(SS->getRange().getBegin(), DiagID)
  682. << SS->getScopeRep() << II->getName()
  683. << SourceRange(SS->getRange().getBegin(), IILoc)
  684. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  685. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  686. *SS, *II, IILoc).get();
  687. } else {
  688. assert(SS && SS->isInvalid() &&
  689. "Invalid scope specifier has already been diagnosed");
  690. }
  691. }
  692. /// Determine whether the given result set contains either a type name
  693. /// or
  694. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  695. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  696. NextToken.is(tok::less);
  697. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  698. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  699. return true;
  700. if (CheckTemplate && isa<TemplateDecl>(*I))
  701. return true;
  702. }
  703. return false;
  704. }
  705. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  706. Scope *S, CXXScopeSpec &SS,
  707. IdentifierInfo *&Name,
  708. SourceLocation NameLoc) {
  709. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  710. SemaRef.LookupParsedName(R, S, &SS);
  711. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  712. StringRef FixItTagName;
  713. switch (Tag->getTagKind()) {
  714. case TTK_Class:
  715. FixItTagName = "class ";
  716. break;
  717. case TTK_Enum:
  718. FixItTagName = "enum ";
  719. break;
  720. case TTK_Struct:
  721. FixItTagName = "struct ";
  722. break;
  723. case TTK_Interface:
  724. FixItTagName = "__interface ";
  725. break;
  726. case TTK_Union:
  727. FixItTagName = "union ";
  728. break;
  729. }
  730. StringRef TagName = FixItTagName.drop_back();
  731. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  732. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  733. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  734. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  735. I != IEnd; ++I)
  736. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  737. << Name << TagName;
  738. // Replace lookup results with just the tag decl.
  739. Result.clear(Sema::LookupTagName);
  740. SemaRef.LookupParsedName(Result, S, &SS);
  741. return true;
  742. }
  743. return false;
  744. }
  745. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  746. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  747. QualType T, SourceLocation NameLoc) {
  748. ASTContext &Context = S.Context;
  749. TypeLocBuilder Builder;
  750. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  751. T = S.getElaboratedType(ETK_None, SS, T);
  752. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  753. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  754. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  755. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  756. }
  757. Sema::NameClassification
  758. Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
  759. SourceLocation NameLoc, const Token &NextToken,
  760. bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) {
  761. DeclarationNameInfo NameInfo(Name, NameLoc);
  762. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  763. if (NextToken.is(tok::coloncolon)) {
  764. NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
  765. BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
  766. } else if (getLangOpts().CPlusPlus && SS.isSet() &&
  767. isCurrentClassName(*Name, S, &SS)) {
  768. // Per [class.qual]p2, this names the constructors of SS, not the
  769. // injected-class-name. We don't have a classification for that.
  770. // There's not much point caching this result, since the parser
  771. // will reject it later.
  772. return NameClassification::Unknown();
  773. }
  774. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  775. LookupParsedName(Result, S, &SS, !CurMethod);
  776. // For unqualified lookup in a class template in MSVC mode, look into
  777. // dependent base classes where the primary class template is known.
  778. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  779. if (ParsedType TypeInBase =
  780. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  781. return TypeInBase;
  782. }
  783. // Perform lookup for Objective-C instance variables (including automatically
  784. // synthesized instance variables), if we're in an Objective-C method.
  785. // FIXME: This lookup really, really needs to be folded in to the normal
  786. // unqualified lookup mechanism.
  787. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  788. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  789. if (E.get() || E.isInvalid())
  790. return E;
  791. }
  792. bool SecondTry = false;
  793. bool IsFilteredTemplateName = false;
  794. Corrected:
  795. switch (Result.getResultKind()) {
  796. case LookupResult::NotFound:
  797. // If an unqualified-id is followed by a '(', then we have a function
  798. // call.
  799. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  800. // In C++, this is an ADL-only call.
  801. // FIXME: Reference?
  802. if (getLangOpts().CPlusPlus)
  803. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  804. // C90 6.3.2.2:
  805. // If the expression that precedes the parenthesized argument list in a
  806. // function call consists solely of an identifier, and if no
  807. // declaration is visible for this identifier, the identifier is
  808. // implicitly declared exactly as if, in the innermost block containing
  809. // the function call, the declaration
  810. //
  811. // extern int identifier ();
  812. //
  813. // appeared.
  814. //
  815. // We also allow this in C99 as an extension.
  816. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  817. Result.addDecl(D);
  818. Result.resolveKind();
  819. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  820. }
  821. }
  822. if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
  823. // In C++20 onwards, this could be an ADL-only call to a function
  824. // template, and we're required to assume that this is a template name.
  825. //
  826. // FIXME: Find a way to still do typo correction in this case.
  827. TemplateName Template =
  828. Context.getAssumedTemplateName(NameInfo.getName());
  829. return NameClassification::UndeclaredTemplate(Template);
  830. }
  831. // In C, we first see whether there is a tag type by the same name, in
  832. // which case it's likely that the user just forgot to write "enum",
  833. // "struct", or "union".
  834. if (!getLangOpts().CPlusPlus && !SecondTry &&
  835. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  836. break;
  837. }
  838. // Perform typo correction to determine if there is another name that is
  839. // close to this name.
  840. if (!SecondTry && CCC) {
  841. SecondTry = true;
  842. if (TypoCorrection Corrected =
  843. CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
  844. &SS, *CCC, CTK_ErrorRecovery)) {
  845. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  846. unsigned QualifiedDiag = diag::err_no_member_suggest;
  847. NamedDecl *FirstDecl = Corrected.getFoundDecl();
  848. NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
  849. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  850. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  851. UnqualifiedDiag = diag::err_no_template_suggest;
  852. QualifiedDiag = diag::err_no_member_template_suggest;
  853. } else if (UnderlyingFirstDecl &&
  854. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  855. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  856. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  857. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  858. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  859. }
  860. if (SS.isEmpty()) {
  861. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  862. } else {// FIXME: is this even reachable? Test it.
  863. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  864. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  865. Name->getName().equals(CorrectedStr);
  866. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  867. << Name << computeDeclContext(SS, false)
  868. << DroppedSpecifier << SS.getRange());
  869. }
  870. // Update the name, so that the caller has the new name.
  871. Name = Corrected.getCorrectionAsIdentifierInfo();
  872. // Typo correction corrected to a keyword.
  873. if (Corrected.isKeyword())
  874. return Name;
  875. // Also update the LookupResult...
  876. // FIXME: This should probably go away at some point
  877. Result.clear();
  878. Result.setLookupName(Corrected.getCorrection());
  879. if (FirstDecl)
  880. Result.addDecl(FirstDecl);
  881. // If we found an Objective-C instance variable, let
  882. // LookupInObjCMethod build the appropriate expression to
  883. // reference the ivar.
  884. // FIXME: This is a gross hack.
  885. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  886. Result.clear();
  887. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  888. return E;
  889. }
  890. goto Corrected;
  891. }
  892. }
  893. // We failed to correct; just fall through and let the parser deal with it.
  894. Result.suppressDiagnostics();
  895. return NameClassification::Unknown();
  896. case LookupResult::NotFoundInCurrentInstantiation: {
  897. // We performed name lookup into the current instantiation, and there were
  898. // dependent bases, so we treat this result the same way as any other
  899. // dependent nested-name-specifier.
  900. // C++ [temp.res]p2:
  901. // A name used in a template declaration or definition and that is
  902. // dependent on a template-parameter is assumed not to name a type
  903. // unless the applicable name lookup finds a type name or the name is
  904. // qualified by the keyword typename.
  905. //
  906. // FIXME: If the next token is '<', we might want to ask the parser to
  907. // perform some heroics to see if we actually have a
  908. // template-argument-list, which would indicate a missing 'template'
  909. // keyword here.
  910. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  911. NameInfo, IsAddressOfOperand,
  912. /*TemplateArgs=*/nullptr);
  913. }
  914. case LookupResult::Found:
  915. case LookupResult::FoundOverloaded:
  916. case LookupResult::FoundUnresolvedValue:
  917. break;
  918. case LookupResult::Ambiguous:
  919. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  920. hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
  921. /*AllowDependent=*/false)) {
  922. // C++ [temp.local]p3:
  923. // A lookup that finds an injected-class-name (10.2) can result in an
  924. // ambiguity in certain cases (for example, if it is found in more than
  925. // one base class). If all of the injected-class-names that are found
  926. // refer to specializations of the same class template, and if the name
  927. // is followed by a template-argument-list, the reference refers to the
  928. // class template itself and not a specialization thereof, and is not
  929. // ambiguous.
  930. //
  931. // This filtering can make an ambiguous result into an unambiguous one,
  932. // so try again after filtering out template names.
  933. FilterAcceptableTemplateNames(Result);
  934. if (!Result.isAmbiguous()) {
  935. IsFilteredTemplateName = true;
  936. break;
  937. }
  938. }
  939. // Diagnose the ambiguity and return an error.
  940. return NameClassification::Error();
  941. }
  942. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  943. (IsFilteredTemplateName ||
  944. hasAnyAcceptableTemplateNames(
  945. Result, /*AllowFunctionTemplates=*/true,
  946. /*AllowDependent=*/false,
  947. /*AllowNonTemplateFunctions*/ !SS.isSet() &&
  948. getLangOpts().CPlusPlus2a))) {
  949. // C++ [temp.names]p3:
  950. // After name lookup (3.4) finds that a name is a template-name or that
  951. // an operator-function-id or a literal- operator-id refers to a set of
  952. // overloaded functions any member of which is a function template if
  953. // this is followed by a <, the < is always taken as the delimiter of a
  954. // template-argument-list and never as the less-than operator.
  955. // C++2a [temp.names]p2:
  956. // A name is also considered to refer to a template if it is an
  957. // unqualified-id followed by a < and name lookup finds either one
  958. // or more functions or finds nothing.
  959. if (!IsFilteredTemplateName)
  960. FilterAcceptableTemplateNames(Result);
  961. bool IsFunctionTemplate;
  962. bool IsVarTemplate;
  963. TemplateName Template;
  964. if (Result.end() - Result.begin() > 1) {
  965. IsFunctionTemplate = true;
  966. Template = Context.getOverloadedTemplateName(Result.begin(),
  967. Result.end());
  968. } else if (!Result.empty()) {
  969. auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
  970. *Result.begin(), /*AllowFunctionTemplates=*/true,
  971. /*AllowDependent=*/false));
  972. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  973. IsVarTemplate = isa<VarTemplateDecl>(TD);
  974. if (SS.isSet() && !SS.isInvalid())
  975. Template =
  976. Context.getQualifiedTemplateName(SS.getScopeRep(),
  977. /*TemplateKeyword=*/false, TD);
  978. else
  979. Template = TemplateName(TD);
  980. } else {
  981. // All results were non-template functions. This is a function template
  982. // name.
  983. IsFunctionTemplate = true;
  984. Template = Context.getAssumedTemplateName(NameInfo.getName());
  985. }
  986. if (IsFunctionTemplate) {
  987. // Function templates always go through overload resolution, at which
  988. // point we'll perform the various checks (e.g., accessibility) we need
  989. // to based on which function we selected.
  990. Result.suppressDiagnostics();
  991. return NameClassification::FunctionTemplate(Template);
  992. }
  993. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  994. : NameClassification::TypeTemplate(Template);
  995. }
  996. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  997. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  998. DiagnoseUseOfDecl(Type, NameLoc);
  999. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  1000. QualType T = Context.getTypeDeclType(Type);
  1001. if (SS.isNotEmpty())
  1002. return buildNestedType(*this, SS, T, NameLoc);
  1003. return ParsedType::make(T);
  1004. }
  1005. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  1006. if (!Class) {
  1007. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  1008. if (ObjCCompatibleAliasDecl *Alias =
  1009. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  1010. Class = Alias->getClassInterface();
  1011. }
  1012. if (Class) {
  1013. DiagnoseUseOfDecl(Class, NameLoc);
  1014. if (NextToken.is(tok::period)) {
  1015. // Interface. <something> is parsed as a property reference expression.
  1016. // Just return "unknown" as a fall-through for now.
  1017. Result.suppressDiagnostics();
  1018. return NameClassification::Unknown();
  1019. }
  1020. QualType T = Context.getObjCInterfaceType(Class);
  1021. return ParsedType::make(T);
  1022. }
  1023. // We can have a type template here if we're classifying a template argument.
  1024. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
  1025. !isa<VarTemplateDecl>(FirstDecl))
  1026. return NameClassification::TypeTemplate(
  1027. TemplateName(cast<TemplateDecl>(FirstDecl)));
  1028. // Check for a tag type hidden by a non-type decl in a few cases where it
  1029. // seems likely a type is wanted instead of the non-type that was found.
  1030. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  1031. if ((NextToken.is(tok::identifier) ||
  1032. (NextIsOp &&
  1033. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  1034. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  1035. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  1036. DiagnoseUseOfDecl(Type, NameLoc);
  1037. QualType T = Context.getTypeDeclType(Type);
  1038. if (SS.isNotEmpty())
  1039. return buildNestedType(*this, SS, T, NameLoc);
  1040. return ParsedType::make(T);
  1041. }
  1042. if (FirstDecl->isCXXClassMember())
  1043. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  1044. nullptr, S);
  1045. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1046. return BuildDeclarationNameExpr(SS, Result, ADL);
  1047. }
  1048. Sema::TemplateNameKindForDiagnostics
  1049. Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
  1050. auto *TD = Name.getAsTemplateDecl();
  1051. if (!TD)
  1052. return TemplateNameKindForDiagnostics::DependentTemplate;
  1053. if (isa<ClassTemplateDecl>(TD))
  1054. return TemplateNameKindForDiagnostics::ClassTemplate;
  1055. if (isa<FunctionTemplateDecl>(TD))
  1056. return TemplateNameKindForDiagnostics::FunctionTemplate;
  1057. if (isa<VarTemplateDecl>(TD))
  1058. return TemplateNameKindForDiagnostics::VarTemplate;
  1059. if (isa<TypeAliasTemplateDecl>(TD))
  1060. return TemplateNameKindForDiagnostics::AliasTemplate;
  1061. if (isa<TemplateTemplateParmDecl>(TD))
  1062. return TemplateNameKindForDiagnostics::TemplateTemplateParam;
  1063. if (isa<ConceptDecl>(TD))
  1064. return TemplateNameKindForDiagnostics::Concept;
  1065. return TemplateNameKindForDiagnostics::DependentTemplate;
  1066. }
  1067. // Determines the context to return to after temporarily entering a
  1068. // context. This depends in an unnecessarily complicated way on the
  1069. // exact ordering of callbacks from the parser.
  1070. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  1071. // Functions defined inline within classes aren't parsed until we've
  1072. // finished parsing the top-level class, so the top-level class is
  1073. // the context we'll need to return to.
  1074. // A Lambda call operator whose parent is a class must not be treated
  1075. // as an inline member function. A Lambda can be used legally
  1076. // either as an in-class member initializer or a default argument. These
  1077. // are parsed once the class has been marked complete and so the containing
  1078. // context would be the nested class (when the lambda is defined in one);
  1079. // If the class is not complete, then the lambda is being used in an
  1080. // ill-formed fashion (such as to specify the width of a bit-field, or
  1081. // in an array-bound) - in which case we still want to return the
  1082. // lexically containing DC (which could be a nested class).
  1083. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  1084. DC = DC->getLexicalParent();
  1085. // A function not defined within a class will always return to its
  1086. // lexical context.
  1087. if (!isa<CXXRecordDecl>(DC))
  1088. return DC;
  1089. // A C++ inline method/friend is parsed *after* the topmost class
  1090. // it was declared in is fully parsed ("complete"); the topmost
  1091. // class is the context we need to return to.
  1092. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  1093. DC = RD;
  1094. // Return the declaration context of the topmost class the inline method is
  1095. // declared in.
  1096. return DC;
  1097. }
  1098. return DC->getLexicalParent();
  1099. }
  1100. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  1101. assert(getContainingDC(DC) == CurContext &&
  1102. "The next DeclContext should be lexically contained in the current one.");
  1103. CurContext = DC;
  1104. S->setEntity(DC);
  1105. }
  1106. void Sema::PopDeclContext() {
  1107. assert(CurContext && "DeclContext imbalance!");
  1108. CurContext = getContainingDC(CurContext);
  1109. assert(CurContext && "Popped translation unit!");
  1110. }
  1111. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  1112. Decl *D) {
  1113. // Unlike PushDeclContext, the context to which we return is not necessarily
  1114. // the containing DC of TD, because the new context will be some pre-existing
  1115. // TagDecl definition instead of a fresh one.
  1116. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  1117. CurContext = cast<TagDecl>(D)->getDefinition();
  1118. assert(CurContext && "skipping definition of undefined tag");
  1119. // Start lookups from the parent of the current context; we don't want to look
  1120. // into the pre-existing complete definition.
  1121. S->setEntity(CurContext->getLookupParent());
  1122. return Result;
  1123. }
  1124. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  1125. CurContext = static_cast<decltype(CurContext)>(Context);
  1126. }
  1127. /// EnterDeclaratorContext - Used when we must lookup names in the context
  1128. /// of a declarator's nested name specifier.
  1129. ///
  1130. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  1131. // C++0x [basic.lookup.unqual]p13:
  1132. // A name used in the definition of a static data member of class
  1133. // X (after the qualified-id of the static member) is looked up as
  1134. // if the name was used in a member function of X.
  1135. // C++0x [basic.lookup.unqual]p14:
  1136. // If a variable member of a namespace is defined outside of the
  1137. // scope of its namespace then any name used in the definition of
  1138. // the variable member (after the declarator-id) is looked up as
  1139. // if the definition of the variable member occurred in its
  1140. // namespace.
  1141. // Both of these imply that we should push a scope whose context
  1142. // is the semantic context of the declaration. We can't use
  1143. // PushDeclContext here because that context is not necessarily
  1144. // lexically contained in the current context. Fortunately,
  1145. // the containing scope should have the appropriate information.
  1146. assert(!S->getEntity() && "scope already has entity");
  1147. #ifndef NDEBUG
  1148. Scope *Ancestor = S->getParent();
  1149. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1150. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1151. #endif
  1152. CurContext = DC;
  1153. S->setEntity(DC);
  1154. }
  1155. void Sema::ExitDeclaratorContext(Scope *S) {
  1156. assert(S->getEntity() == CurContext && "Context imbalance!");
  1157. // Switch back to the lexical context. The safety of this is
  1158. // enforced by an assert in EnterDeclaratorContext.
  1159. Scope *Ancestor = S->getParent();
  1160. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1161. CurContext = Ancestor->getEntity();
  1162. // We don't need to do anything with the scope, which is going to
  1163. // disappear.
  1164. }
  1165. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1166. // We assume that the caller has already called
  1167. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1168. FunctionDecl *FD = D->getAsFunction();
  1169. if (!FD)
  1170. return;
  1171. // Same implementation as PushDeclContext, but enters the context
  1172. // from the lexical parent, rather than the top-level class.
  1173. assert(CurContext == FD->getLexicalParent() &&
  1174. "The next DeclContext should be lexically contained in the current one.");
  1175. CurContext = FD;
  1176. S->setEntity(CurContext);
  1177. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1178. ParmVarDecl *Param = FD->getParamDecl(P);
  1179. // If the parameter has an identifier, then add it to the scope
  1180. if (Param->getIdentifier()) {
  1181. S->AddDecl(Param);
  1182. IdResolver.AddDecl(Param);
  1183. }
  1184. }
  1185. }
  1186. void Sema::ActOnExitFunctionContext() {
  1187. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1188. // rather than the top-level class.
  1189. assert(CurContext && "DeclContext imbalance!");
  1190. CurContext = CurContext->getLexicalParent();
  1191. assert(CurContext && "Popped translation unit!");
  1192. }
  1193. /// Determine whether we allow overloading of the function
  1194. /// PrevDecl with another declaration.
  1195. ///
  1196. /// This routine determines whether overloading is possible, not
  1197. /// whether some new function is actually an overload. It will return
  1198. /// true in C++ (where we can always provide overloads) or, as an
  1199. /// extension, in C when the previous function is already an
  1200. /// overloaded function declaration or has the "overloadable"
  1201. /// attribute.
  1202. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1203. ASTContext &Context,
  1204. const FunctionDecl *New) {
  1205. if (Context.getLangOpts().CPlusPlus)
  1206. return true;
  1207. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1208. return true;
  1209. return Previous.getResultKind() == LookupResult::Found &&
  1210. (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
  1211. New->hasAttr<OverloadableAttr>());
  1212. }
  1213. /// Add this decl to the scope shadowed decl chains.
  1214. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1215. // Move up the scope chain until we find the nearest enclosing
  1216. // non-transparent context. The declaration will be introduced into this
  1217. // scope.
  1218. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1219. S = S->getParent();
  1220. // Add scoped declarations into their context, so that they can be
  1221. // found later. Declarations without a context won't be inserted
  1222. // into any context.
  1223. if (AddToContext)
  1224. CurContext->addDecl(D);
  1225. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1226. // are function-local declarations.
  1227. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1228. !D->getDeclContext()->getRedeclContext()->Equals(
  1229. D->getLexicalDeclContext()->getRedeclContext()) &&
  1230. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1231. return;
  1232. // Template instantiations should also not be pushed into scope.
  1233. if (isa<FunctionDecl>(D) &&
  1234. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1235. return;
  1236. // If this replaces anything in the current scope,
  1237. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1238. IEnd = IdResolver.end();
  1239. for (; I != IEnd; ++I) {
  1240. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1241. S->RemoveDecl(*I);
  1242. IdResolver.RemoveDecl(*I);
  1243. // Should only need to replace one decl.
  1244. break;
  1245. }
  1246. }
  1247. S->AddDecl(D);
  1248. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1249. // Implicitly-generated labels may end up getting generated in an order that
  1250. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1251. // the label at the appropriate place in the identifier chain.
  1252. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1253. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1254. if (IDC == CurContext) {
  1255. if (!S->isDeclScope(*I))
  1256. continue;
  1257. } else if (IDC->Encloses(CurContext))
  1258. break;
  1259. }
  1260. IdResolver.InsertDeclAfter(I, D);
  1261. } else {
  1262. IdResolver.AddDecl(D);
  1263. }
  1264. }
  1265. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1266. bool AllowInlineNamespace) {
  1267. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1268. }
  1269. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1270. DeclContext *TargetDC = DC->getPrimaryContext();
  1271. do {
  1272. if (DeclContext *ScopeDC = S->getEntity())
  1273. if (ScopeDC->getPrimaryContext() == TargetDC)
  1274. return S;
  1275. } while ((S = S->getParent()));
  1276. return nullptr;
  1277. }
  1278. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1279. DeclContext*,
  1280. ASTContext&);
  1281. /// Filters out lookup results that don't fall within the given scope
  1282. /// as determined by isDeclInScope.
  1283. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1284. bool ConsiderLinkage,
  1285. bool AllowInlineNamespace) {
  1286. LookupResult::Filter F = R.makeFilter();
  1287. while (F.hasNext()) {
  1288. NamedDecl *D = F.next();
  1289. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1290. continue;
  1291. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1292. continue;
  1293. F.erase();
  1294. }
  1295. F.done();
  1296. }
  1297. /// We've determined that \p New is a redeclaration of \p Old. Check that they
  1298. /// have compatible owning modules.
  1299. bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
  1300. // FIXME: The Modules TS is not clear about how friend declarations are
  1301. // to be treated. It's not meaningful to have different owning modules for
  1302. // linkage in redeclarations of the same entity, so for now allow the
  1303. // redeclaration and change the owning modules to match.
  1304. if (New->getFriendObjectKind() &&
  1305. Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
  1306. New->setLocalOwningModule(Old->getOwningModule());
  1307. makeMergedDefinitionVisible(New);
  1308. return false;
  1309. }
  1310. Module *NewM = New->getOwningModule();
  1311. Module *OldM = Old->getOwningModule();
  1312. if (NewM && NewM->Kind == Module::PrivateModuleFragment)
  1313. NewM = NewM->Parent;
  1314. if (OldM && OldM->Kind == Module::PrivateModuleFragment)
  1315. OldM = OldM->Parent;
  1316. if (NewM == OldM)
  1317. return false;
  1318. bool NewIsModuleInterface = NewM && NewM->isModulePurview();
  1319. bool OldIsModuleInterface = OldM && OldM->isModulePurview();
  1320. if (NewIsModuleInterface || OldIsModuleInterface) {
  1321. // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
  1322. // if a declaration of D [...] appears in the purview of a module, all
  1323. // other such declarations shall appear in the purview of the same module
  1324. Diag(New->getLocation(), diag::err_mismatched_owning_module)
  1325. << New
  1326. << NewIsModuleInterface
  1327. << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
  1328. << OldIsModuleInterface
  1329. << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
  1330. Diag(Old->getLocation(), diag::note_previous_declaration);
  1331. New->setInvalidDecl();
  1332. return true;
  1333. }
  1334. return false;
  1335. }
  1336. static bool isUsingDecl(NamedDecl *D) {
  1337. return isa<UsingShadowDecl>(D) ||
  1338. isa<UnresolvedUsingTypenameDecl>(D) ||
  1339. isa<UnresolvedUsingValueDecl>(D);
  1340. }
  1341. /// Removes using shadow declarations from the lookup results.
  1342. static void RemoveUsingDecls(LookupResult &R) {
  1343. LookupResult::Filter F = R.makeFilter();
  1344. while (F.hasNext())
  1345. if (isUsingDecl(F.next()))
  1346. F.erase();
  1347. F.done();
  1348. }
  1349. /// Check for this common pattern:
  1350. /// @code
  1351. /// class S {
  1352. /// S(const S&); // DO NOT IMPLEMENT
  1353. /// void operator=(const S&); // DO NOT IMPLEMENT
  1354. /// };
  1355. /// @endcode
  1356. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1357. // FIXME: Should check for private access too but access is set after we get
  1358. // the decl here.
  1359. if (D->doesThisDeclarationHaveABody())
  1360. return false;
  1361. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1362. return CD->isCopyConstructor();
  1363. return D->isCopyAssignmentOperator();
  1364. }
  1365. // We need this to handle
  1366. //
  1367. // typedef struct {
  1368. // void *foo() { return 0; }
  1369. // } A;
  1370. //
  1371. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1372. // for example. If 'A', foo will have external linkage. If we have '*A',
  1373. // foo will have no linkage. Since we can't know until we get to the end
  1374. // of the typedef, this function finds out if D might have non-external linkage.
  1375. // Callers should verify at the end of the TU if it D has external linkage or
  1376. // not.
  1377. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1378. const DeclContext *DC = D->getDeclContext();
  1379. while (!DC->isTranslationUnit()) {
  1380. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1381. if (!RD->hasNameForLinkage())
  1382. return true;
  1383. }
  1384. DC = DC->getParent();
  1385. }
  1386. return !D->isExternallyVisible();
  1387. }
  1388. // FIXME: This needs to be refactored; some other isInMainFile users want
  1389. // these semantics.
  1390. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1391. if (S.TUKind != TU_Complete)
  1392. return false;
  1393. return S.SourceMgr.isInMainFile(Loc);
  1394. }
  1395. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1396. assert(D);
  1397. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1398. return false;
  1399. // Ignore all entities declared within templates, and out-of-line definitions
  1400. // of members of class templates.
  1401. if (D->getDeclContext()->isDependentContext() ||
  1402. D->getLexicalDeclContext()->isDependentContext())
  1403. return false;
  1404. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1405. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1406. return false;
  1407. // A non-out-of-line declaration of a member specialization was implicitly
  1408. // instantiated; it's the out-of-line declaration that we're interested in.
  1409. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1410. FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
  1411. return false;
  1412. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1413. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1414. return false;
  1415. } else {
  1416. // 'static inline' functions are defined in headers; don't warn.
  1417. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1418. return false;
  1419. }
  1420. if (FD->doesThisDeclarationHaveABody() &&
  1421. Context.DeclMustBeEmitted(FD))
  1422. return false;
  1423. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1424. // Constants and utility variables are defined in headers with internal
  1425. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1426. // like "inline".)
  1427. if (!isMainFileLoc(*this, VD->getLocation()))
  1428. return false;
  1429. if (Context.DeclMustBeEmitted(VD))
  1430. return false;
  1431. if (VD->isStaticDataMember() &&
  1432. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1433. return false;
  1434. if (VD->isStaticDataMember() &&
  1435. VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1436. VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
  1437. return false;
  1438. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1439. return false;
  1440. } else {
  1441. return false;
  1442. }
  1443. // Only warn for unused decls internal to the translation unit.
  1444. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1445. // for inline functions defined in the main source file, for instance.
  1446. return mightHaveNonExternalLinkage(D);
  1447. }
  1448. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1449. if (!D)
  1450. return;
  1451. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1452. const FunctionDecl *First = FD->getFirstDecl();
  1453. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1454. return; // First should already be in the vector.
  1455. }
  1456. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1457. const VarDecl *First = VD->getFirstDecl();
  1458. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1459. return; // First should already be in the vector.
  1460. }
  1461. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1462. UnusedFileScopedDecls.push_back(D);
  1463. }
  1464. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1465. if (D->isInvalidDecl())
  1466. return false;
  1467. bool Referenced = false;
  1468. if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
  1469. // For a decomposition declaration, warn if none of the bindings are
  1470. // referenced, instead of if the variable itself is referenced (which
  1471. // it is, by the bindings' expressions).
  1472. for (auto *BD : DD->bindings()) {
  1473. if (BD->isReferenced()) {
  1474. Referenced = true;
  1475. break;
  1476. }
  1477. }
  1478. } else if (!D->getDeclName()) {
  1479. return false;
  1480. } else if (D->isReferenced() || D->isUsed()) {
  1481. Referenced = true;
  1482. }
  1483. if (Referenced || D->hasAttr<UnusedAttr>() ||
  1484. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1485. return false;
  1486. if (isa<LabelDecl>(D))
  1487. return true;
  1488. // Except for labels, we only care about unused decls that are local to
  1489. // functions.
  1490. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1491. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1492. // For dependent types, the diagnostic is deferred.
  1493. WithinFunction =
  1494. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1495. if (!WithinFunction)
  1496. return false;
  1497. if (isa<TypedefNameDecl>(D))
  1498. return true;
  1499. // White-list anything that isn't a local variable.
  1500. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1501. return false;
  1502. // Types of valid local variables should be complete, so this should succeed.
  1503. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1504. // White-list anything with an __attribute__((unused)) type.
  1505. const auto *Ty = VD->getType().getTypePtr();
  1506. // Only look at the outermost level of typedef.
  1507. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1508. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1509. return false;
  1510. }
  1511. // If we failed to complete the type for some reason, or if the type is
  1512. // dependent, don't diagnose the variable.
  1513. if (Ty->isIncompleteType() || Ty->isDependentType())
  1514. return false;
  1515. // Look at the element type to ensure that the warning behaviour is
  1516. // consistent for both scalars and arrays.
  1517. Ty = Ty->getBaseElementTypeUnsafe();
  1518. if (const TagType *TT = Ty->getAs<TagType>()) {
  1519. const TagDecl *Tag = TT->getDecl();
  1520. if (Tag->hasAttr<UnusedAttr>())
  1521. return false;
  1522. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1523. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1524. return false;
  1525. if (const Expr *Init = VD->getInit()) {
  1526. if (const ExprWithCleanups *Cleanups =
  1527. dyn_cast<ExprWithCleanups>(Init))
  1528. Init = Cleanups->getSubExpr();
  1529. const CXXConstructExpr *Construct =
  1530. dyn_cast<CXXConstructExpr>(Init);
  1531. if (Construct && !Construct->isElidable()) {
  1532. CXXConstructorDecl *CD = Construct->getConstructor();
  1533. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
  1534. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  1535. return false;
  1536. }
  1537. }
  1538. }
  1539. }
  1540. // TODO: __attribute__((unused)) templates?
  1541. }
  1542. return true;
  1543. }
  1544. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1545. FixItHint &Hint) {
  1546. if (isa<LabelDecl>(D)) {
  1547. SourceLocation AfterColon = Lexer::findLocationAfterToken(
  1548. D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
  1549. true);
  1550. if (AfterColon.isInvalid())
  1551. return;
  1552. Hint = FixItHint::CreateRemoval(
  1553. CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
  1554. }
  1555. }
  1556. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1557. if (D->getTypeForDecl()->isDependentType())
  1558. return;
  1559. for (auto *TmpD : D->decls()) {
  1560. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1561. DiagnoseUnusedDecl(T);
  1562. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1563. DiagnoseUnusedNestedTypedefs(R);
  1564. }
  1565. }
  1566. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1567. /// unless they are marked attr(unused).
  1568. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1569. if (!ShouldDiagnoseUnusedDecl(D))
  1570. return;
  1571. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1572. // typedefs can be referenced later on, so the diagnostics are emitted
  1573. // at end-of-translation-unit.
  1574. UnusedLocalTypedefNameCandidates.insert(TD);
  1575. return;
  1576. }
  1577. FixItHint Hint;
  1578. GenerateFixForUnusedDecl(D, Context, Hint);
  1579. unsigned DiagID;
  1580. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1581. DiagID = diag::warn_unused_exception_param;
  1582. else if (isa<LabelDecl>(D))
  1583. DiagID = diag::warn_unused_label;
  1584. else
  1585. DiagID = diag::warn_unused_variable;
  1586. Diag(D->getLocation(), DiagID) << D << Hint;
  1587. }
  1588. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1589. // Verify that we have no forward references left. If so, there was a goto
  1590. // or address of a label taken, but no definition of it. Label fwd
  1591. // definitions are indicated with a null substmt which is also not a resolved
  1592. // MS inline assembly label name.
  1593. bool Diagnose = false;
  1594. if (L->isMSAsmLabel())
  1595. Diagnose = !L->isResolvedMSAsmLabel();
  1596. else
  1597. Diagnose = L->getStmt() == nullptr;
  1598. if (Diagnose)
  1599. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1600. }
  1601. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1602. S->mergeNRVOIntoParent();
  1603. if (S->decl_empty()) return;
  1604. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1605. "Scope shouldn't contain decls!");
  1606. for (auto *TmpD : S->decls()) {
  1607. assert(TmpD && "This decl didn't get pushed??");
  1608. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1609. NamedDecl *D = cast<NamedDecl>(TmpD);
  1610. // Diagnose unused variables in this scope.
  1611. if (!S->hasUnrecoverableErrorOccurred()) {
  1612. DiagnoseUnusedDecl(D);
  1613. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1614. DiagnoseUnusedNestedTypedefs(RD);
  1615. }
  1616. if (!D->getDeclName()) continue;
  1617. // If this was a forward reference to a label, verify it was defined.
  1618. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1619. CheckPoppedLabel(LD, *this);
  1620. // Remove this name from our lexical scope, and warn on it if we haven't
  1621. // already.
  1622. IdResolver.RemoveDecl(D);
  1623. auto ShadowI = ShadowingDecls.find(D);
  1624. if (ShadowI != ShadowingDecls.end()) {
  1625. if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
  1626. Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
  1627. << D << FD << FD->getParent();
  1628. Diag(FD->getLocation(), diag::note_previous_declaration);
  1629. }
  1630. ShadowingDecls.erase(ShadowI);
  1631. }
  1632. }
  1633. }
  1634. /// Look for an Objective-C class in the translation unit.
  1635. ///
  1636. /// \param Id The name of the Objective-C class we're looking for. If
  1637. /// typo-correction fixes this name, the Id will be updated
  1638. /// to the fixed name.
  1639. ///
  1640. /// \param IdLoc The location of the name in the translation unit.
  1641. ///
  1642. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1643. /// if there is no class with the given name.
  1644. ///
  1645. /// \returns The declaration of the named Objective-C class, or NULL if the
  1646. /// class could not be found.
  1647. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1648. SourceLocation IdLoc,
  1649. bool DoTypoCorrection) {
  1650. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1651. // creation from this context.
  1652. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1653. if (!IDecl && DoTypoCorrection) {
  1654. // Perform typo correction at the given location, but only if we
  1655. // find an Objective-C class name.
  1656. DeclFilterCCC<ObjCInterfaceDecl> CCC{};
  1657. if (TypoCorrection C =
  1658. CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
  1659. TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
  1660. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1661. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1662. Id = IDecl->getIdentifier();
  1663. }
  1664. }
  1665. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1666. // This routine must always return a class definition, if any.
  1667. if (Def && Def->getDefinition())
  1668. Def = Def->getDefinition();
  1669. return Def;
  1670. }
  1671. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1672. /// from S, where a non-field would be declared. This routine copes
  1673. /// with the difference between C and C++ scoping rules in structs and
  1674. /// unions. For example, the following code is well-formed in C but
  1675. /// ill-formed in C++:
  1676. /// @code
  1677. /// struct S6 {
  1678. /// enum { BAR } e;
  1679. /// };
  1680. ///
  1681. /// void test_S6() {
  1682. /// struct S6 a;
  1683. /// a.e = BAR;
  1684. /// }
  1685. /// @endcode
  1686. /// For the declaration of BAR, this routine will return a different
  1687. /// scope. The scope S will be the scope of the unnamed enumeration
  1688. /// within S6. In C++, this routine will return the scope associated
  1689. /// with S6, because the enumeration's scope is a transparent
  1690. /// context but structures can contain non-field names. In C, this
  1691. /// routine will return the translation unit scope, since the
  1692. /// enumeration's scope is a transparent context and structures cannot
  1693. /// contain non-field names.
  1694. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1695. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1696. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1697. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1698. S = S->getParent();
  1699. return S;
  1700. }
  1701. /// Looks up the declaration of "struct objc_super" and
  1702. /// saves it for later use in building builtin declaration of
  1703. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1704. /// pre-existing declaration exists no action takes place.
  1705. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1706. IdentifierInfo *II) {
  1707. if (!II->isStr("objc_msgSendSuper"))
  1708. return;
  1709. ASTContext &Context = ThisSema.Context;
  1710. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1711. SourceLocation(), Sema::LookupTagName);
  1712. ThisSema.LookupName(Result, S);
  1713. if (Result.getResultKind() == LookupResult::Found)
  1714. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1715. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1716. }
  1717. static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
  1718. ASTContext::GetBuiltinTypeError Error) {
  1719. switch (Error) {
  1720. case ASTContext::GE_None:
  1721. return "";
  1722. case ASTContext::GE_Missing_type:
  1723. return BuiltinInfo.getHeaderName(ID);
  1724. case ASTContext::GE_Missing_stdio:
  1725. return "stdio.h";
  1726. case ASTContext::GE_Missing_setjmp:
  1727. return "setjmp.h";
  1728. case ASTContext::GE_Missing_ucontext:
  1729. return "ucontext.h";
  1730. }
  1731. llvm_unreachable("unhandled error kind");
  1732. }
  1733. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1734. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1735. /// if we're creating this built-in in anticipation of redeclaring the
  1736. /// built-in.
  1737. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1738. Scope *S, bool ForRedeclaration,
  1739. SourceLocation Loc) {
  1740. LookupPredefedObjCSuperType(*this, S, II);
  1741. ASTContext::GetBuiltinTypeError Error;
  1742. QualType R = Context.GetBuiltinType(ID, Error);
  1743. if (Error) {
  1744. if (ForRedeclaration)
  1745. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1746. << getHeaderName(Context.BuiltinInfo, ID, Error)
  1747. << Context.BuiltinInfo.getName(ID);
  1748. return nullptr;
  1749. }
  1750. if (!ForRedeclaration &&
  1751. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1752. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1753. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1754. << Context.BuiltinInfo.getName(ID) << R;
  1755. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1756. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1757. Diag(Loc, diag::note_include_header_or_declare)
  1758. << Context.BuiltinInfo.getHeaderName(ID)
  1759. << Context.BuiltinInfo.getName(ID);
  1760. }
  1761. if (R.isNull())
  1762. return nullptr;
  1763. DeclContext *Parent = Context.getTranslationUnitDecl();
  1764. if (getLangOpts().CPlusPlus) {
  1765. LinkageSpecDecl *CLinkageDecl =
  1766. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1767. LinkageSpecDecl::lang_c, false);
  1768. CLinkageDecl->setImplicit();
  1769. Parent->addDecl(CLinkageDecl);
  1770. Parent = CLinkageDecl;
  1771. }
  1772. FunctionDecl *New = FunctionDecl::Create(Context,
  1773. Parent,
  1774. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1775. SC_Extern,
  1776. false,
  1777. R->isFunctionProtoType());
  1778. New->setImplicit();
  1779. // Create Decl objects for each parameter, adding them to the
  1780. // FunctionDecl.
  1781. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1782. SmallVector<ParmVarDecl*, 16> Params;
  1783. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1784. ParmVarDecl *parm =
  1785. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1786. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1787. SC_None, nullptr);
  1788. parm->setScopeInfo(0, i);
  1789. Params.push_back(parm);
  1790. }
  1791. New->setParams(Params);
  1792. }
  1793. AddKnownFunctionAttributes(New);
  1794. RegisterLocallyScopedExternCDecl(New, S);
  1795. // TUScope is the translation-unit scope to insert this function into.
  1796. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1797. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1798. // entirely, but we're not there yet.
  1799. DeclContext *SavedContext = CurContext;
  1800. CurContext = Parent;
  1801. PushOnScopeChains(New, TUScope);
  1802. CurContext = SavedContext;
  1803. return New;
  1804. }
  1805. /// Typedef declarations don't have linkage, but they still denote the same
  1806. /// entity if their types are the same.
  1807. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1808. /// isSameEntity.
  1809. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1810. TypedefNameDecl *Decl,
  1811. LookupResult &Previous) {
  1812. // This is only interesting when modules are enabled.
  1813. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1814. return;
  1815. // Empty sets are uninteresting.
  1816. if (Previous.empty())
  1817. return;
  1818. LookupResult::Filter Filter = Previous.makeFilter();
  1819. while (Filter.hasNext()) {
  1820. NamedDecl *Old = Filter.next();
  1821. // Non-hidden declarations are never ignored.
  1822. if (S.isVisible(Old))
  1823. continue;
  1824. // Declarations of the same entity are not ignored, even if they have
  1825. // different linkages.
  1826. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1827. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1828. Decl->getUnderlyingType()))
  1829. continue;
  1830. // If both declarations give a tag declaration a typedef name for linkage
  1831. // purposes, then they declare the same entity.
  1832. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1833. Decl->getAnonDeclWithTypedefName())
  1834. continue;
  1835. }
  1836. Filter.erase();
  1837. }
  1838. Filter.done();
  1839. }
  1840. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1841. QualType OldType;
  1842. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1843. OldType = OldTypedef->getUnderlyingType();
  1844. else
  1845. OldType = Context.getTypeDeclType(Old);
  1846. QualType NewType = New->getUnderlyingType();
  1847. if (NewType->isVariablyModifiedType()) {
  1848. // Must not redefine a typedef with a variably-modified type.
  1849. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1850. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1851. << Kind << NewType;
  1852. if (Old->getLocation().isValid())
  1853. notePreviousDefinition(Old, New->getLocation());
  1854. New->setInvalidDecl();
  1855. return true;
  1856. }
  1857. if (OldType != NewType &&
  1858. !OldType->isDependentType() &&
  1859. !NewType->isDependentType() &&
  1860. !Context.hasSameType(OldType, NewType)) {
  1861. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1862. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1863. << Kind << NewType << OldType;
  1864. if (Old->getLocation().isValid())
  1865. notePreviousDefinition(Old, New->getLocation());
  1866. New->setInvalidDecl();
  1867. return true;
  1868. }
  1869. return false;
  1870. }
  1871. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1872. /// same name and scope as a previous declaration 'Old'. Figure out
  1873. /// how to resolve this situation, merging decls or emitting
  1874. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1875. ///
  1876. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  1877. LookupResult &OldDecls) {
  1878. // If the new decl is known invalid already, don't bother doing any
  1879. // merging checks.
  1880. if (New->isInvalidDecl()) return;
  1881. // Allow multiple definitions for ObjC built-in typedefs.
  1882. // FIXME: Verify the underlying types are equivalent!
  1883. if (getLangOpts().ObjC) {
  1884. const IdentifierInfo *TypeID = New->getIdentifier();
  1885. switch (TypeID->getLength()) {
  1886. default: break;
  1887. case 2:
  1888. {
  1889. if (!TypeID->isStr("id"))
  1890. break;
  1891. QualType T = New->getUnderlyingType();
  1892. if (!T->isPointerType())
  1893. break;
  1894. if (!T->isVoidPointerType()) {
  1895. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1896. if (!PT->isStructureType())
  1897. break;
  1898. }
  1899. Context.setObjCIdRedefinitionType(T);
  1900. // Install the built-in type for 'id', ignoring the current definition.
  1901. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1902. return;
  1903. }
  1904. case 5:
  1905. if (!TypeID->isStr("Class"))
  1906. break;
  1907. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1908. // Install the built-in type for 'Class', ignoring the current definition.
  1909. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1910. return;
  1911. case 3:
  1912. if (!TypeID->isStr("SEL"))
  1913. break;
  1914. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1915. // Install the built-in type for 'SEL', ignoring the current definition.
  1916. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1917. return;
  1918. }
  1919. // Fall through - the typedef name was not a builtin type.
  1920. }
  1921. // Verify the old decl was also a type.
  1922. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1923. if (!Old) {
  1924. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1925. << New->getDeclName();
  1926. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1927. if (OldD->getLocation().isValid())
  1928. notePreviousDefinition(OldD, New->getLocation());
  1929. return New->setInvalidDecl();
  1930. }
  1931. // If the old declaration is invalid, just give up here.
  1932. if (Old->isInvalidDecl())
  1933. return New->setInvalidDecl();
  1934. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1935. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1936. auto *NewTag = New->getAnonDeclWithTypedefName();
  1937. NamedDecl *Hidden = nullptr;
  1938. if (OldTag && NewTag &&
  1939. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1940. !hasVisibleDefinition(OldTag, &Hidden)) {
  1941. // There is a definition of this tag, but it is not visible. Use it
  1942. // instead of our tag.
  1943. New->setTypeForDecl(OldTD->getTypeForDecl());
  1944. if (OldTD->isModed())
  1945. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1946. OldTD->getUnderlyingType());
  1947. else
  1948. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1949. // Make the old tag definition visible.
  1950. makeMergedDefinitionVisible(Hidden);
  1951. // If this was an unscoped enumeration, yank all of its enumerators
  1952. // out of the scope.
  1953. if (isa<EnumDecl>(NewTag)) {
  1954. Scope *EnumScope = getNonFieldDeclScope(S);
  1955. for (auto *D : NewTag->decls()) {
  1956. auto *ED = cast<EnumConstantDecl>(D);
  1957. assert(EnumScope->isDeclScope(ED));
  1958. EnumScope->RemoveDecl(ED);
  1959. IdResolver.RemoveDecl(ED);
  1960. ED->getLexicalDeclContext()->removeDecl(ED);
  1961. }
  1962. }
  1963. }
  1964. }
  1965. // If the typedef types are not identical, reject them in all languages and
  1966. // with any extensions enabled.
  1967. if (isIncompatibleTypedef(Old, New))
  1968. return;
  1969. // The types match. Link up the redeclaration chain and merge attributes if
  1970. // the old declaration was a typedef.
  1971. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1972. New->setPreviousDecl(Typedef);
  1973. mergeDeclAttributes(New, Old);
  1974. }
  1975. if (getLangOpts().MicrosoftExt)
  1976. return;
  1977. if (getLangOpts().CPlusPlus) {
  1978. // C++ [dcl.typedef]p2:
  1979. // In a given non-class scope, a typedef specifier can be used to
  1980. // redefine the name of any type declared in that scope to refer
  1981. // to the type to which it already refers.
  1982. if (!isa<CXXRecordDecl>(CurContext))
  1983. return;
  1984. // C++0x [dcl.typedef]p4:
  1985. // In a given class scope, a typedef specifier can be used to redefine
  1986. // any class-name declared in that scope that is not also a typedef-name
  1987. // to refer to the type to which it already refers.
  1988. //
  1989. // This wording came in via DR424, which was a correction to the
  1990. // wording in DR56, which accidentally banned code like:
  1991. //
  1992. // struct S {
  1993. // typedef struct A { } A;
  1994. // };
  1995. //
  1996. // in the C++03 standard. We implement the C++0x semantics, which
  1997. // allow the above but disallow
  1998. //
  1999. // struct S {
  2000. // typedef int I;
  2001. // typedef int I;
  2002. // };
  2003. //
  2004. // since that was the intent of DR56.
  2005. if (!isa<TypedefNameDecl>(Old))
  2006. return;
  2007. Diag(New->getLocation(), diag::err_redefinition)
  2008. << New->getDeclName();
  2009. notePreviousDefinition(Old, New->getLocation());
  2010. return New->setInvalidDecl();
  2011. }
  2012. // Modules always permit redefinition of typedefs, as does C11.
  2013. if (getLangOpts().Modules || getLangOpts().C11)
  2014. return;
  2015. // If we have a redefinition of a typedef in C, emit a warning. This warning
  2016. // is normally mapped to an error, but can be controlled with
  2017. // -Wtypedef-redefinition. If either the original or the redefinition is
  2018. // in a system header, don't emit this for compatibility with GCC.
  2019. if (getDiagnostics().getSuppressSystemWarnings() &&
  2020. // Some standard types are defined implicitly in Clang (e.g. OpenCL).
  2021. (Old->isImplicit() ||
  2022. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  2023. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  2024. return;
  2025. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  2026. << New->getDeclName();
  2027. notePreviousDefinition(Old, New->getLocation());
  2028. }
  2029. /// DeclhasAttr - returns true if decl Declaration already has the target
  2030. /// attribute.
  2031. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  2032. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  2033. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  2034. for (const auto *i : D->attrs())
  2035. if (i->getKind() == A->getKind()) {
  2036. if (Ann) {
  2037. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  2038. return true;
  2039. continue;
  2040. }
  2041. // FIXME: Don't hardcode this check
  2042. if (OA && isa<OwnershipAttr>(i))
  2043. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  2044. return true;
  2045. }
  2046. return false;
  2047. }
  2048. static bool isAttributeTargetADefinition(Decl *D) {
  2049. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  2050. return VD->isThisDeclarationADefinition();
  2051. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  2052. return TD->isCompleteDefinition() || TD->isBeingDefined();
  2053. return true;
  2054. }
  2055. /// Merge alignment attributes from \p Old to \p New, taking into account the
  2056. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  2057. ///
  2058. /// \return \c true if any attributes were added to \p New.
  2059. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  2060. // Look for alignas attributes on Old, and pick out whichever attribute
  2061. // specifies the strictest alignment requirement.
  2062. AlignedAttr *OldAlignasAttr = nullptr;
  2063. AlignedAttr *OldStrictestAlignAttr = nullptr;
  2064. unsigned OldAlign = 0;
  2065. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  2066. // FIXME: We have no way of representing inherited dependent alignments
  2067. // in a case like:
  2068. // template<int A, int B> struct alignas(A) X;
  2069. // template<int A, int B> struct alignas(B) X {};
  2070. // For now, we just ignore any alignas attributes which are not on the
  2071. // definition in such a case.
  2072. if (I->isAlignmentDependent())
  2073. return false;
  2074. if (I->isAlignas())
  2075. OldAlignasAttr = I;
  2076. unsigned Align = I->getAlignment(S.Context);
  2077. if (Align > OldAlign) {
  2078. OldAlign = Align;
  2079. OldStrictestAlignAttr = I;
  2080. }
  2081. }
  2082. // Look for alignas attributes on New.
  2083. AlignedAttr *NewAlignasAttr = nullptr;
  2084. unsigned NewAlign = 0;
  2085. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  2086. if (I->isAlignmentDependent())
  2087. return false;
  2088. if (I->isAlignas())
  2089. NewAlignasAttr = I;
  2090. unsigned Align = I->getAlignment(S.Context);
  2091. if (Align > NewAlign)
  2092. NewAlign = Align;
  2093. }
  2094. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  2095. // Both declarations have 'alignas' attributes. We require them to match.
  2096. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  2097. // fall short. (If two declarations both have alignas, they must both match
  2098. // every definition, and so must match each other if there is a definition.)
  2099. // If either declaration only contains 'alignas(0)' specifiers, then it
  2100. // specifies the natural alignment for the type.
  2101. if (OldAlign == 0 || NewAlign == 0) {
  2102. QualType Ty;
  2103. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  2104. Ty = VD->getType();
  2105. else
  2106. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  2107. if (OldAlign == 0)
  2108. OldAlign = S.Context.getTypeAlign(Ty);
  2109. if (NewAlign == 0)
  2110. NewAlign = S.Context.getTypeAlign(Ty);
  2111. }
  2112. if (OldAlign != NewAlign) {
  2113. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  2114. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  2115. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  2116. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  2117. }
  2118. }
  2119. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  2120. // C++11 [dcl.align]p6:
  2121. // if any declaration of an entity has an alignment-specifier,
  2122. // every defining declaration of that entity shall specify an
  2123. // equivalent alignment.
  2124. // C11 6.7.5/7:
  2125. // If the definition of an object does not have an alignment
  2126. // specifier, any other declaration of that object shall also
  2127. // have no alignment specifier.
  2128. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2129. << OldAlignasAttr;
  2130. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2131. << OldAlignasAttr;
  2132. }
  2133. bool AnyAdded = false;
  2134. // Ensure we have an attribute representing the strictest alignment.
  2135. if (OldAlign > NewAlign) {
  2136. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2137. Clone->setInherited(true);
  2138. New->addAttr(Clone);
  2139. AnyAdded = true;
  2140. }
  2141. // Ensure we have an alignas attribute if the old declaration had one.
  2142. if (OldAlignasAttr && !NewAlignasAttr &&
  2143. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2144. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2145. Clone->setInherited(true);
  2146. New->addAttr(Clone);
  2147. AnyAdded = true;
  2148. }
  2149. return AnyAdded;
  2150. }
  2151. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2152. const InheritableAttr *Attr,
  2153. Sema::AvailabilityMergeKind AMK) {
  2154. // This function copies an attribute Attr from a previous declaration to the
  2155. // new declaration D if the new declaration doesn't itself have that attribute
  2156. // yet or if that attribute allows duplicates.
  2157. // If you're adding a new attribute that requires logic different from
  2158. // "use explicit attribute on decl if present, else use attribute from
  2159. // previous decl", for example if the attribute needs to be consistent
  2160. // between redeclarations, you need to call a custom merge function here.
  2161. InheritableAttr *NewAttr = nullptr;
  2162. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  2163. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2164. NewAttr = S.mergeAvailabilityAttr(
  2165. D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
  2166. AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
  2167. AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
  2168. AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
  2169. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2170. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2171. AttrSpellingListIndex);
  2172. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2173. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2174. AttrSpellingListIndex);
  2175. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2176. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  2177. AttrSpellingListIndex);
  2178. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2179. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  2180. AttrSpellingListIndex);
  2181. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2182. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  2183. FA->getFormatIdx(), FA->getFirstArg(),
  2184. AttrSpellingListIndex);
  2185. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2186. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  2187. AttrSpellingListIndex);
  2188. else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
  2189. NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
  2190. AttrSpellingListIndex);
  2191. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2192. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  2193. AttrSpellingListIndex,
  2194. IA->getSemanticSpelling());
  2195. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2196. NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
  2197. &S.Context.Idents.get(AA->getSpelling()),
  2198. AttrSpellingListIndex);
  2199. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2200. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2201. isa<CUDAGlobalAttr>(Attr))) {
  2202. // CUDA target attributes are part of function signature for
  2203. // overloading purposes and must not be merged.
  2204. return false;
  2205. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2206. NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
  2207. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2208. NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
  2209. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2210. NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
  2211. else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
  2212. NewAttr = S.mergeCommonAttr(D, *CommonA);
  2213. else if (isa<AlignedAttr>(Attr))
  2214. // AlignedAttrs are handled separately, because we need to handle all
  2215. // such attributes on a declaration at the same time.
  2216. NewAttr = nullptr;
  2217. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2218. (AMK == Sema::AMK_Override ||
  2219. AMK == Sema::AMK_ProtocolImplementation))
  2220. NewAttr = nullptr;
  2221. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2222. NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
  2223. UA->getGuid());
  2224. else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
  2225. NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
  2226. else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
  2227. NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
  2228. else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
  2229. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2230. if (NewAttr) {
  2231. NewAttr->setInherited(true);
  2232. D->addAttr(NewAttr);
  2233. if (isa<MSInheritanceAttr>(NewAttr))
  2234. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2235. return true;
  2236. }
  2237. return false;
  2238. }
  2239. static const NamedDecl *getDefinition(const Decl *D) {
  2240. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2241. return TD->getDefinition();
  2242. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2243. const VarDecl *Def = VD->getDefinition();
  2244. if (Def)
  2245. return Def;
  2246. return VD->getActingDefinition();
  2247. }
  2248. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2249. return FD->getDefinition();
  2250. return nullptr;
  2251. }
  2252. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2253. for (const auto *Attribute : D->attrs())
  2254. if (Attribute->getKind() == Kind)
  2255. return true;
  2256. return false;
  2257. }
  2258. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2259. /// there are no new attributes in this declaration.
  2260. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2261. if (!New->hasAttrs())
  2262. return;
  2263. const NamedDecl *Def = getDefinition(Old);
  2264. if (!Def || Def == New)
  2265. return;
  2266. AttrVec &NewAttributes = New->getAttrs();
  2267. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2268. const Attr *NewAttribute = NewAttributes[I];
  2269. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2270. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2271. Sema::SkipBodyInfo SkipBody;
  2272. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2273. // If we're skipping this definition, drop the "alias" attribute.
  2274. if (SkipBody.ShouldSkip) {
  2275. NewAttributes.erase(NewAttributes.begin() + I);
  2276. --E;
  2277. continue;
  2278. }
  2279. } else {
  2280. VarDecl *VD = cast<VarDecl>(New);
  2281. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2282. VarDecl::TentativeDefinition
  2283. ? diag::err_alias_after_tentative
  2284. : diag::err_redefinition;
  2285. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2286. if (Diag == diag::err_redefinition)
  2287. S.notePreviousDefinition(Def, VD->getLocation());
  2288. else
  2289. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2290. VD->setInvalidDecl();
  2291. }
  2292. ++I;
  2293. continue;
  2294. }
  2295. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2296. // Tentative definitions are only interesting for the alias check above.
  2297. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2298. ++I;
  2299. continue;
  2300. }
  2301. }
  2302. if (hasAttribute(Def, NewAttribute->getKind())) {
  2303. ++I;
  2304. continue; // regular attr merging will take care of validating this.
  2305. }
  2306. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2307. // C's _Noreturn is allowed to be added to a function after it is defined.
  2308. ++I;
  2309. continue;
  2310. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2311. if (AA->isAlignas()) {
  2312. // C++11 [dcl.align]p6:
  2313. // if any declaration of an entity has an alignment-specifier,
  2314. // every defining declaration of that entity shall specify an
  2315. // equivalent alignment.
  2316. // C11 6.7.5/7:
  2317. // If the definition of an object does not have an alignment
  2318. // specifier, any other declaration of that object shall also
  2319. // have no alignment specifier.
  2320. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2321. << AA;
  2322. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2323. << AA;
  2324. NewAttributes.erase(NewAttributes.begin() + I);
  2325. --E;
  2326. continue;
  2327. }
  2328. }
  2329. S.Diag(NewAttribute->getLocation(),
  2330. diag::warn_attribute_precede_definition);
  2331. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2332. NewAttributes.erase(NewAttributes.begin() + I);
  2333. --E;
  2334. }
  2335. }
  2336. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2337. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2338. AvailabilityMergeKind AMK) {
  2339. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2340. UsedAttr *NewAttr = OldAttr->clone(Context);
  2341. NewAttr->setInherited(true);
  2342. New->addAttr(NewAttr);
  2343. }
  2344. if (!Old->hasAttrs() && !New->hasAttrs())
  2345. return;
  2346. // Attributes declared post-definition are currently ignored.
  2347. checkNewAttributesAfterDef(*this, New, Old);
  2348. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2349. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2350. if (OldA->getLabel() != NewA->getLabel()) {
  2351. // This redeclaration changes __asm__ label.
  2352. Diag(New->getLocation(), diag::err_different_asm_label);
  2353. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2354. }
  2355. } else if (Old->isUsed()) {
  2356. // This redeclaration adds an __asm__ label to a declaration that has
  2357. // already been ODR-used.
  2358. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2359. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2360. }
  2361. }
  2362. // Re-declaration cannot add abi_tag's.
  2363. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2364. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2365. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2366. if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
  2367. NewTag) == OldAbiTagAttr->tags_end()) {
  2368. Diag(NewAbiTagAttr->getLocation(),
  2369. diag::err_new_abi_tag_on_redeclaration)
  2370. << NewTag;
  2371. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2372. }
  2373. }
  2374. } else {
  2375. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2376. Diag(Old->getLocation(), diag::note_previous_declaration);
  2377. }
  2378. }
  2379. // This redeclaration adds a section attribute.
  2380. if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
  2381. if (auto *VD = dyn_cast<VarDecl>(New)) {
  2382. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
  2383. Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
  2384. Diag(Old->getLocation(), diag::note_previous_declaration);
  2385. }
  2386. }
  2387. }
  2388. // Redeclaration adds code-seg attribute.
  2389. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  2390. if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
  2391. !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
  2392. Diag(New->getLocation(), diag::warn_mismatched_section)
  2393. << 0 /*codeseg*/;
  2394. Diag(Old->getLocation(), diag::note_previous_declaration);
  2395. }
  2396. if (!Old->hasAttrs())
  2397. return;
  2398. bool foundAny = New->hasAttrs();
  2399. // Ensure that any moving of objects within the allocated map is done before
  2400. // we process them.
  2401. if (!foundAny) New->setAttrs(AttrVec());
  2402. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2403. // Ignore deprecated/unavailable/availability attributes if requested.
  2404. AvailabilityMergeKind LocalAMK = AMK_None;
  2405. if (isa<DeprecatedAttr>(I) ||
  2406. isa<UnavailableAttr>(I) ||
  2407. isa<AvailabilityAttr>(I)) {
  2408. switch (AMK) {
  2409. case AMK_None:
  2410. continue;
  2411. case AMK_Redeclaration:
  2412. case AMK_Override:
  2413. case AMK_ProtocolImplementation:
  2414. LocalAMK = AMK;
  2415. break;
  2416. }
  2417. }
  2418. // Already handled.
  2419. if (isa<UsedAttr>(I))
  2420. continue;
  2421. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2422. foundAny = true;
  2423. }
  2424. if (mergeAlignedAttrs(*this, New, Old))
  2425. foundAny = true;
  2426. if (!foundAny) New->dropAttrs();
  2427. }
  2428. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2429. /// to the new one.
  2430. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2431. const ParmVarDecl *oldDecl,
  2432. Sema &S) {
  2433. // C++11 [dcl.attr.depend]p2:
  2434. // The first declaration of a function shall specify the
  2435. // carries_dependency attribute for its declarator-id if any declaration
  2436. // of the function specifies the carries_dependency attribute.
  2437. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2438. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2439. S.Diag(CDA->getLocation(),
  2440. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2441. // Find the first declaration of the parameter.
  2442. // FIXME: Should we build redeclaration chains for function parameters?
  2443. const FunctionDecl *FirstFD =
  2444. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2445. const ParmVarDecl *FirstVD =
  2446. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2447. S.Diag(FirstVD->getLocation(),
  2448. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2449. }
  2450. if (!oldDecl->hasAttrs())
  2451. return;
  2452. bool foundAny = newDecl->hasAttrs();
  2453. // Ensure that any moving of objects within the allocated map is
  2454. // done before we process them.
  2455. if (!foundAny) newDecl->setAttrs(AttrVec());
  2456. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2457. if (!DeclHasAttr(newDecl, I)) {
  2458. InheritableAttr *newAttr =
  2459. cast<InheritableParamAttr>(I->clone(S.Context));
  2460. newAttr->setInherited(true);
  2461. newDecl->addAttr(newAttr);
  2462. foundAny = true;
  2463. }
  2464. }
  2465. if (!foundAny) newDecl->dropAttrs();
  2466. }
  2467. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2468. const ParmVarDecl *OldParam,
  2469. Sema &S) {
  2470. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2471. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2472. if (*Oldnullability != *Newnullability) {
  2473. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2474. << DiagNullabilityKind(
  2475. *Newnullability,
  2476. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2477. != 0))
  2478. << DiagNullabilityKind(
  2479. *Oldnullability,
  2480. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2481. != 0));
  2482. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2483. }
  2484. } else {
  2485. QualType NewT = NewParam->getType();
  2486. NewT = S.Context.getAttributedType(
  2487. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2488. NewT, NewT);
  2489. NewParam->setType(NewT);
  2490. }
  2491. }
  2492. }
  2493. namespace {
  2494. /// Used in MergeFunctionDecl to keep track of function parameters in
  2495. /// C.
  2496. struct GNUCompatibleParamWarning {
  2497. ParmVarDecl *OldParm;
  2498. ParmVarDecl *NewParm;
  2499. QualType PromotedType;
  2500. };
  2501. } // end anonymous namespace
  2502. /// getSpecialMember - get the special member enum for a method.
  2503. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2504. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2505. if (Ctor->isDefaultConstructor())
  2506. return Sema::CXXDefaultConstructor;
  2507. if (Ctor->isCopyConstructor())
  2508. return Sema::CXXCopyConstructor;
  2509. if (Ctor->isMoveConstructor())
  2510. return Sema::CXXMoveConstructor;
  2511. } else if (isa<CXXDestructorDecl>(MD)) {
  2512. return Sema::CXXDestructor;
  2513. } else if (MD->isCopyAssignmentOperator()) {
  2514. return Sema::CXXCopyAssignment;
  2515. } else if (MD->isMoveAssignmentOperator()) {
  2516. return Sema::CXXMoveAssignment;
  2517. }
  2518. return Sema::CXXInvalid;
  2519. }
  2520. // Determine whether the previous declaration was a definition, implicit
  2521. // declaration, or a declaration.
  2522. template <typename T>
  2523. static std::pair<diag::kind, SourceLocation>
  2524. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2525. diag::kind PrevDiag;
  2526. SourceLocation OldLocation = Old->getLocation();
  2527. if (Old->isThisDeclarationADefinition())
  2528. PrevDiag = diag::note_previous_definition;
  2529. else if (Old->isImplicit()) {
  2530. PrevDiag = diag::note_previous_implicit_declaration;
  2531. if (OldLocation.isInvalid())
  2532. OldLocation = New->getLocation();
  2533. } else
  2534. PrevDiag = diag::note_previous_declaration;
  2535. return std::make_pair(PrevDiag, OldLocation);
  2536. }
  2537. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2538. /// only extern inline functions can be redefined, and even then only in
  2539. /// GNU89 mode.
  2540. static bool canRedefineFunction(const FunctionDecl *FD,
  2541. const LangOptions& LangOpts) {
  2542. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2543. !LangOpts.CPlusPlus &&
  2544. FD->isInlineSpecified() &&
  2545. FD->getStorageClass() == SC_Extern);
  2546. }
  2547. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2548. const AttributedType *AT = T->getAs<AttributedType>();
  2549. while (AT && !AT->isCallingConv())
  2550. AT = AT->getModifiedType()->getAs<AttributedType>();
  2551. return AT;
  2552. }
  2553. template <typename T>
  2554. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2555. const DeclContext *DC = Old->getDeclContext();
  2556. if (DC->isRecord())
  2557. return false;
  2558. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2559. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2560. return true;
  2561. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2562. return true;
  2563. return false;
  2564. }
  2565. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2566. static bool isExternC(VarTemplateDecl *) { return false; }
  2567. /// Check whether a redeclaration of an entity introduced by a
  2568. /// using-declaration is valid, given that we know it's not an overload
  2569. /// (nor a hidden tag declaration).
  2570. template<typename ExpectedDecl>
  2571. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2572. ExpectedDecl *New) {
  2573. // C++11 [basic.scope.declarative]p4:
  2574. // Given a set of declarations in a single declarative region, each of
  2575. // which specifies the same unqualified name,
  2576. // -- they shall all refer to the same entity, or all refer to functions
  2577. // and function templates; or
  2578. // -- exactly one declaration shall declare a class name or enumeration
  2579. // name that is not a typedef name and the other declarations shall all
  2580. // refer to the same variable or enumerator, or all refer to functions
  2581. // and function templates; in this case the class name or enumeration
  2582. // name is hidden (3.3.10).
  2583. // C++11 [namespace.udecl]p14:
  2584. // If a function declaration in namespace scope or block scope has the
  2585. // same name and the same parameter-type-list as a function introduced
  2586. // by a using-declaration, and the declarations do not declare the same
  2587. // function, the program is ill-formed.
  2588. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2589. if (Old &&
  2590. !Old->getDeclContext()->getRedeclContext()->Equals(
  2591. New->getDeclContext()->getRedeclContext()) &&
  2592. !(isExternC(Old) && isExternC(New)))
  2593. Old = nullptr;
  2594. if (!Old) {
  2595. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2596. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2597. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2598. return true;
  2599. }
  2600. return false;
  2601. }
  2602. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2603. const FunctionDecl *B) {
  2604. assert(A->getNumParams() == B->getNumParams());
  2605. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2606. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2607. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2608. if (AttrA == AttrB)
  2609. return true;
  2610. return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
  2611. AttrA->isDynamic() == AttrB->isDynamic();
  2612. };
  2613. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2614. }
  2615. /// If necessary, adjust the semantic declaration context for a qualified
  2616. /// declaration to name the correct inline namespace within the qualifier.
  2617. static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
  2618. DeclaratorDecl *OldD) {
  2619. // The only case where we need to update the DeclContext is when
  2620. // redeclaration lookup for a qualified name finds a declaration
  2621. // in an inline namespace within the context named by the qualifier:
  2622. //
  2623. // inline namespace N { int f(); }
  2624. // int ::f(); // Sema DC needs adjusting from :: to N::.
  2625. //
  2626. // For unqualified declarations, the semantic context *can* change
  2627. // along the redeclaration chain (for local extern declarations,
  2628. // extern "C" declarations, and friend declarations in particular).
  2629. if (!NewD->getQualifier())
  2630. return;
  2631. // NewD is probably already in the right context.
  2632. auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
  2633. auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
  2634. if (NamedDC->Equals(SemaDC))
  2635. return;
  2636. assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
  2637. NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
  2638. "unexpected context for redeclaration");
  2639. auto *LexDC = NewD->getLexicalDeclContext();
  2640. auto FixSemaDC = [=](NamedDecl *D) {
  2641. if (!D)
  2642. return;
  2643. D->setDeclContext(SemaDC);
  2644. D->setLexicalDeclContext(LexDC);
  2645. };
  2646. FixSemaDC(NewD);
  2647. if (auto *FD = dyn_cast<FunctionDecl>(NewD))
  2648. FixSemaDC(FD->getDescribedFunctionTemplate());
  2649. else if (auto *VD = dyn_cast<VarDecl>(NewD))
  2650. FixSemaDC(VD->getDescribedVarTemplate());
  2651. }
  2652. /// MergeFunctionDecl - We just parsed a function 'New' from
  2653. /// declarator D which has the same name and scope as a previous
  2654. /// declaration 'Old'. Figure out how to resolve this situation,
  2655. /// merging decls or emitting diagnostics as appropriate.
  2656. ///
  2657. /// In C++, New and Old must be declarations that are not
  2658. /// overloaded. Use IsOverload to determine whether New and Old are
  2659. /// overloaded, and to select the Old declaration that New should be
  2660. /// merged with.
  2661. ///
  2662. /// Returns true if there was an error, false otherwise.
  2663. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2664. Scope *S, bool MergeTypeWithOld) {
  2665. // Verify the old decl was also a function.
  2666. FunctionDecl *Old = OldD->getAsFunction();
  2667. if (!Old) {
  2668. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2669. if (New->getFriendObjectKind()) {
  2670. Diag(New->getLocation(), diag::err_using_decl_friend);
  2671. Diag(Shadow->getTargetDecl()->getLocation(),
  2672. diag::note_using_decl_target);
  2673. Diag(Shadow->getUsingDecl()->getLocation(),
  2674. diag::note_using_decl) << 0;
  2675. return true;
  2676. }
  2677. // Check whether the two declarations might declare the same function.
  2678. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2679. return true;
  2680. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2681. } else {
  2682. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2683. << New->getDeclName();
  2684. notePreviousDefinition(OldD, New->getLocation());
  2685. return true;
  2686. }
  2687. }
  2688. // If the old declaration is invalid, just give up here.
  2689. if (Old->isInvalidDecl())
  2690. return true;
  2691. // Disallow redeclaration of some builtins.
  2692. if (!getASTContext().canBuiltinBeRedeclared(Old)) {
  2693. Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
  2694. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  2695. << Old << Old->getType();
  2696. return true;
  2697. }
  2698. diag::kind PrevDiag;
  2699. SourceLocation OldLocation;
  2700. std::tie(PrevDiag, OldLocation) =
  2701. getNoteDiagForInvalidRedeclaration(Old, New);
  2702. // Don't complain about this if we're in GNU89 mode and the old function
  2703. // is an extern inline function.
  2704. // Don't complain about specializations. They are not supposed to have
  2705. // storage classes.
  2706. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2707. New->getStorageClass() == SC_Static &&
  2708. Old->hasExternalFormalLinkage() &&
  2709. !New->getTemplateSpecializationInfo() &&
  2710. !canRedefineFunction(Old, getLangOpts())) {
  2711. if (getLangOpts().MicrosoftExt) {
  2712. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2713. Diag(OldLocation, PrevDiag);
  2714. } else {
  2715. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2716. Diag(OldLocation, PrevDiag);
  2717. return true;
  2718. }
  2719. }
  2720. if (New->hasAttr<InternalLinkageAttr>() &&
  2721. !Old->hasAttr<InternalLinkageAttr>()) {
  2722. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  2723. << New->getDeclName();
  2724. notePreviousDefinition(Old, New->getLocation());
  2725. New->dropAttr<InternalLinkageAttr>();
  2726. }
  2727. if (CheckRedeclarationModuleOwnership(New, Old))
  2728. return true;
  2729. if (!getLangOpts().CPlusPlus) {
  2730. bool OldOvl = Old->hasAttr<OverloadableAttr>();
  2731. if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
  2732. Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
  2733. << New << OldOvl;
  2734. // Try our best to find a decl that actually has the overloadable
  2735. // attribute for the note. In most cases (e.g. programs with only one
  2736. // broken declaration/definition), this won't matter.
  2737. //
  2738. // FIXME: We could do this if we juggled some extra state in
  2739. // OverloadableAttr, rather than just removing it.
  2740. const Decl *DiagOld = Old;
  2741. if (OldOvl) {
  2742. auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
  2743. const auto *A = D->getAttr<OverloadableAttr>();
  2744. return A && !A->isImplicit();
  2745. });
  2746. // If we've implicitly added *all* of the overloadable attrs to this
  2747. // chain, emitting a "previous redecl" note is pointless.
  2748. DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
  2749. }
  2750. if (DiagOld)
  2751. Diag(DiagOld->getLocation(),
  2752. diag::note_attribute_overloadable_prev_overload)
  2753. << OldOvl;
  2754. if (OldOvl)
  2755. New->addAttr(OverloadableAttr::CreateImplicit(Context));
  2756. else
  2757. New->dropAttr<OverloadableAttr>();
  2758. }
  2759. }
  2760. // If a function is first declared with a calling convention, but is later
  2761. // declared or defined without one, all following decls assume the calling
  2762. // convention of the first.
  2763. //
  2764. // It's OK if a function is first declared without a calling convention,
  2765. // but is later declared or defined with the default calling convention.
  2766. //
  2767. // To test if either decl has an explicit calling convention, we look for
  2768. // AttributedType sugar nodes on the type as written. If they are missing or
  2769. // were canonicalized away, we assume the calling convention was implicit.
  2770. //
  2771. // Note also that we DO NOT return at this point, because we still have
  2772. // other tests to run.
  2773. QualType OldQType = Context.getCanonicalType(Old->getType());
  2774. QualType NewQType = Context.getCanonicalType(New->getType());
  2775. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2776. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2777. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2778. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2779. bool RequiresAdjustment = false;
  2780. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2781. FunctionDecl *First = Old->getFirstDecl();
  2782. const FunctionType *FT =
  2783. First->getType().getCanonicalType()->castAs<FunctionType>();
  2784. FunctionType::ExtInfo FI = FT->getExtInfo();
  2785. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2786. if (!NewCCExplicit) {
  2787. // Inherit the CC from the previous declaration if it was specified
  2788. // there but not here.
  2789. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2790. RequiresAdjustment = true;
  2791. } else if (New->getBuiltinID()) {
  2792. // Calling Conventions on a Builtin aren't really useful and setting a
  2793. // default calling convention and cdecl'ing some builtin redeclarations is
  2794. // common, so warn and ignore the calling convention on the redeclaration.
  2795. Diag(New->getLocation(), diag::warn_cconv_ignored)
  2796. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2797. << (int)CallingConventionIgnoredReason::BuiltinFunction;
  2798. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2799. RequiresAdjustment = true;
  2800. } else {
  2801. // Calling conventions aren't compatible, so complain.
  2802. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2803. Diag(New->getLocation(), diag::err_cconv_change)
  2804. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2805. << !FirstCCExplicit
  2806. << (!FirstCCExplicit ? "" :
  2807. FunctionType::getNameForCallConv(FI.getCC()));
  2808. // Put the note on the first decl, since it is the one that matters.
  2809. Diag(First->getLocation(), diag::note_previous_declaration);
  2810. return true;
  2811. }
  2812. }
  2813. // FIXME: diagnose the other way around?
  2814. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2815. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2816. RequiresAdjustment = true;
  2817. }
  2818. // Merge regparm attribute.
  2819. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2820. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2821. if (NewTypeInfo.getHasRegParm()) {
  2822. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2823. << NewType->getRegParmType()
  2824. << OldType->getRegParmType();
  2825. Diag(OldLocation, diag::note_previous_declaration);
  2826. return true;
  2827. }
  2828. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2829. RequiresAdjustment = true;
  2830. }
  2831. // Merge ns_returns_retained attribute.
  2832. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2833. if (NewTypeInfo.getProducesResult()) {
  2834. Diag(New->getLocation(), diag::err_function_attribute_mismatch)
  2835. << "'ns_returns_retained'";
  2836. Diag(OldLocation, diag::note_previous_declaration);
  2837. return true;
  2838. }
  2839. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2840. RequiresAdjustment = true;
  2841. }
  2842. if (OldTypeInfo.getNoCallerSavedRegs() !=
  2843. NewTypeInfo.getNoCallerSavedRegs()) {
  2844. if (NewTypeInfo.getNoCallerSavedRegs()) {
  2845. AnyX86NoCallerSavedRegistersAttr *Attr =
  2846. New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
  2847. Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
  2848. Diag(OldLocation, diag::note_previous_declaration);
  2849. return true;
  2850. }
  2851. NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
  2852. RequiresAdjustment = true;
  2853. }
  2854. if (RequiresAdjustment) {
  2855. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2856. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2857. New->setType(QualType(AdjustedType, 0));
  2858. NewQType = Context.getCanonicalType(New->getType());
  2859. }
  2860. // If this redeclaration makes the function inline, we may need to add it to
  2861. // UndefinedButUsed.
  2862. if (!Old->isInlined() && New->isInlined() &&
  2863. !New->hasAttr<GNUInlineAttr>() &&
  2864. !getLangOpts().GNUInline &&
  2865. Old->isUsed(false) &&
  2866. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2867. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2868. SourceLocation()));
  2869. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2870. // about it.
  2871. if (New->hasAttr<GNUInlineAttr>() &&
  2872. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2873. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2874. }
  2875. // If pass_object_size params don't match up perfectly, this isn't a valid
  2876. // redeclaration.
  2877. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  2878. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  2879. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  2880. << New->getDeclName();
  2881. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2882. return true;
  2883. }
  2884. if (getLangOpts().CPlusPlus) {
  2885. // C++1z [over.load]p2
  2886. // Certain function declarations cannot be overloaded:
  2887. // -- Function declarations that differ only in the return type,
  2888. // the exception specification, or both cannot be overloaded.
  2889. // Check the exception specifications match. This may recompute the type of
  2890. // both Old and New if it resolved exception specifications, so grab the
  2891. // types again after this. Because this updates the type, we do this before
  2892. // any of the other checks below, which may update the "de facto" NewQType
  2893. // but do not necessarily update the type of New.
  2894. if (CheckEquivalentExceptionSpec(Old, New))
  2895. return true;
  2896. OldQType = Context.getCanonicalType(Old->getType());
  2897. NewQType = Context.getCanonicalType(New->getType());
  2898. // Go back to the type source info to compare the declared return types,
  2899. // per C++1y [dcl.type.auto]p13:
  2900. // Redeclarations or specializations of a function or function template
  2901. // with a declared return type that uses a placeholder type shall also
  2902. // use that placeholder, not a deduced type.
  2903. QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
  2904. QualType NewDeclaredReturnType = New->getDeclaredReturnType();
  2905. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  2906. canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
  2907. OldDeclaredReturnType)) {
  2908. QualType ResQT;
  2909. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  2910. OldDeclaredReturnType->isObjCObjectPointerType())
  2911. // FIXME: This does the wrong thing for a deduced return type.
  2912. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  2913. if (ResQT.isNull()) {
  2914. if (New->isCXXClassMember() && New->isOutOfLine())
  2915. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  2916. << New << New->getReturnTypeSourceRange();
  2917. else
  2918. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  2919. << New->getReturnTypeSourceRange();
  2920. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  2921. << Old->getReturnTypeSourceRange();
  2922. return true;
  2923. }
  2924. else
  2925. NewQType = ResQT;
  2926. }
  2927. QualType OldReturnType = OldType->getReturnType();
  2928. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  2929. if (OldReturnType != NewReturnType) {
  2930. // If this function has a deduced return type and has already been
  2931. // defined, copy the deduced value from the old declaration.
  2932. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  2933. if (OldAT && OldAT->isDeduced()) {
  2934. New->setType(
  2935. SubstAutoType(New->getType(),
  2936. OldAT->isDependentType() ? Context.DependentTy
  2937. : OldAT->getDeducedType()));
  2938. NewQType = Context.getCanonicalType(
  2939. SubstAutoType(NewQType,
  2940. OldAT->isDependentType() ? Context.DependentTy
  2941. : OldAT->getDeducedType()));
  2942. }
  2943. }
  2944. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  2945. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  2946. if (OldMethod && NewMethod) {
  2947. // Preserve triviality.
  2948. NewMethod->setTrivial(OldMethod->isTrivial());
  2949. // MSVC allows explicit template specialization at class scope:
  2950. // 2 CXXMethodDecls referring to the same function will be injected.
  2951. // We don't want a redeclaration error.
  2952. bool IsClassScopeExplicitSpecialization =
  2953. OldMethod->isFunctionTemplateSpecialization() &&
  2954. NewMethod->isFunctionTemplateSpecialization();
  2955. bool isFriend = NewMethod->getFriendObjectKind();
  2956. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  2957. !IsClassScopeExplicitSpecialization) {
  2958. // -- Member function declarations with the same name and the
  2959. // same parameter types cannot be overloaded if any of them
  2960. // is a static member function declaration.
  2961. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  2962. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  2963. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2964. return true;
  2965. }
  2966. // C++ [class.mem]p1:
  2967. // [...] A member shall not be declared twice in the
  2968. // member-specification, except that a nested class or member
  2969. // class template can be declared and then later defined.
  2970. if (!inTemplateInstantiation()) {
  2971. unsigned NewDiag;
  2972. if (isa<CXXConstructorDecl>(OldMethod))
  2973. NewDiag = diag::err_constructor_redeclared;
  2974. else if (isa<CXXDestructorDecl>(NewMethod))
  2975. NewDiag = diag::err_destructor_redeclared;
  2976. else if (isa<CXXConversionDecl>(NewMethod))
  2977. NewDiag = diag::err_conv_function_redeclared;
  2978. else
  2979. NewDiag = diag::err_member_redeclared;
  2980. Diag(New->getLocation(), NewDiag);
  2981. } else {
  2982. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2983. << New << New->getType();
  2984. }
  2985. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2986. return true;
  2987. // Complain if this is an explicit declaration of a special
  2988. // member that was initially declared implicitly.
  2989. //
  2990. // As an exception, it's okay to befriend such methods in order
  2991. // to permit the implicit constructor/destructor/operator calls.
  2992. } else if (OldMethod->isImplicit()) {
  2993. if (isFriend) {
  2994. NewMethod->setImplicit();
  2995. } else {
  2996. Diag(NewMethod->getLocation(),
  2997. diag::err_definition_of_implicitly_declared_member)
  2998. << New << getSpecialMember(OldMethod);
  2999. return true;
  3000. }
  3001. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  3002. Diag(NewMethod->getLocation(),
  3003. diag::err_definition_of_explicitly_defaulted_member)
  3004. << getSpecialMember(OldMethod);
  3005. return true;
  3006. }
  3007. }
  3008. // C++11 [dcl.attr.noreturn]p1:
  3009. // The first declaration of a function shall specify the noreturn
  3010. // attribute if any declaration of that function specifies the noreturn
  3011. // attribute.
  3012. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  3013. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  3014. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  3015. Diag(Old->getFirstDecl()->getLocation(),
  3016. diag::note_noreturn_missing_first_decl);
  3017. }
  3018. // C++11 [dcl.attr.depend]p2:
  3019. // The first declaration of a function shall specify the
  3020. // carries_dependency attribute for its declarator-id if any declaration
  3021. // of the function specifies the carries_dependency attribute.
  3022. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  3023. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  3024. Diag(CDA->getLocation(),
  3025. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  3026. Diag(Old->getFirstDecl()->getLocation(),
  3027. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  3028. }
  3029. // (C++98 8.3.5p3):
  3030. // All declarations for a function shall agree exactly in both the
  3031. // return type and the parameter-type-list.
  3032. // We also want to respect all the extended bits except noreturn.
  3033. // noreturn should now match unless the old type info didn't have it.
  3034. QualType OldQTypeForComparison = OldQType;
  3035. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  3036. auto *OldType = OldQType->castAs<FunctionProtoType>();
  3037. const FunctionType *OldTypeForComparison
  3038. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  3039. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  3040. assert(OldQTypeForComparison.isCanonical());
  3041. }
  3042. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3043. // As a special case, retain the language linkage from previous
  3044. // declarations of a friend function as an extension.
  3045. //
  3046. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  3047. // and is useful because there's otherwise no way to specify language
  3048. // linkage within class scope.
  3049. //
  3050. // Check cautiously as the friend object kind isn't yet complete.
  3051. if (New->getFriendObjectKind() != Decl::FOK_None) {
  3052. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  3053. Diag(OldLocation, PrevDiag);
  3054. } else {
  3055. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3056. Diag(OldLocation, PrevDiag);
  3057. return true;
  3058. }
  3059. }
  3060. if (OldQTypeForComparison == NewQType)
  3061. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3062. // If the types are imprecise (due to dependent constructs in friends or
  3063. // local extern declarations), it's OK if they differ. We'll check again
  3064. // during instantiation.
  3065. if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
  3066. return false;
  3067. // Fall through for conflicting redeclarations and redefinitions.
  3068. }
  3069. // C: Function types need to be compatible, not identical. This handles
  3070. // duplicate function decls like "void f(int); void f(enum X);" properly.
  3071. if (!getLangOpts().CPlusPlus &&
  3072. Context.typesAreCompatible(OldQType, NewQType)) {
  3073. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  3074. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  3075. const FunctionProtoType *OldProto = nullptr;
  3076. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  3077. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  3078. // The old declaration provided a function prototype, but the
  3079. // new declaration does not. Merge in the prototype.
  3080. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  3081. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  3082. NewQType =
  3083. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  3084. OldProto->getExtProtoInfo());
  3085. New->setType(NewQType);
  3086. New->setHasInheritedPrototype();
  3087. // Synthesize parameters with the same types.
  3088. SmallVector<ParmVarDecl*, 16> Params;
  3089. for (const auto &ParamType : OldProto->param_types()) {
  3090. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  3091. SourceLocation(), nullptr,
  3092. ParamType, /*TInfo=*/nullptr,
  3093. SC_None, nullptr);
  3094. Param->setScopeInfo(0, Params.size());
  3095. Param->setImplicit();
  3096. Params.push_back(Param);
  3097. }
  3098. New->setParams(Params);
  3099. }
  3100. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3101. }
  3102. // GNU C permits a K&R definition to follow a prototype declaration
  3103. // if the declared types of the parameters in the K&R definition
  3104. // match the types in the prototype declaration, even when the
  3105. // promoted types of the parameters from the K&R definition differ
  3106. // from the types in the prototype. GCC then keeps the types from
  3107. // the prototype.
  3108. //
  3109. // If a variadic prototype is followed by a non-variadic K&R definition,
  3110. // the K&R definition becomes variadic. This is sort of an edge case, but
  3111. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  3112. // C99 6.9.1p8.
  3113. if (!getLangOpts().CPlusPlus &&
  3114. Old->hasPrototype() && !New->hasPrototype() &&
  3115. New->getType()->getAs<FunctionProtoType>() &&
  3116. Old->getNumParams() == New->getNumParams()) {
  3117. SmallVector<QualType, 16> ArgTypes;
  3118. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  3119. const FunctionProtoType *OldProto
  3120. = Old->getType()->getAs<FunctionProtoType>();
  3121. const FunctionProtoType *NewProto
  3122. = New->getType()->getAs<FunctionProtoType>();
  3123. // Determine whether this is the GNU C extension.
  3124. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  3125. NewProto->getReturnType());
  3126. bool LooseCompatible = !MergedReturn.isNull();
  3127. for (unsigned Idx = 0, End = Old->getNumParams();
  3128. LooseCompatible && Idx != End; ++Idx) {
  3129. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  3130. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  3131. if (Context.typesAreCompatible(OldParm->getType(),
  3132. NewProto->getParamType(Idx))) {
  3133. ArgTypes.push_back(NewParm->getType());
  3134. } else if (Context.typesAreCompatible(OldParm->getType(),
  3135. NewParm->getType(),
  3136. /*CompareUnqualified=*/true)) {
  3137. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  3138. NewProto->getParamType(Idx) };
  3139. Warnings.push_back(Warn);
  3140. ArgTypes.push_back(NewParm->getType());
  3141. } else
  3142. LooseCompatible = false;
  3143. }
  3144. if (LooseCompatible) {
  3145. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  3146. Diag(Warnings[Warn].NewParm->getLocation(),
  3147. diag::ext_param_promoted_not_compatible_with_prototype)
  3148. << Warnings[Warn].PromotedType
  3149. << Warnings[Warn].OldParm->getType();
  3150. if (Warnings[Warn].OldParm->getLocation().isValid())
  3151. Diag(Warnings[Warn].OldParm->getLocation(),
  3152. diag::note_previous_declaration);
  3153. }
  3154. if (MergeTypeWithOld)
  3155. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  3156. OldProto->getExtProtoInfo()));
  3157. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3158. }
  3159. // Fall through to diagnose conflicting types.
  3160. }
  3161. // A function that has already been declared has been redeclared or
  3162. // defined with a different type; show an appropriate diagnostic.
  3163. // If the previous declaration was an implicitly-generated builtin
  3164. // declaration, then at the very least we should use a specialized note.
  3165. unsigned BuiltinID;
  3166. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  3167. // If it's actually a library-defined builtin function like 'malloc'
  3168. // or 'printf', just warn about the incompatible redeclaration.
  3169. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  3170. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  3171. Diag(OldLocation, diag::note_previous_builtin_declaration)
  3172. << Old << Old->getType();
  3173. // If this is a global redeclaration, just forget hereafter
  3174. // about the "builtin-ness" of the function.
  3175. //
  3176. // Doing this for local extern declarations is problematic. If
  3177. // the builtin declaration remains visible, a second invalid
  3178. // local declaration will produce a hard error; if it doesn't
  3179. // remain visible, a single bogus local redeclaration (which is
  3180. // actually only a warning) could break all the downstream code.
  3181. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  3182. New->getIdentifier()->revertBuiltin();
  3183. return false;
  3184. }
  3185. PrevDiag = diag::note_previous_builtin_declaration;
  3186. }
  3187. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  3188. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3189. return true;
  3190. }
  3191. /// Completes the merge of two function declarations that are
  3192. /// known to be compatible.
  3193. ///
  3194. /// This routine handles the merging of attributes and other
  3195. /// properties of function declarations from the old declaration to
  3196. /// the new declaration, once we know that New is in fact a
  3197. /// redeclaration of Old.
  3198. ///
  3199. /// \returns false
  3200. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  3201. Scope *S, bool MergeTypeWithOld) {
  3202. // Merge the attributes
  3203. mergeDeclAttributes(New, Old);
  3204. // Merge "pure" flag.
  3205. if (Old->isPure())
  3206. New->setPure();
  3207. // Merge "used" flag.
  3208. if (Old->getMostRecentDecl()->isUsed(false))
  3209. New->setIsUsed();
  3210. // Merge attributes from the parameters. These can mismatch with K&R
  3211. // declarations.
  3212. if (New->getNumParams() == Old->getNumParams())
  3213. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  3214. ParmVarDecl *NewParam = New->getParamDecl(i);
  3215. ParmVarDecl *OldParam = Old->getParamDecl(i);
  3216. mergeParamDeclAttributes(NewParam, OldParam, *this);
  3217. mergeParamDeclTypes(NewParam, OldParam, *this);
  3218. }
  3219. if (getLangOpts().CPlusPlus)
  3220. return MergeCXXFunctionDecl(New, Old, S);
  3221. // Merge the function types so the we get the composite types for the return
  3222. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  3223. // was visible.
  3224. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  3225. if (!Merged.isNull() && MergeTypeWithOld)
  3226. New->setType(Merged);
  3227. return false;
  3228. }
  3229. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  3230. ObjCMethodDecl *oldMethod) {
  3231. // Merge the attributes, including deprecated/unavailable
  3232. AvailabilityMergeKind MergeKind =
  3233. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  3234. ? AMK_ProtocolImplementation
  3235. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  3236. : AMK_Override;
  3237. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  3238. // Merge attributes from the parameters.
  3239. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3240. oe = oldMethod->param_end();
  3241. for (ObjCMethodDecl::param_iterator
  3242. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3243. ni != ne && oi != oe; ++ni, ++oi)
  3244. mergeParamDeclAttributes(*ni, *oi, *this);
  3245. CheckObjCMethodOverride(newMethod, oldMethod);
  3246. }
  3247. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3248. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3249. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3250. ? diag::err_redefinition_different_type
  3251. : diag::err_redeclaration_different_type)
  3252. << New->getDeclName() << New->getType() << Old->getType();
  3253. diag::kind PrevDiag;
  3254. SourceLocation OldLocation;
  3255. std::tie(PrevDiag, OldLocation)
  3256. = getNoteDiagForInvalidRedeclaration(Old, New);
  3257. S.Diag(OldLocation, PrevDiag);
  3258. New->setInvalidDecl();
  3259. }
  3260. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3261. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3262. /// emitting diagnostics as appropriate.
  3263. ///
  3264. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3265. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3266. /// is attached.
  3267. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3268. bool MergeTypeWithOld) {
  3269. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3270. return;
  3271. QualType MergedT;
  3272. if (getLangOpts().CPlusPlus) {
  3273. if (New->getType()->isUndeducedType()) {
  3274. // We don't know what the new type is until the initializer is attached.
  3275. return;
  3276. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3277. // These could still be something that needs exception specs checked.
  3278. return MergeVarDeclExceptionSpecs(New, Old);
  3279. }
  3280. // C++ [basic.link]p10:
  3281. // [...] the types specified by all declarations referring to a given
  3282. // object or function shall be identical, except that declarations for an
  3283. // array object can specify array types that differ by the presence or
  3284. // absence of a major array bound (8.3.4).
  3285. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3286. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3287. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3288. // We are merging a variable declaration New into Old. If it has an array
  3289. // bound, and that bound differs from Old's bound, we should diagnose the
  3290. // mismatch.
  3291. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3292. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3293. PrevVD = PrevVD->getPreviousDecl()) {
  3294. const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
  3295. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3296. continue;
  3297. if (!Context.hasSameType(NewArray, PrevVDTy))
  3298. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3299. }
  3300. }
  3301. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3302. if (Context.hasSameType(OldArray->getElementType(),
  3303. NewArray->getElementType()))
  3304. MergedT = New->getType();
  3305. }
  3306. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3307. // has no array bound, it should not inherit one from Old, if Old is not
  3308. // visible.
  3309. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3310. if (Context.hasSameType(OldArray->getElementType(),
  3311. NewArray->getElementType()))
  3312. MergedT = Old->getType();
  3313. }
  3314. }
  3315. else if (New->getType()->isObjCObjectPointerType() &&
  3316. Old->getType()->isObjCObjectPointerType()) {
  3317. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3318. Old->getType());
  3319. }
  3320. } else {
  3321. // C 6.2.7p2:
  3322. // All declarations that refer to the same object or function shall have
  3323. // compatible type.
  3324. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3325. }
  3326. if (MergedT.isNull()) {
  3327. // It's OK if we couldn't merge types if either type is dependent, for a
  3328. // block-scope variable. In other cases (static data members of class
  3329. // templates, variable templates, ...), we require the types to be
  3330. // equivalent.
  3331. // FIXME: The C++ standard doesn't say anything about this.
  3332. if ((New->getType()->isDependentType() ||
  3333. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3334. // If the old type was dependent, we can't merge with it, so the new type
  3335. // becomes dependent for now. We'll reproduce the original type when we
  3336. // instantiate the TypeSourceInfo for the variable.
  3337. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3338. New->setType(Context.DependentTy);
  3339. return;
  3340. }
  3341. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3342. }
  3343. // Don't actually update the type on the new declaration if the old
  3344. // declaration was an extern declaration in a different scope.
  3345. if (MergeTypeWithOld)
  3346. New->setType(MergedT);
  3347. }
  3348. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3349. LookupResult &Previous) {
  3350. // C11 6.2.7p4:
  3351. // For an identifier with internal or external linkage declared
  3352. // in a scope in which a prior declaration of that identifier is
  3353. // visible, if the prior declaration specifies internal or
  3354. // external linkage, the type of the identifier at the later
  3355. // declaration becomes the composite type.
  3356. //
  3357. // If the variable isn't visible, we do not merge with its type.
  3358. if (Previous.isShadowed())
  3359. return false;
  3360. if (S.getLangOpts().CPlusPlus) {
  3361. // C++11 [dcl.array]p3:
  3362. // If there is a preceding declaration of the entity in the same
  3363. // scope in which the bound was specified, an omitted array bound
  3364. // is taken to be the same as in that earlier declaration.
  3365. return NewVD->isPreviousDeclInSameBlockScope() ||
  3366. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3367. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3368. } else {
  3369. // If the old declaration was function-local, don't merge with its
  3370. // type unless we're in the same function.
  3371. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3372. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3373. }
  3374. }
  3375. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3376. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3377. /// situation, merging decls or emitting diagnostics as appropriate.
  3378. ///
  3379. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3380. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3381. /// definitions here, since the initializer hasn't been attached.
  3382. ///
  3383. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3384. // If the new decl is already invalid, don't do any other checking.
  3385. if (New->isInvalidDecl())
  3386. return;
  3387. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3388. return;
  3389. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3390. // Verify the old decl was also a variable or variable template.
  3391. VarDecl *Old = nullptr;
  3392. VarTemplateDecl *OldTemplate = nullptr;
  3393. if (Previous.isSingleResult()) {
  3394. if (NewTemplate) {
  3395. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3396. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3397. if (auto *Shadow =
  3398. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3399. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3400. return New->setInvalidDecl();
  3401. } else {
  3402. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3403. if (auto *Shadow =
  3404. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3405. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3406. return New->setInvalidDecl();
  3407. }
  3408. }
  3409. if (!Old) {
  3410. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3411. << New->getDeclName();
  3412. notePreviousDefinition(Previous.getRepresentativeDecl(),
  3413. New->getLocation());
  3414. return New->setInvalidDecl();
  3415. }
  3416. // Ensure the template parameters are compatible.
  3417. if (NewTemplate &&
  3418. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3419. OldTemplate->getTemplateParameters(),
  3420. /*Complain=*/true, TPL_TemplateMatch))
  3421. return New->setInvalidDecl();
  3422. // C++ [class.mem]p1:
  3423. // A member shall not be declared twice in the member-specification [...]
  3424. //
  3425. // Here, we need only consider static data members.
  3426. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3427. Diag(New->getLocation(), diag::err_duplicate_member)
  3428. << New->getIdentifier();
  3429. Diag(Old->getLocation(), diag::note_previous_declaration);
  3430. New->setInvalidDecl();
  3431. }
  3432. mergeDeclAttributes(New, Old);
  3433. // Warn if an already-declared variable is made a weak_import in a subsequent
  3434. // declaration
  3435. if (New->hasAttr<WeakImportAttr>() &&
  3436. Old->getStorageClass() == SC_None &&
  3437. !Old->hasAttr<WeakImportAttr>()) {
  3438. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3439. notePreviousDefinition(Old, New->getLocation());
  3440. // Remove weak_import attribute on new declaration.
  3441. New->dropAttr<WeakImportAttr>();
  3442. }
  3443. if (New->hasAttr<InternalLinkageAttr>() &&
  3444. !Old->hasAttr<InternalLinkageAttr>()) {
  3445. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  3446. << New->getDeclName();
  3447. notePreviousDefinition(Old, New->getLocation());
  3448. New->dropAttr<InternalLinkageAttr>();
  3449. }
  3450. // Merge the types.
  3451. VarDecl *MostRecent = Old->getMostRecentDecl();
  3452. if (MostRecent != Old) {
  3453. MergeVarDeclTypes(New, MostRecent,
  3454. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3455. if (New->isInvalidDecl())
  3456. return;
  3457. }
  3458. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3459. if (New->isInvalidDecl())
  3460. return;
  3461. diag::kind PrevDiag;
  3462. SourceLocation OldLocation;
  3463. std::tie(PrevDiag, OldLocation) =
  3464. getNoteDiagForInvalidRedeclaration(Old, New);
  3465. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3466. if (New->getStorageClass() == SC_Static &&
  3467. !New->isStaticDataMember() &&
  3468. Old->hasExternalFormalLinkage()) {
  3469. if (getLangOpts().MicrosoftExt) {
  3470. Diag(New->getLocation(), diag::ext_static_non_static)
  3471. << New->getDeclName();
  3472. Diag(OldLocation, PrevDiag);
  3473. } else {
  3474. Diag(New->getLocation(), diag::err_static_non_static)
  3475. << New->getDeclName();
  3476. Diag(OldLocation, PrevDiag);
  3477. return New->setInvalidDecl();
  3478. }
  3479. }
  3480. // C99 6.2.2p4:
  3481. // For an identifier declared with the storage-class specifier
  3482. // extern in a scope in which a prior declaration of that
  3483. // identifier is visible,23) if the prior declaration specifies
  3484. // internal or external linkage, the linkage of the identifier at
  3485. // the later declaration is the same as the linkage specified at
  3486. // the prior declaration. If no prior declaration is visible, or
  3487. // if the prior declaration specifies no linkage, then the
  3488. // identifier has external linkage.
  3489. if (New->hasExternalStorage() && Old->hasLinkage())
  3490. /* Okay */;
  3491. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3492. !New->isStaticDataMember() &&
  3493. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3494. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3495. Diag(OldLocation, PrevDiag);
  3496. return New->setInvalidDecl();
  3497. }
  3498. // Check if extern is followed by non-extern and vice-versa.
  3499. if (New->hasExternalStorage() &&
  3500. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3501. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3502. Diag(OldLocation, PrevDiag);
  3503. return New->setInvalidDecl();
  3504. }
  3505. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3506. !New->hasExternalStorage()) {
  3507. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3508. Diag(OldLocation, PrevDiag);
  3509. return New->setInvalidDecl();
  3510. }
  3511. if (CheckRedeclarationModuleOwnership(New, Old))
  3512. return;
  3513. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3514. // FIXME: The test for external storage here seems wrong? We still
  3515. // need to check for mismatches.
  3516. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3517. // Don't complain about out-of-line definitions of static members.
  3518. !(Old->getLexicalDeclContext()->isRecord() &&
  3519. !New->getLexicalDeclContext()->isRecord())) {
  3520. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3521. Diag(OldLocation, PrevDiag);
  3522. return New->setInvalidDecl();
  3523. }
  3524. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3525. if (VarDecl *Def = Old->getDefinition()) {
  3526. // C++1z [dcl.fcn.spec]p4:
  3527. // If the definition of a variable appears in a translation unit before
  3528. // its first declaration as inline, the program is ill-formed.
  3529. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3530. Diag(Def->getLocation(), diag::note_previous_definition);
  3531. }
  3532. }
  3533. // If this redeclaration makes the variable inline, we may need to add it to
  3534. // UndefinedButUsed.
  3535. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3536. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3537. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3538. SourceLocation()));
  3539. if (New->getTLSKind() != Old->getTLSKind()) {
  3540. if (!Old->getTLSKind()) {
  3541. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3542. Diag(OldLocation, PrevDiag);
  3543. } else if (!New->getTLSKind()) {
  3544. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3545. Diag(OldLocation, PrevDiag);
  3546. } else {
  3547. // Do not allow redeclaration to change the variable between requiring
  3548. // static and dynamic initialization.
  3549. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3550. // declaration to determine the kind. Do we need to be compatible here?
  3551. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3552. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3553. Diag(OldLocation, PrevDiag);
  3554. }
  3555. }
  3556. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3557. if (getLangOpts().CPlusPlus &&
  3558. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3559. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3560. Old->getCanonicalDecl()->isConstexpr()) {
  3561. // This definition won't be a definition any more once it's been merged.
  3562. Diag(New->getLocation(),
  3563. diag::warn_deprecated_redundant_constexpr_static_def);
  3564. } else if (VarDecl *Def = Old->getDefinition()) {
  3565. if (checkVarDeclRedefinition(Def, New))
  3566. return;
  3567. }
  3568. }
  3569. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3570. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3571. Diag(OldLocation, PrevDiag);
  3572. New->setInvalidDecl();
  3573. return;
  3574. }
  3575. // Merge "used" flag.
  3576. if (Old->getMostRecentDecl()->isUsed(false))
  3577. New->setIsUsed();
  3578. // Keep a chain of previous declarations.
  3579. New->setPreviousDecl(Old);
  3580. if (NewTemplate)
  3581. NewTemplate->setPreviousDecl(OldTemplate);
  3582. adjustDeclContextForDeclaratorDecl(New, Old);
  3583. // Inherit access appropriately.
  3584. New->setAccess(Old->getAccess());
  3585. if (NewTemplate)
  3586. NewTemplate->setAccess(New->getAccess());
  3587. if (Old->isInline())
  3588. New->setImplicitlyInline();
  3589. }
  3590. void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
  3591. SourceManager &SrcMgr = getSourceManager();
  3592. auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
  3593. auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
  3594. auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
  3595. auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
  3596. auto &HSI = PP.getHeaderSearchInfo();
  3597. StringRef HdrFilename =
  3598. SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
  3599. auto noteFromModuleOrInclude = [&](Module *Mod,
  3600. SourceLocation IncLoc) -> bool {
  3601. // Redefinition errors with modules are common with non modular mapped
  3602. // headers, example: a non-modular header H in module A that also gets
  3603. // included directly in a TU. Pointing twice to the same header/definition
  3604. // is confusing, try to get better diagnostics when modules is on.
  3605. if (IncLoc.isValid()) {
  3606. if (Mod) {
  3607. Diag(IncLoc, diag::note_redefinition_modules_same_file)
  3608. << HdrFilename.str() << Mod->getFullModuleName();
  3609. if (!Mod->DefinitionLoc.isInvalid())
  3610. Diag(Mod->DefinitionLoc, diag::note_defined_here)
  3611. << Mod->getFullModuleName();
  3612. } else {
  3613. Diag(IncLoc, diag::note_redefinition_include_same_file)
  3614. << HdrFilename.str();
  3615. }
  3616. return true;
  3617. }
  3618. return false;
  3619. };
  3620. // Is it the same file and same offset? Provide more information on why
  3621. // this leads to a redefinition error.
  3622. bool EmittedDiag = false;
  3623. if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
  3624. SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
  3625. SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
  3626. EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
  3627. EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
  3628. // If the header has no guards, emit a note suggesting one.
  3629. if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
  3630. Diag(Old->getLocation(), diag::note_use_ifdef_guards);
  3631. if (EmittedDiag)
  3632. return;
  3633. }
  3634. // Redefinition coming from different files or couldn't do better above.
  3635. if (Old->getLocation().isValid())
  3636. Diag(Old->getLocation(), diag::note_previous_definition);
  3637. }
  3638. /// We've just determined that \p Old and \p New both appear to be definitions
  3639. /// of the same variable. Either diagnose or fix the problem.
  3640. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3641. if (!hasVisibleDefinition(Old) &&
  3642. (New->getFormalLinkage() == InternalLinkage ||
  3643. New->isInline() ||
  3644. New->getDescribedVarTemplate() ||
  3645. New->getNumTemplateParameterLists() ||
  3646. New->getDeclContext()->isDependentContext())) {
  3647. // The previous definition is hidden, and multiple definitions are
  3648. // permitted (in separate TUs). Demote this to a declaration.
  3649. New->demoteThisDefinitionToDeclaration();
  3650. // Make the canonical definition visible.
  3651. if (auto *OldTD = Old->getDescribedVarTemplate())
  3652. makeMergedDefinitionVisible(OldTD);
  3653. makeMergedDefinitionVisible(Old);
  3654. return false;
  3655. } else {
  3656. Diag(New->getLocation(), diag::err_redefinition) << New;
  3657. notePreviousDefinition(Old, New->getLocation());
  3658. New->setInvalidDecl();
  3659. return true;
  3660. }
  3661. }
  3662. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3663. /// no declarator (e.g. "struct foo;") is parsed.
  3664. Decl *
  3665. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3666. RecordDecl *&AnonRecord) {
  3667. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3668. AnonRecord);
  3669. }
  3670. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3671. // disambiguate entities defined in different scopes.
  3672. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3673. // compatibility.
  3674. // We will pick our mangling number depending on which version of MSVC is being
  3675. // targeted.
  3676. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3677. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3678. ? S->getMSCurManglingNumber()
  3679. : S->getMSLastManglingNumber();
  3680. }
  3681. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3682. if (!Context.getLangOpts().CPlusPlus)
  3683. return;
  3684. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3685. // If this tag is the direct child of a class, number it if
  3686. // it is anonymous.
  3687. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3688. return;
  3689. MangleNumberingContext &MCtx =
  3690. Context.getManglingNumberContext(Tag->getParent());
  3691. Context.setManglingNumber(
  3692. Tag, MCtx.getManglingNumber(
  3693. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3694. return;
  3695. }
  3696. // If this tag isn't a direct child of a class, number it if it is local.
  3697. Decl *ManglingContextDecl;
  3698. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3699. Tag->getDeclContext(), ManglingContextDecl)) {
  3700. Context.setManglingNumber(
  3701. Tag, MCtx->getManglingNumber(
  3702. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3703. }
  3704. }
  3705. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3706. TypedefNameDecl *NewTD) {
  3707. if (TagFromDeclSpec->isInvalidDecl())
  3708. return;
  3709. // Do nothing if the tag already has a name for linkage purposes.
  3710. if (TagFromDeclSpec->hasNameForLinkage())
  3711. return;
  3712. // A well-formed anonymous tag must always be a TUK_Definition.
  3713. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3714. // The type must match the tag exactly; no qualifiers allowed.
  3715. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3716. Context.getTagDeclType(TagFromDeclSpec))) {
  3717. if (getLangOpts().CPlusPlus)
  3718. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3719. return;
  3720. }
  3721. // If we've already computed linkage for the anonymous tag, then
  3722. // adding a typedef name for the anonymous decl can change that
  3723. // linkage, which might be a serious problem. Diagnose this as
  3724. // unsupported and ignore the typedef name. TODO: we should
  3725. // pursue this as a language defect and establish a formal rule
  3726. // for how to handle it.
  3727. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3728. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3729. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3730. tagLoc = getLocForEndOfToken(tagLoc);
  3731. llvm::SmallString<40> textToInsert;
  3732. textToInsert += ' ';
  3733. textToInsert += NewTD->getIdentifier()->getName();
  3734. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3735. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3736. return;
  3737. }
  3738. // Otherwise, set this is the anon-decl typedef for the tag.
  3739. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3740. }
  3741. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3742. switch (T) {
  3743. case DeclSpec::TST_class:
  3744. return 0;
  3745. case DeclSpec::TST_struct:
  3746. return 1;
  3747. case DeclSpec::TST_interface:
  3748. return 2;
  3749. case DeclSpec::TST_union:
  3750. return 3;
  3751. case DeclSpec::TST_enum:
  3752. return 4;
  3753. default:
  3754. llvm_unreachable("unexpected type specifier");
  3755. }
  3756. }
  3757. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3758. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3759. /// parameters to cope with template friend declarations.
  3760. Decl *
  3761. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3762. MultiTemplateParamsArg TemplateParams,
  3763. bool IsExplicitInstantiation,
  3764. RecordDecl *&AnonRecord) {
  3765. Decl *TagD = nullptr;
  3766. TagDecl *Tag = nullptr;
  3767. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3768. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3769. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3770. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3771. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3772. TagD = DS.getRepAsDecl();
  3773. if (!TagD) // We probably had an error
  3774. return nullptr;
  3775. // Note that the above type specs guarantee that the
  3776. // type rep is a Decl, whereas in many of the others
  3777. // it's a Type.
  3778. if (isa<TagDecl>(TagD))
  3779. Tag = cast<TagDecl>(TagD);
  3780. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3781. Tag = CTD->getTemplatedDecl();
  3782. }
  3783. if (Tag) {
  3784. handleTagNumbering(Tag, S);
  3785. Tag->setFreeStanding();
  3786. if (Tag->isInvalidDecl())
  3787. return Tag;
  3788. }
  3789. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3790. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3791. // or incomplete types shall not be restrict-qualified."
  3792. if (TypeQuals & DeclSpec::TQ_restrict)
  3793. Diag(DS.getRestrictSpecLoc(),
  3794. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3795. << DS.getSourceRange();
  3796. }
  3797. if (DS.isInlineSpecified())
  3798. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  3799. << getLangOpts().CPlusPlus17;
  3800. if (DS.hasConstexprSpecifier()) {
  3801. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3802. // and definitions of functions and variables.
  3803. // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
  3804. // the declaration of a function or function template
  3805. bool IsConsteval = DS.getConstexprSpecifier() == CSK_consteval;
  3806. if (Tag)
  3807. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3808. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << IsConsteval;
  3809. else
  3810. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
  3811. << IsConsteval;
  3812. // Don't emit warnings after this error.
  3813. return TagD;
  3814. }
  3815. DiagnoseFunctionSpecifiers(DS);
  3816. if (DS.isFriendSpecified()) {
  3817. // If we're dealing with a decl but not a TagDecl, assume that
  3818. // whatever routines created it handled the friendship aspect.
  3819. if (TagD && !Tag)
  3820. return nullptr;
  3821. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3822. }
  3823. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3824. bool IsExplicitSpecialization =
  3825. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3826. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3827. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  3828. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  3829. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3830. // nested-name-specifier unless it is an explicit instantiation
  3831. // or an explicit specialization.
  3832. //
  3833. // FIXME: We allow class template partial specializations here too, per the
  3834. // obvious intent of DR1819.
  3835. //
  3836. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3837. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3838. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3839. return nullptr;
  3840. }
  3841. // Track whether this decl-specifier declares anything.
  3842. bool DeclaresAnything = true;
  3843. // Handle anonymous struct definitions.
  3844. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3845. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3846. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3847. if (getLangOpts().CPlusPlus ||
  3848. Record->getDeclContext()->isRecord()) {
  3849. // If CurContext is a DeclContext that can contain statements,
  3850. // RecursiveASTVisitor won't visit the decls that
  3851. // BuildAnonymousStructOrUnion() will put into CurContext.
  3852. // Also store them here so that they can be part of the
  3853. // DeclStmt that gets created in this case.
  3854. // FIXME: Also return the IndirectFieldDecls created by
  3855. // BuildAnonymousStructOr union, for the same reason?
  3856. if (CurContext->isFunctionOrMethod())
  3857. AnonRecord = Record;
  3858. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3859. Context.getPrintingPolicy());
  3860. }
  3861. DeclaresAnything = false;
  3862. }
  3863. }
  3864. // C11 6.7.2.1p2:
  3865. // A struct-declaration that does not declare an anonymous structure or
  3866. // anonymous union shall contain a struct-declarator-list.
  3867. //
  3868. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3869. // did not permit a struct-declaration without a struct-declarator-list.
  3870. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3871. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3872. // Check for Microsoft C extension: anonymous struct/union member.
  3873. // Handle 2 kinds of anonymous struct/union:
  3874. // struct STRUCT;
  3875. // union UNION;
  3876. // and
  3877. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3878. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3879. if ((Tag && Tag->getDeclName()) ||
  3880. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3881. RecordDecl *Record = nullptr;
  3882. if (Tag)
  3883. Record = dyn_cast<RecordDecl>(Tag);
  3884. else if (const RecordType *RT =
  3885. DS.getRepAsType().get()->getAsStructureType())
  3886. Record = RT->getDecl();
  3887. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3888. Record = UT->getDecl();
  3889. if (Record && getLangOpts().MicrosoftExt) {
  3890. Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
  3891. << Record->isUnion() << DS.getSourceRange();
  3892. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3893. }
  3894. DeclaresAnything = false;
  3895. }
  3896. }
  3897. // Skip all the checks below if we have a type error.
  3898. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3899. (TagD && TagD->isInvalidDecl()))
  3900. return TagD;
  3901. if (getLangOpts().CPlusPlus &&
  3902. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3903. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  3904. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  3905. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  3906. DeclaresAnything = false;
  3907. if (!DS.isMissingDeclaratorOk()) {
  3908. // Customize diagnostic for a typedef missing a name.
  3909. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  3910. Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
  3911. << DS.getSourceRange();
  3912. else
  3913. DeclaresAnything = false;
  3914. }
  3915. if (DS.isModulePrivateSpecified() &&
  3916. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  3917. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  3918. << Tag->getTagKind()
  3919. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  3920. ActOnDocumentableDecl(TagD);
  3921. // C 6.7/2:
  3922. // A declaration [...] shall declare at least a declarator [...], a tag,
  3923. // or the members of an enumeration.
  3924. // C++ [dcl.dcl]p3:
  3925. // [If there are no declarators], and except for the declaration of an
  3926. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  3927. // names into the program, or shall redeclare a name introduced by a
  3928. // previous declaration.
  3929. if (!DeclaresAnything) {
  3930. // In C, we allow this as a (popular) extension / bug. Don't bother
  3931. // producing further diagnostics for redundant qualifiers after this.
  3932. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  3933. return TagD;
  3934. }
  3935. // C++ [dcl.stc]p1:
  3936. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  3937. // init-declarator-list of the declaration shall not be empty.
  3938. // C++ [dcl.fct.spec]p1:
  3939. // If a cv-qualifier appears in a decl-specifier-seq, the
  3940. // init-declarator-list of the declaration shall not be empty.
  3941. //
  3942. // Spurious qualifiers here appear to be valid in C.
  3943. unsigned DiagID = diag::warn_standalone_specifier;
  3944. if (getLangOpts().CPlusPlus)
  3945. DiagID = diag::ext_standalone_specifier;
  3946. // Note that a linkage-specification sets a storage class, but
  3947. // 'extern "C" struct foo;' is actually valid and not theoretically
  3948. // useless.
  3949. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3950. if (SCS == DeclSpec::SCS_mutable)
  3951. // Since mutable is not a viable storage class specifier in C, there is
  3952. // no reason to treat it as an extension. Instead, diagnose as an error.
  3953. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  3954. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  3955. Diag(DS.getStorageClassSpecLoc(), DiagID)
  3956. << DeclSpec::getSpecifierName(SCS);
  3957. }
  3958. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  3959. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  3960. << DeclSpec::getSpecifierName(TSCS);
  3961. if (DS.getTypeQualifiers()) {
  3962. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3963. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  3964. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3965. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  3966. // Restrict is covered above.
  3967. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3968. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  3969. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  3970. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  3971. }
  3972. // Warn about ignored type attributes, for example:
  3973. // __attribute__((aligned)) struct A;
  3974. // Attributes should be placed after tag to apply to type declaration.
  3975. if (!DS.getAttributes().empty()) {
  3976. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  3977. if (TypeSpecType == DeclSpec::TST_class ||
  3978. TypeSpecType == DeclSpec::TST_struct ||
  3979. TypeSpecType == DeclSpec::TST_interface ||
  3980. TypeSpecType == DeclSpec::TST_union ||
  3981. TypeSpecType == DeclSpec::TST_enum) {
  3982. for (const ParsedAttr &AL : DS.getAttributes())
  3983. Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
  3984. << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  3985. }
  3986. }
  3987. return TagD;
  3988. }
  3989. /// We are trying to inject an anonymous member into the given scope;
  3990. /// check if there's an existing declaration that can't be overloaded.
  3991. ///
  3992. /// \return true if this is a forbidden redeclaration
  3993. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  3994. Scope *S,
  3995. DeclContext *Owner,
  3996. DeclarationName Name,
  3997. SourceLocation NameLoc,
  3998. bool IsUnion) {
  3999. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  4000. Sema::ForVisibleRedeclaration);
  4001. if (!SemaRef.LookupName(R, S)) return false;
  4002. // Pick a representative declaration.
  4003. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  4004. assert(PrevDecl && "Expected a non-null Decl");
  4005. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  4006. return false;
  4007. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  4008. << IsUnion << Name;
  4009. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  4010. return true;
  4011. }
  4012. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  4013. /// anonymous struct or union AnonRecord into the owning context Owner
  4014. /// and scope S. This routine will be invoked just after we realize
  4015. /// that an unnamed union or struct is actually an anonymous union or
  4016. /// struct, e.g.,
  4017. ///
  4018. /// @code
  4019. /// union {
  4020. /// int i;
  4021. /// float f;
  4022. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  4023. /// // f into the surrounding scope.x
  4024. /// @endcode
  4025. ///
  4026. /// This routine is recursive, injecting the names of nested anonymous
  4027. /// structs/unions into the owning context and scope as well.
  4028. static bool
  4029. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  4030. RecordDecl *AnonRecord, AccessSpecifier AS,
  4031. SmallVectorImpl<NamedDecl *> &Chaining) {
  4032. bool Invalid = false;
  4033. // Look every FieldDecl and IndirectFieldDecl with a name.
  4034. for (auto *D : AnonRecord->decls()) {
  4035. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  4036. cast<NamedDecl>(D)->getDeclName()) {
  4037. ValueDecl *VD = cast<ValueDecl>(D);
  4038. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  4039. VD->getLocation(),
  4040. AnonRecord->isUnion())) {
  4041. // C++ [class.union]p2:
  4042. // The names of the members of an anonymous union shall be
  4043. // distinct from the names of any other entity in the
  4044. // scope in which the anonymous union is declared.
  4045. Invalid = true;
  4046. } else {
  4047. // C++ [class.union]p2:
  4048. // For the purpose of name lookup, after the anonymous union
  4049. // definition, the members of the anonymous union are
  4050. // considered to have been defined in the scope in which the
  4051. // anonymous union is declared.
  4052. unsigned OldChainingSize = Chaining.size();
  4053. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  4054. Chaining.append(IF->chain_begin(), IF->chain_end());
  4055. else
  4056. Chaining.push_back(VD);
  4057. assert(Chaining.size() >= 2);
  4058. NamedDecl **NamedChain =
  4059. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  4060. for (unsigned i = 0; i < Chaining.size(); i++)
  4061. NamedChain[i] = Chaining[i];
  4062. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  4063. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  4064. VD->getType(), {NamedChain, Chaining.size()});
  4065. for (const auto *Attr : VD->attrs())
  4066. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  4067. IndirectField->setAccess(AS);
  4068. IndirectField->setImplicit();
  4069. SemaRef.PushOnScopeChains(IndirectField, S);
  4070. // That includes picking up the appropriate access specifier.
  4071. if (AS != AS_none) IndirectField->setAccess(AS);
  4072. Chaining.resize(OldChainingSize);
  4073. }
  4074. }
  4075. }
  4076. return Invalid;
  4077. }
  4078. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  4079. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  4080. /// illegal input values are mapped to SC_None.
  4081. static StorageClass
  4082. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  4083. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  4084. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  4085. "Parser allowed 'typedef' as storage class VarDecl.");
  4086. switch (StorageClassSpec) {
  4087. case DeclSpec::SCS_unspecified: return SC_None;
  4088. case DeclSpec::SCS_extern:
  4089. if (DS.isExternInLinkageSpec())
  4090. return SC_None;
  4091. return SC_Extern;
  4092. case DeclSpec::SCS_static: return SC_Static;
  4093. case DeclSpec::SCS_auto: return SC_Auto;
  4094. case DeclSpec::SCS_register: return SC_Register;
  4095. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4096. // Illegal SCSs map to None: error reporting is up to the caller.
  4097. case DeclSpec::SCS_mutable: // Fall through.
  4098. case DeclSpec::SCS_typedef: return SC_None;
  4099. }
  4100. llvm_unreachable("unknown storage class specifier");
  4101. }
  4102. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  4103. assert(Record->hasInClassInitializer());
  4104. for (const auto *I : Record->decls()) {
  4105. const auto *FD = dyn_cast<FieldDecl>(I);
  4106. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  4107. FD = IFD->getAnonField();
  4108. if (FD && FD->hasInClassInitializer())
  4109. return FD->getLocation();
  4110. }
  4111. llvm_unreachable("couldn't find in-class initializer");
  4112. }
  4113. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4114. SourceLocation DefaultInitLoc) {
  4115. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4116. return;
  4117. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  4118. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  4119. }
  4120. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4121. CXXRecordDecl *AnonUnion) {
  4122. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4123. return;
  4124. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  4125. }
  4126. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  4127. /// anonymous structure or union. Anonymous unions are a C++ feature
  4128. /// (C++ [class.union]) and a C11 feature; anonymous structures
  4129. /// are a C11 feature and GNU C++ extension.
  4130. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  4131. AccessSpecifier AS,
  4132. RecordDecl *Record,
  4133. const PrintingPolicy &Policy) {
  4134. DeclContext *Owner = Record->getDeclContext();
  4135. // Diagnose whether this anonymous struct/union is an extension.
  4136. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  4137. Diag(Record->getLocation(), diag::ext_anonymous_union);
  4138. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  4139. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  4140. else if (!Record->isUnion() && !getLangOpts().C11)
  4141. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  4142. // C and C++ require different kinds of checks for anonymous
  4143. // structs/unions.
  4144. bool Invalid = false;
  4145. if (getLangOpts().CPlusPlus) {
  4146. const char *PrevSpec = nullptr;
  4147. unsigned DiagID;
  4148. if (Record->isUnion()) {
  4149. // C++ [class.union]p6:
  4150. // C++17 [class.union.anon]p2:
  4151. // Anonymous unions declared in a named namespace or in the
  4152. // global namespace shall be declared static.
  4153. DeclContext *OwnerScope = Owner->getRedeclContext();
  4154. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  4155. (OwnerScope->isTranslationUnit() ||
  4156. (OwnerScope->isNamespace() &&
  4157. !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
  4158. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  4159. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  4160. // Recover by adding 'static'.
  4161. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  4162. PrevSpec, DiagID, Policy);
  4163. }
  4164. // C++ [class.union]p6:
  4165. // A storage class is not allowed in a declaration of an
  4166. // anonymous union in a class scope.
  4167. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  4168. isa<RecordDecl>(Owner)) {
  4169. Diag(DS.getStorageClassSpecLoc(),
  4170. diag::err_anonymous_union_with_storage_spec)
  4171. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  4172. // Recover by removing the storage specifier.
  4173. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  4174. SourceLocation(),
  4175. PrevSpec, DiagID, Context.getPrintingPolicy());
  4176. }
  4177. }
  4178. // Ignore const/volatile/restrict qualifiers.
  4179. if (DS.getTypeQualifiers()) {
  4180. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4181. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  4182. << Record->isUnion() << "const"
  4183. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  4184. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4185. Diag(DS.getVolatileSpecLoc(),
  4186. diag::ext_anonymous_struct_union_qualified)
  4187. << Record->isUnion() << "volatile"
  4188. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  4189. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  4190. Diag(DS.getRestrictSpecLoc(),
  4191. diag::ext_anonymous_struct_union_qualified)
  4192. << Record->isUnion() << "restrict"
  4193. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  4194. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4195. Diag(DS.getAtomicSpecLoc(),
  4196. diag::ext_anonymous_struct_union_qualified)
  4197. << Record->isUnion() << "_Atomic"
  4198. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  4199. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4200. Diag(DS.getUnalignedSpecLoc(),
  4201. diag::ext_anonymous_struct_union_qualified)
  4202. << Record->isUnion() << "__unaligned"
  4203. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  4204. DS.ClearTypeQualifiers();
  4205. }
  4206. // C++ [class.union]p2:
  4207. // The member-specification of an anonymous union shall only
  4208. // define non-static data members. [Note: nested types and
  4209. // functions cannot be declared within an anonymous union. ]
  4210. for (auto *Mem : Record->decls()) {
  4211. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  4212. // C++ [class.union]p3:
  4213. // An anonymous union shall not have private or protected
  4214. // members (clause 11).
  4215. assert(FD->getAccess() != AS_none);
  4216. if (FD->getAccess() != AS_public) {
  4217. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  4218. << Record->isUnion() << (FD->getAccess() == AS_protected);
  4219. Invalid = true;
  4220. }
  4221. // C++ [class.union]p1
  4222. // An object of a class with a non-trivial constructor, a non-trivial
  4223. // copy constructor, a non-trivial destructor, or a non-trivial copy
  4224. // assignment operator cannot be a member of a union, nor can an
  4225. // array of such objects.
  4226. if (CheckNontrivialField(FD))
  4227. Invalid = true;
  4228. } else if (Mem->isImplicit()) {
  4229. // Any implicit members are fine.
  4230. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  4231. // This is a type that showed up in an
  4232. // elaborated-type-specifier inside the anonymous struct or
  4233. // union, but which actually declares a type outside of the
  4234. // anonymous struct or union. It's okay.
  4235. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  4236. if (!MemRecord->isAnonymousStructOrUnion() &&
  4237. MemRecord->getDeclName()) {
  4238. // Visual C++ allows type definition in anonymous struct or union.
  4239. if (getLangOpts().MicrosoftExt)
  4240. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  4241. << Record->isUnion();
  4242. else {
  4243. // This is a nested type declaration.
  4244. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  4245. << Record->isUnion();
  4246. Invalid = true;
  4247. }
  4248. } else {
  4249. // This is an anonymous type definition within another anonymous type.
  4250. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  4251. // not part of standard C++.
  4252. Diag(MemRecord->getLocation(),
  4253. diag::ext_anonymous_record_with_anonymous_type)
  4254. << Record->isUnion();
  4255. }
  4256. } else if (isa<AccessSpecDecl>(Mem)) {
  4257. // Any access specifier is fine.
  4258. } else if (isa<StaticAssertDecl>(Mem)) {
  4259. // In C++1z, static_assert declarations are also fine.
  4260. } else {
  4261. // We have something that isn't a non-static data
  4262. // member. Complain about it.
  4263. unsigned DK = diag::err_anonymous_record_bad_member;
  4264. if (isa<TypeDecl>(Mem))
  4265. DK = diag::err_anonymous_record_with_type;
  4266. else if (isa<FunctionDecl>(Mem))
  4267. DK = diag::err_anonymous_record_with_function;
  4268. else if (isa<VarDecl>(Mem))
  4269. DK = diag::err_anonymous_record_with_static;
  4270. // Visual C++ allows type definition in anonymous struct or union.
  4271. if (getLangOpts().MicrosoftExt &&
  4272. DK == diag::err_anonymous_record_with_type)
  4273. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  4274. << Record->isUnion();
  4275. else {
  4276. Diag(Mem->getLocation(), DK) << Record->isUnion();
  4277. Invalid = true;
  4278. }
  4279. }
  4280. }
  4281. // C++11 [class.union]p8 (DR1460):
  4282. // At most one variant member of a union may have a
  4283. // brace-or-equal-initializer.
  4284. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  4285. Owner->isRecord())
  4286. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  4287. cast<CXXRecordDecl>(Record));
  4288. }
  4289. if (!Record->isUnion() && !Owner->isRecord()) {
  4290. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  4291. << getLangOpts().CPlusPlus;
  4292. Invalid = true;
  4293. }
  4294. // C++ [dcl.dcl]p3:
  4295. // [If there are no declarators], and except for the declaration of an
  4296. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  4297. // names into the program
  4298. // C++ [class.mem]p2:
  4299. // each such member-declaration shall either declare at least one member
  4300. // name of the class or declare at least one unnamed bit-field
  4301. //
  4302. // For C this is an error even for a named struct, and is diagnosed elsewhere.
  4303. if (getLangOpts().CPlusPlus && Record->field_empty())
  4304. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  4305. // Mock up a declarator.
  4306. Declarator Dc(DS, DeclaratorContext::MemberContext);
  4307. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4308. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  4309. // Create a declaration for this anonymous struct/union.
  4310. NamedDecl *Anon = nullptr;
  4311. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  4312. Anon = FieldDecl::Create(
  4313. Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
  4314. /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
  4315. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4316. /*InitStyle=*/ICIS_NoInit);
  4317. Anon->setAccess(AS);
  4318. if (getLangOpts().CPlusPlus)
  4319. FieldCollector->Add(cast<FieldDecl>(Anon));
  4320. } else {
  4321. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  4322. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  4323. if (SCSpec == DeclSpec::SCS_mutable) {
  4324. // mutable can only appear on non-static class members, so it's always
  4325. // an error here
  4326. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  4327. Invalid = true;
  4328. SC = SC_None;
  4329. }
  4330. Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
  4331. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  4332. Context.getTypeDeclType(Record), TInfo, SC);
  4333. // Default-initialize the implicit variable. This initialization will be
  4334. // trivial in almost all cases, except if a union member has an in-class
  4335. // initializer:
  4336. // union { int n = 0; };
  4337. ActOnUninitializedDecl(Anon);
  4338. }
  4339. Anon->setImplicit();
  4340. // Mark this as an anonymous struct/union type.
  4341. Record->setAnonymousStructOrUnion(true);
  4342. // Add the anonymous struct/union object to the current
  4343. // context. We'll be referencing this object when we refer to one of
  4344. // its members.
  4345. Owner->addDecl(Anon);
  4346. // Inject the members of the anonymous struct/union into the owning
  4347. // context and into the identifier resolver chain for name lookup
  4348. // purposes.
  4349. SmallVector<NamedDecl*, 2> Chain;
  4350. Chain.push_back(Anon);
  4351. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4352. Invalid = true;
  4353. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4354. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4355. Decl *ManglingContextDecl;
  4356. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  4357. NewVD->getDeclContext(), ManglingContextDecl)) {
  4358. Context.setManglingNumber(
  4359. NewVD, MCtx->getManglingNumber(
  4360. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4361. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4362. }
  4363. }
  4364. }
  4365. if (Invalid)
  4366. Anon->setInvalidDecl();
  4367. return Anon;
  4368. }
  4369. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4370. /// Microsoft C anonymous structure.
  4371. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4372. /// Example:
  4373. ///
  4374. /// struct A { int a; };
  4375. /// struct B { struct A; int b; };
  4376. ///
  4377. /// void foo() {
  4378. /// B var;
  4379. /// var.a = 3;
  4380. /// }
  4381. ///
  4382. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4383. RecordDecl *Record) {
  4384. assert(Record && "expected a record!");
  4385. // Mock up a declarator.
  4386. Declarator Dc(DS, DeclaratorContext::TypeNameContext);
  4387. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4388. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4389. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4390. QualType RecTy = Context.getTypeDeclType(Record);
  4391. // Create a declaration for this anonymous struct.
  4392. NamedDecl *Anon =
  4393. FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
  4394. /*IdentifierInfo=*/nullptr, RecTy, TInfo,
  4395. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4396. /*InitStyle=*/ICIS_NoInit);
  4397. Anon->setImplicit();
  4398. // Add the anonymous struct object to the current context.
  4399. CurContext->addDecl(Anon);
  4400. // Inject the members of the anonymous struct into the current
  4401. // context and into the identifier resolver chain for name lookup
  4402. // purposes.
  4403. SmallVector<NamedDecl*, 2> Chain;
  4404. Chain.push_back(Anon);
  4405. RecordDecl *RecordDef = Record->getDefinition();
  4406. if (RequireCompleteType(Anon->getLocation(), RecTy,
  4407. diag::err_field_incomplete) ||
  4408. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4409. AS_none, Chain)) {
  4410. Anon->setInvalidDecl();
  4411. ParentDecl->setInvalidDecl();
  4412. }
  4413. return Anon;
  4414. }
  4415. /// GetNameForDeclarator - Determine the full declaration name for the
  4416. /// given Declarator.
  4417. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4418. return GetNameFromUnqualifiedId(D.getName());
  4419. }
  4420. /// Retrieves the declaration name from a parsed unqualified-id.
  4421. DeclarationNameInfo
  4422. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4423. DeclarationNameInfo NameInfo;
  4424. NameInfo.setLoc(Name.StartLocation);
  4425. switch (Name.getKind()) {
  4426. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  4427. case UnqualifiedIdKind::IK_Identifier:
  4428. NameInfo.setName(Name.Identifier);
  4429. return NameInfo;
  4430. case UnqualifiedIdKind::IK_DeductionGuideName: {
  4431. // C++ [temp.deduct.guide]p3:
  4432. // The simple-template-id shall name a class template specialization.
  4433. // The template-name shall be the same identifier as the template-name
  4434. // of the simple-template-id.
  4435. // These together intend to imply that the template-name shall name a
  4436. // class template.
  4437. // FIXME: template<typename T> struct X {};
  4438. // template<typename T> using Y = X<T>;
  4439. // Y(int) -> Y<int>;
  4440. // satisfies these rules but does not name a class template.
  4441. TemplateName TN = Name.TemplateName.get().get();
  4442. auto *Template = TN.getAsTemplateDecl();
  4443. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  4444. Diag(Name.StartLocation,
  4445. diag::err_deduction_guide_name_not_class_template)
  4446. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  4447. if (Template)
  4448. Diag(Template->getLocation(), diag::note_template_decl_here);
  4449. return DeclarationNameInfo();
  4450. }
  4451. NameInfo.setName(
  4452. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  4453. return NameInfo;
  4454. }
  4455. case UnqualifiedIdKind::IK_OperatorFunctionId:
  4456. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4457. Name.OperatorFunctionId.Operator));
  4458. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  4459. = Name.OperatorFunctionId.SymbolLocations[0];
  4460. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  4461. = Name.EndLocation.getRawEncoding();
  4462. return NameInfo;
  4463. case UnqualifiedIdKind::IK_LiteralOperatorId:
  4464. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4465. Name.Identifier));
  4466. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4467. return NameInfo;
  4468. case UnqualifiedIdKind::IK_ConversionFunctionId: {
  4469. TypeSourceInfo *TInfo;
  4470. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4471. if (Ty.isNull())
  4472. return DeclarationNameInfo();
  4473. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4474. Context.getCanonicalType(Ty)));
  4475. NameInfo.setNamedTypeInfo(TInfo);
  4476. return NameInfo;
  4477. }
  4478. case UnqualifiedIdKind::IK_ConstructorName: {
  4479. TypeSourceInfo *TInfo;
  4480. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4481. if (Ty.isNull())
  4482. return DeclarationNameInfo();
  4483. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4484. Context.getCanonicalType(Ty)));
  4485. NameInfo.setNamedTypeInfo(TInfo);
  4486. return NameInfo;
  4487. }
  4488. case UnqualifiedIdKind::IK_ConstructorTemplateId: {
  4489. // In well-formed code, we can only have a constructor
  4490. // template-id that refers to the current context, so go there
  4491. // to find the actual type being constructed.
  4492. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4493. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4494. return DeclarationNameInfo();
  4495. // Determine the type of the class being constructed.
  4496. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4497. // FIXME: Check two things: that the template-id names the same type as
  4498. // CurClassType, and that the template-id does not occur when the name
  4499. // was qualified.
  4500. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4501. Context.getCanonicalType(CurClassType)));
  4502. // FIXME: should we retrieve TypeSourceInfo?
  4503. NameInfo.setNamedTypeInfo(nullptr);
  4504. return NameInfo;
  4505. }
  4506. case UnqualifiedIdKind::IK_DestructorName: {
  4507. TypeSourceInfo *TInfo;
  4508. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4509. if (Ty.isNull())
  4510. return DeclarationNameInfo();
  4511. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4512. Context.getCanonicalType(Ty)));
  4513. NameInfo.setNamedTypeInfo(TInfo);
  4514. return NameInfo;
  4515. }
  4516. case UnqualifiedIdKind::IK_TemplateId: {
  4517. TemplateName TName = Name.TemplateId->Template.get();
  4518. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4519. return Context.getNameForTemplate(TName, TNameLoc);
  4520. }
  4521. } // switch (Name.getKind())
  4522. llvm_unreachable("Unknown name kind");
  4523. }
  4524. static QualType getCoreType(QualType Ty) {
  4525. do {
  4526. if (Ty->isPointerType() || Ty->isReferenceType())
  4527. Ty = Ty->getPointeeType();
  4528. else if (Ty->isArrayType())
  4529. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4530. else
  4531. return Ty.withoutLocalFastQualifiers();
  4532. } while (true);
  4533. }
  4534. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4535. /// and Definition have "nearly" matching parameters. This heuristic is
  4536. /// used to improve diagnostics in the case where an out-of-line function
  4537. /// definition doesn't match any declaration within the class or namespace.
  4538. /// Also sets Params to the list of indices to the parameters that differ
  4539. /// between the declaration and the definition. If hasSimilarParameters
  4540. /// returns true and Params is empty, then all of the parameters match.
  4541. static bool hasSimilarParameters(ASTContext &Context,
  4542. FunctionDecl *Declaration,
  4543. FunctionDecl *Definition,
  4544. SmallVectorImpl<unsigned> &Params) {
  4545. Params.clear();
  4546. if (Declaration->param_size() != Definition->param_size())
  4547. return false;
  4548. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4549. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4550. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4551. // The parameter types are identical
  4552. if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
  4553. continue;
  4554. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4555. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4556. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4557. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4558. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4559. (DeclTyName && DeclTyName == DefTyName))
  4560. Params.push_back(Idx);
  4561. else // The two parameters aren't even close
  4562. return false;
  4563. }
  4564. return true;
  4565. }
  4566. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4567. /// declarator needs to be rebuilt in the current instantiation.
  4568. /// Any bits of declarator which appear before the name are valid for
  4569. /// consideration here. That's specifically the type in the decl spec
  4570. /// and the base type in any member-pointer chunks.
  4571. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4572. DeclarationName Name) {
  4573. // The types we specifically need to rebuild are:
  4574. // - typenames, typeofs, and decltypes
  4575. // - types which will become injected class names
  4576. // Of course, we also need to rebuild any type referencing such a
  4577. // type. It's safest to just say "dependent", but we call out a
  4578. // few cases here.
  4579. DeclSpec &DS = D.getMutableDeclSpec();
  4580. switch (DS.getTypeSpecType()) {
  4581. case DeclSpec::TST_typename:
  4582. case DeclSpec::TST_typeofType:
  4583. case DeclSpec::TST_underlyingType:
  4584. case DeclSpec::TST_atomic: {
  4585. // Grab the type from the parser.
  4586. TypeSourceInfo *TSI = nullptr;
  4587. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4588. if (T.isNull() || !T->isDependentType()) break;
  4589. // Make sure there's a type source info. This isn't really much
  4590. // of a waste; most dependent types should have type source info
  4591. // attached already.
  4592. if (!TSI)
  4593. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4594. // Rebuild the type in the current instantiation.
  4595. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4596. if (!TSI) return true;
  4597. // Store the new type back in the decl spec.
  4598. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4599. DS.UpdateTypeRep(LocType);
  4600. break;
  4601. }
  4602. case DeclSpec::TST_decltype:
  4603. case DeclSpec::TST_typeofExpr: {
  4604. Expr *E = DS.getRepAsExpr();
  4605. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4606. if (Result.isInvalid()) return true;
  4607. DS.UpdateExprRep(Result.get());
  4608. break;
  4609. }
  4610. default:
  4611. // Nothing to do for these decl specs.
  4612. break;
  4613. }
  4614. // It doesn't matter what order we do this in.
  4615. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4616. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4617. // The only type information in the declarator which can come
  4618. // before the declaration name is the base type of a member
  4619. // pointer.
  4620. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4621. continue;
  4622. // Rebuild the scope specifier in-place.
  4623. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4624. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4625. return true;
  4626. }
  4627. return false;
  4628. }
  4629. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4630. D.setFunctionDefinitionKind(FDK_Declaration);
  4631. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4632. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4633. Dcl && Dcl->getDeclContext()->isFileContext())
  4634. Dcl->setTopLevelDeclInObjCContainer();
  4635. if (getLangOpts().OpenCL)
  4636. setCurrentOpenCLExtensionForDecl(Dcl);
  4637. return Dcl;
  4638. }
  4639. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4640. /// If T is the name of a class, then each of the following shall have a
  4641. /// name different from T:
  4642. /// - every static data member of class T;
  4643. /// - every member function of class T
  4644. /// - every member of class T that is itself a type;
  4645. /// \returns true if the declaration name violates these rules.
  4646. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4647. DeclarationNameInfo NameInfo) {
  4648. DeclarationName Name = NameInfo.getName();
  4649. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  4650. while (Record && Record->isAnonymousStructOrUnion())
  4651. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  4652. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  4653. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4654. return true;
  4655. }
  4656. return false;
  4657. }
  4658. /// Diagnose a declaration whose declarator-id has the given
  4659. /// nested-name-specifier.
  4660. ///
  4661. /// \param SS The nested-name-specifier of the declarator-id.
  4662. ///
  4663. /// \param DC The declaration context to which the nested-name-specifier
  4664. /// resolves.
  4665. ///
  4666. /// \param Name The name of the entity being declared.
  4667. ///
  4668. /// \param Loc The location of the name of the entity being declared.
  4669. ///
  4670. /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
  4671. /// we're declaring an explicit / partial specialization / instantiation.
  4672. ///
  4673. /// \returns true if we cannot safely recover from this error, false otherwise.
  4674. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4675. DeclarationName Name,
  4676. SourceLocation Loc, bool IsTemplateId) {
  4677. DeclContext *Cur = CurContext;
  4678. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4679. Cur = Cur->getParent();
  4680. // If the user provided a superfluous scope specifier that refers back to the
  4681. // class in which the entity is already declared, diagnose and ignore it.
  4682. //
  4683. // class X {
  4684. // void X::f();
  4685. // };
  4686. //
  4687. // Note, it was once ill-formed to give redundant qualification in all
  4688. // contexts, but that rule was removed by DR482.
  4689. if (Cur->Equals(DC)) {
  4690. if (Cur->isRecord()) {
  4691. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4692. : diag::err_member_extra_qualification)
  4693. << Name << FixItHint::CreateRemoval(SS.getRange());
  4694. SS.clear();
  4695. } else {
  4696. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4697. }
  4698. return false;
  4699. }
  4700. // Check whether the qualifying scope encloses the scope of the original
  4701. // declaration. For a template-id, we perform the checks in
  4702. // CheckTemplateSpecializationScope.
  4703. if (!Cur->Encloses(DC) && !IsTemplateId) {
  4704. if (Cur->isRecord())
  4705. Diag(Loc, diag::err_member_qualification)
  4706. << Name << SS.getRange();
  4707. else if (isa<TranslationUnitDecl>(DC))
  4708. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4709. << Name << SS.getRange();
  4710. else if (isa<FunctionDecl>(Cur))
  4711. Diag(Loc, diag::err_invalid_declarator_in_function)
  4712. << Name << SS.getRange();
  4713. else if (isa<BlockDecl>(Cur))
  4714. Diag(Loc, diag::err_invalid_declarator_in_block)
  4715. << Name << SS.getRange();
  4716. else
  4717. Diag(Loc, diag::err_invalid_declarator_scope)
  4718. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4719. return true;
  4720. }
  4721. if (Cur->isRecord()) {
  4722. // Cannot qualify members within a class.
  4723. Diag(Loc, diag::err_member_qualification)
  4724. << Name << SS.getRange();
  4725. SS.clear();
  4726. // C++ constructors and destructors with incorrect scopes can break
  4727. // our AST invariants by having the wrong underlying types. If
  4728. // that's the case, then drop this declaration entirely.
  4729. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4730. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4731. !Context.hasSameType(Name.getCXXNameType(),
  4732. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4733. return true;
  4734. return false;
  4735. }
  4736. // C++11 [dcl.meaning]p1:
  4737. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4738. // not begin with a decltype-specifer"
  4739. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4740. while (SpecLoc.getPrefix())
  4741. SpecLoc = SpecLoc.getPrefix();
  4742. if (dyn_cast_or_null<DecltypeType>(
  4743. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4744. Diag(Loc, diag::err_decltype_in_declarator)
  4745. << SpecLoc.getTypeLoc().getSourceRange();
  4746. return false;
  4747. }
  4748. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4749. MultiTemplateParamsArg TemplateParamLists) {
  4750. // TODO: consider using NameInfo for diagnostic.
  4751. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4752. DeclarationName Name = NameInfo.getName();
  4753. // All of these full declarators require an identifier. If it doesn't have
  4754. // one, the ParsedFreeStandingDeclSpec action should be used.
  4755. if (D.isDecompositionDeclarator()) {
  4756. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  4757. } else if (!Name) {
  4758. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4759. Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
  4760. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4761. return nullptr;
  4762. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4763. return nullptr;
  4764. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4765. // we find one that is.
  4766. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4767. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4768. S = S->getParent();
  4769. DeclContext *DC = CurContext;
  4770. if (D.getCXXScopeSpec().isInvalid())
  4771. D.setInvalidType();
  4772. else if (D.getCXXScopeSpec().isSet()) {
  4773. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4774. UPPC_DeclarationQualifier))
  4775. return nullptr;
  4776. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4777. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4778. if (!DC || isa<EnumDecl>(DC)) {
  4779. // If we could not compute the declaration context, it's because the
  4780. // declaration context is dependent but does not refer to a class,
  4781. // class template, or class template partial specialization. Complain
  4782. // and return early, to avoid the coming semantic disaster.
  4783. Diag(D.getIdentifierLoc(),
  4784. diag::err_template_qualified_declarator_no_match)
  4785. << D.getCXXScopeSpec().getScopeRep()
  4786. << D.getCXXScopeSpec().getRange();
  4787. return nullptr;
  4788. }
  4789. bool IsDependentContext = DC->isDependentContext();
  4790. if (!IsDependentContext &&
  4791. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4792. return nullptr;
  4793. // If a class is incomplete, do not parse entities inside it.
  4794. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4795. Diag(D.getIdentifierLoc(),
  4796. diag::err_member_def_undefined_record)
  4797. << Name << DC << D.getCXXScopeSpec().getRange();
  4798. return nullptr;
  4799. }
  4800. if (!D.getDeclSpec().isFriendSpecified()) {
  4801. if (diagnoseQualifiedDeclaration(
  4802. D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
  4803. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
  4804. if (DC->isRecord())
  4805. return nullptr;
  4806. D.setInvalidType();
  4807. }
  4808. }
  4809. // Check whether we need to rebuild the type of the given
  4810. // declaration in the current instantiation.
  4811. if (EnteringContext && IsDependentContext &&
  4812. TemplateParamLists.size() != 0) {
  4813. ContextRAII SavedContext(*this, DC);
  4814. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4815. D.setInvalidType();
  4816. }
  4817. }
  4818. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4819. QualType R = TInfo->getType();
  4820. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4821. UPPC_DeclarationType))
  4822. D.setInvalidType();
  4823. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4824. forRedeclarationInCurContext());
  4825. // See if this is a redefinition of a variable in the same scope.
  4826. if (!D.getCXXScopeSpec().isSet()) {
  4827. bool IsLinkageLookup = false;
  4828. bool CreateBuiltins = false;
  4829. // If the declaration we're planning to build will be a function
  4830. // or object with linkage, then look for another declaration with
  4831. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4832. //
  4833. // If the declaration we're planning to build will be declared with
  4834. // external linkage in the translation unit, create any builtin with
  4835. // the same name.
  4836. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4837. /* Do nothing*/;
  4838. else if (CurContext->isFunctionOrMethod() &&
  4839. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4840. R->isFunctionType())) {
  4841. IsLinkageLookup = true;
  4842. CreateBuiltins =
  4843. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4844. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4845. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4846. CreateBuiltins = true;
  4847. if (IsLinkageLookup) {
  4848. Previous.clear(LookupRedeclarationWithLinkage);
  4849. Previous.setRedeclarationKind(ForExternalRedeclaration);
  4850. }
  4851. LookupName(Previous, S, CreateBuiltins);
  4852. } else { // Something like "int foo::x;"
  4853. LookupQualifiedName(Previous, DC);
  4854. // C++ [dcl.meaning]p1:
  4855. // When the declarator-id is qualified, the declaration shall refer to a
  4856. // previously declared member of the class or namespace to which the
  4857. // qualifier refers (or, in the case of a namespace, of an element of the
  4858. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4859. // thereof; [...]
  4860. //
  4861. // Note that we already checked the context above, and that we do not have
  4862. // enough information to make sure that Previous contains the declaration
  4863. // we want to match. For example, given:
  4864. //
  4865. // class X {
  4866. // void f();
  4867. // void f(float);
  4868. // };
  4869. //
  4870. // void X::f(int) { } // ill-formed
  4871. //
  4872. // In this case, Previous will point to the overload set
  4873. // containing the two f's declared in X, but neither of them
  4874. // matches.
  4875. // C++ [dcl.meaning]p1:
  4876. // [...] the member shall not merely have been introduced by a
  4877. // using-declaration in the scope of the class or namespace nominated by
  4878. // the nested-name-specifier of the declarator-id.
  4879. RemoveUsingDecls(Previous);
  4880. }
  4881. if (Previous.isSingleResult() &&
  4882. Previous.getFoundDecl()->isTemplateParameter()) {
  4883. // Maybe we will complain about the shadowed template parameter.
  4884. if (!D.isInvalidType())
  4885. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4886. Previous.getFoundDecl());
  4887. // Just pretend that we didn't see the previous declaration.
  4888. Previous.clear();
  4889. }
  4890. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4891. // Forget that the previous declaration is the injected-class-name.
  4892. Previous.clear();
  4893. // In C++, the previous declaration we find might be a tag type
  4894. // (class or enum). In this case, the new declaration will hide the
  4895. // tag type. Note that this applies to functions, function templates, and
  4896. // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
  4897. if (Previous.isSingleTagDecl() &&
  4898. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  4899. (TemplateParamLists.size() == 0 || R->isFunctionType()))
  4900. Previous.clear();
  4901. // Check that there are no default arguments other than in the parameters
  4902. // of a function declaration (C++ only).
  4903. if (getLangOpts().CPlusPlus)
  4904. CheckExtraCXXDefaultArguments(D);
  4905. NamedDecl *New;
  4906. bool AddToScope = true;
  4907. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  4908. if (TemplateParamLists.size()) {
  4909. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  4910. return nullptr;
  4911. }
  4912. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  4913. } else if (R->isFunctionType()) {
  4914. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  4915. TemplateParamLists,
  4916. AddToScope);
  4917. } else {
  4918. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  4919. AddToScope);
  4920. }
  4921. if (!New)
  4922. return nullptr;
  4923. // If this has an identifier and is not a function template specialization,
  4924. // add it to the scope stack.
  4925. if (New->getDeclName() && AddToScope)
  4926. PushOnScopeChains(New, S);
  4927. if (isInOpenMPDeclareTargetContext())
  4928. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  4929. return New;
  4930. }
  4931. /// Helper method to turn variable array types into constant array
  4932. /// types in certain situations which would otherwise be errors (for
  4933. /// GCC compatibility).
  4934. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  4935. ASTContext &Context,
  4936. bool &SizeIsNegative,
  4937. llvm::APSInt &Oversized) {
  4938. // This method tries to turn a variable array into a constant
  4939. // array even when the size isn't an ICE. This is necessary
  4940. // for compatibility with code that depends on gcc's buggy
  4941. // constant expression folding, like struct {char x[(int)(char*)2];}
  4942. SizeIsNegative = false;
  4943. Oversized = 0;
  4944. if (T->isDependentType())
  4945. return QualType();
  4946. QualifierCollector Qs;
  4947. const Type *Ty = Qs.strip(T);
  4948. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  4949. QualType Pointee = PTy->getPointeeType();
  4950. QualType FixedType =
  4951. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  4952. Oversized);
  4953. if (FixedType.isNull()) return FixedType;
  4954. FixedType = Context.getPointerType(FixedType);
  4955. return Qs.apply(Context, FixedType);
  4956. }
  4957. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  4958. QualType Inner = PTy->getInnerType();
  4959. QualType FixedType =
  4960. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  4961. Oversized);
  4962. if (FixedType.isNull()) return FixedType;
  4963. FixedType = Context.getParenType(FixedType);
  4964. return Qs.apply(Context, FixedType);
  4965. }
  4966. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  4967. if (!VLATy)
  4968. return QualType();
  4969. // FIXME: We should probably handle this case
  4970. if (VLATy->getElementType()->isVariablyModifiedType())
  4971. return QualType();
  4972. Expr::EvalResult Result;
  4973. if (!VLATy->getSizeExpr() ||
  4974. !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
  4975. return QualType();
  4976. llvm::APSInt Res = Result.Val.getInt();
  4977. // Check whether the array size is negative.
  4978. if (Res.isSigned() && Res.isNegative()) {
  4979. SizeIsNegative = true;
  4980. return QualType();
  4981. }
  4982. // Check whether the array is too large to be addressed.
  4983. unsigned ActiveSizeBits
  4984. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  4985. Res);
  4986. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  4987. Oversized = Res;
  4988. return QualType();
  4989. }
  4990. return Context.getConstantArrayType(VLATy->getElementType(),
  4991. Res, ArrayType::Normal, 0);
  4992. }
  4993. static void
  4994. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  4995. SrcTL = SrcTL.getUnqualifiedLoc();
  4996. DstTL = DstTL.getUnqualifiedLoc();
  4997. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  4998. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  4999. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  5000. DstPTL.getPointeeLoc());
  5001. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  5002. return;
  5003. }
  5004. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  5005. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  5006. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  5007. DstPTL.getInnerLoc());
  5008. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  5009. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  5010. return;
  5011. }
  5012. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  5013. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  5014. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  5015. TypeLoc DstElemTL = DstATL.getElementLoc();
  5016. DstElemTL.initializeFullCopy(SrcElemTL);
  5017. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  5018. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  5019. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  5020. }
  5021. /// Helper method to turn variable array types into constant array
  5022. /// types in certain situations which would otherwise be errors (for
  5023. /// GCC compatibility).
  5024. static TypeSourceInfo*
  5025. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  5026. ASTContext &Context,
  5027. bool &SizeIsNegative,
  5028. llvm::APSInt &Oversized) {
  5029. QualType FixedTy
  5030. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  5031. SizeIsNegative, Oversized);
  5032. if (FixedTy.isNull())
  5033. return nullptr;
  5034. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  5035. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  5036. FixedTInfo->getTypeLoc());
  5037. return FixedTInfo;
  5038. }
  5039. /// Register the given locally-scoped extern "C" declaration so
  5040. /// that it can be found later for redeclarations. We include any extern "C"
  5041. /// declaration that is not visible in the translation unit here, not just
  5042. /// function-scope declarations.
  5043. void
  5044. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  5045. if (!getLangOpts().CPlusPlus &&
  5046. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  5047. // Don't need to track declarations in the TU in C.
  5048. return;
  5049. // Note that we have a locally-scoped external with this name.
  5050. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  5051. }
  5052. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  5053. // FIXME: We can have multiple results via __attribute__((overloadable)).
  5054. auto Result = Context.getExternCContextDecl()->lookup(Name);
  5055. return Result.empty() ? nullptr : *Result.begin();
  5056. }
  5057. /// Diagnose function specifiers on a declaration of an identifier that
  5058. /// does not identify a function.
  5059. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  5060. // FIXME: We should probably indicate the identifier in question to avoid
  5061. // confusion for constructs like "virtual int a(), b;"
  5062. if (DS.isVirtualSpecified())
  5063. Diag(DS.getVirtualSpecLoc(),
  5064. diag::err_virtual_non_function);
  5065. if (DS.hasExplicitSpecifier())
  5066. Diag(DS.getExplicitSpecLoc(),
  5067. diag::err_explicit_non_function);
  5068. if (DS.isNoreturnSpecified())
  5069. Diag(DS.getNoreturnSpecLoc(),
  5070. diag::err_noreturn_non_function);
  5071. }
  5072. NamedDecl*
  5073. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  5074. TypeSourceInfo *TInfo, LookupResult &Previous) {
  5075. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  5076. if (D.getCXXScopeSpec().isSet()) {
  5077. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  5078. << D.getCXXScopeSpec().getRange();
  5079. D.setInvalidType();
  5080. // Pretend we didn't see the scope specifier.
  5081. DC = CurContext;
  5082. Previous.clear();
  5083. }
  5084. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5085. if (D.getDeclSpec().isInlineSpecified())
  5086. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5087. << getLangOpts().CPlusPlus17;
  5088. if (D.getDeclSpec().hasConstexprSpecifier())
  5089. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5090. << 1 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
  5091. if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
  5092. if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
  5093. Diag(D.getName().StartLocation,
  5094. diag::err_deduction_guide_invalid_specifier)
  5095. << "typedef";
  5096. else
  5097. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  5098. << D.getName().getSourceRange();
  5099. return nullptr;
  5100. }
  5101. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  5102. if (!NewTD) return nullptr;
  5103. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5104. ProcessDeclAttributes(S, NewTD, D);
  5105. CheckTypedefForVariablyModifiedType(S, NewTD);
  5106. bool Redeclaration = D.isRedeclaration();
  5107. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  5108. D.setRedeclaration(Redeclaration);
  5109. return ND;
  5110. }
  5111. void
  5112. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  5113. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  5114. // then it shall have block scope.
  5115. // Note that variably modified types must be fixed before merging the decl so
  5116. // that redeclarations will match.
  5117. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  5118. QualType T = TInfo->getType();
  5119. if (T->isVariablyModifiedType()) {
  5120. setFunctionHasBranchProtectedScope();
  5121. if (S->getFnParent() == nullptr) {
  5122. bool SizeIsNegative;
  5123. llvm::APSInt Oversized;
  5124. TypeSourceInfo *FixedTInfo =
  5125. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5126. SizeIsNegative,
  5127. Oversized);
  5128. if (FixedTInfo) {
  5129. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  5130. NewTD->setTypeSourceInfo(FixedTInfo);
  5131. } else {
  5132. if (SizeIsNegative)
  5133. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  5134. else if (T->isVariableArrayType())
  5135. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  5136. else if (Oversized.getBoolValue())
  5137. Diag(NewTD->getLocation(), diag::err_array_too_large)
  5138. << Oversized.toString(10);
  5139. else
  5140. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  5141. NewTD->setInvalidDecl();
  5142. }
  5143. }
  5144. }
  5145. }
  5146. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  5147. /// declares a typedef-name, either using the 'typedef' type specifier or via
  5148. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  5149. NamedDecl*
  5150. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  5151. LookupResult &Previous, bool &Redeclaration) {
  5152. // Find the shadowed declaration before filtering for scope.
  5153. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
  5154. // Merge the decl with the existing one if appropriate. If the decl is
  5155. // in an outer scope, it isn't the same thing.
  5156. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  5157. /*AllowInlineNamespace*/false);
  5158. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  5159. if (!Previous.empty()) {
  5160. Redeclaration = true;
  5161. MergeTypedefNameDecl(S, NewTD, Previous);
  5162. }
  5163. if (ShadowedDecl && !Redeclaration)
  5164. CheckShadow(NewTD, ShadowedDecl, Previous);
  5165. // If this is the C FILE type, notify the AST context.
  5166. if (IdentifierInfo *II = NewTD->getIdentifier())
  5167. if (!NewTD->isInvalidDecl() &&
  5168. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5169. if (II->isStr("FILE"))
  5170. Context.setFILEDecl(NewTD);
  5171. else if (II->isStr("jmp_buf"))
  5172. Context.setjmp_bufDecl(NewTD);
  5173. else if (II->isStr("sigjmp_buf"))
  5174. Context.setsigjmp_bufDecl(NewTD);
  5175. else if (II->isStr("ucontext_t"))
  5176. Context.setucontext_tDecl(NewTD);
  5177. }
  5178. return NewTD;
  5179. }
  5180. /// Determines whether the given declaration is an out-of-scope
  5181. /// previous declaration.
  5182. ///
  5183. /// This routine should be invoked when name lookup has found a
  5184. /// previous declaration (PrevDecl) that is not in the scope where a
  5185. /// new declaration by the same name is being introduced. If the new
  5186. /// declaration occurs in a local scope, previous declarations with
  5187. /// linkage may still be considered previous declarations (C99
  5188. /// 6.2.2p4-5, C++ [basic.link]p6).
  5189. ///
  5190. /// \param PrevDecl the previous declaration found by name
  5191. /// lookup
  5192. ///
  5193. /// \param DC the context in which the new declaration is being
  5194. /// declared.
  5195. ///
  5196. /// \returns true if PrevDecl is an out-of-scope previous declaration
  5197. /// for a new delcaration with the same name.
  5198. static bool
  5199. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  5200. ASTContext &Context) {
  5201. if (!PrevDecl)
  5202. return false;
  5203. if (!PrevDecl->hasLinkage())
  5204. return false;
  5205. if (Context.getLangOpts().CPlusPlus) {
  5206. // C++ [basic.link]p6:
  5207. // If there is a visible declaration of an entity with linkage
  5208. // having the same name and type, ignoring entities declared
  5209. // outside the innermost enclosing namespace scope, the block
  5210. // scope declaration declares that same entity and receives the
  5211. // linkage of the previous declaration.
  5212. DeclContext *OuterContext = DC->getRedeclContext();
  5213. if (!OuterContext->isFunctionOrMethod())
  5214. // This rule only applies to block-scope declarations.
  5215. return false;
  5216. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  5217. if (PrevOuterContext->isRecord())
  5218. // We found a member function: ignore it.
  5219. return false;
  5220. // Find the innermost enclosing namespace for the new and
  5221. // previous declarations.
  5222. OuterContext = OuterContext->getEnclosingNamespaceContext();
  5223. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  5224. // The previous declaration is in a different namespace, so it
  5225. // isn't the same function.
  5226. if (!OuterContext->Equals(PrevOuterContext))
  5227. return false;
  5228. }
  5229. return true;
  5230. }
  5231. static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
  5232. CXXScopeSpec &SS = D.getCXXScopeSpec();
  5233. if (!SS.isSet()) return;
  5234. DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
  5235. }
  5236. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  5237. QualType type = decl->getType();
  5238. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  5239. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  5240. // Various kinds of declaration aren't allowed to be __autoreleasing.
  5241. unsigned kind = -1U;
  5242. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5243. if (var->hasAttr<BlocksAttr>())
  5244. kind = 0; // __block
  5245. else if (!var->hasLocalStorage())
  5246. kind = 1; // global
  5247. } else if (isa<ObjCIvarDecl>(decl)) {
  5248. kind = 3; // ivar
  5249. } else if (isa<FieldDecl>(decl)) {
  5250. kind = 2; // field
  5251. }
  5252. if (kind != -1U) {
  5253. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  5254. << kind;
  5255. }
  5256. } else if (lifetime == Qualifiers::OCL_None) {
  5257. // Try to infer lifetime.
  5258. if (!type->isObjCLifetimeType())
  5259. return false;
  5260. lifetime = type->getObjCARCImplicitLifetime();
  5261. type = Context.getLifetimeQualifiedType(type, lifetime);
  5262. decl->setType(type);
  5263. }
  5264. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5265. // Thread-local variables cannot have lifetime.
  5266. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  5267. var->getTLSKind()) {
  5268. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  5269. << var->getType();
  5270. return true;
  5271. }
  5272. }
  5273. return false;
  5274. }
  5275. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  5276. // Ensure that an auto decl is deduced otherwise the checks below might cache
  5277. // the wrong linkage.
  5278. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  5279. // 'weak' only applies to declarations with external linkage.
  5280. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  5281. if (!ND.isExternallyVisible()) {
  5282. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  5283. ND.dropAttr<WeakAttr>();
  5284. }
  5285. }
  5286. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  5287. if (ND.isExternallyVisible()) {
  5288. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  5289. ND.dropAttr<WeakRefAttr>();
  5290. ND.dropAttr<AliasAttr>();
  5291. }
  5292. }
  5293. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  5294. if (VD->hasInit()) {
  5295. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  5296. assert(VD->isThisDeclarationADefinition() &&
  5297. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  5298. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  5299. VD->dropAttr<AliasAttr>();
  5300. }
  5301. }
  5302. }
  5303. // 'selectany' only applies to externally visible variable declarations.
  5304. // It does not apply to functions.
  5305. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  5306. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  5307. S.Diag(Attr->getLocation(),
  5308. diag::err_attribute_selectany_non_extern_data);
  5309. ND.dropAttr<SelectAnyAttr>();
  5310. }
  5311. }
  5312. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  5313. auto *VD = dyn_cast<VarDecl>(&ND);
  5314. bool IsAnonymousNS = false;
  5315. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5316. if (VD) {
  5317. const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
  5318. while (NS && !IsAnonymousNS) {
  5319. IsAnonymousNS = NS->isAnonymousNamespace();
  5320. NS = dyn_cast<NamespaceDecl>(NS->getParent());
  5321. }
  5322. }
  5323. // dll attributes require external linkage. Static locals may have external
  5324. // linkage but still cannot be explicitly imported or exported.
  5325. // In Microsoft mode, a variable defined in anonymous namespace must have
  5326. // external linkage in order to be exported.
  5327. bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
  5328. if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
  5329. (!AnonNSInMicrosoftMode &&
  5330. (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
  5331. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  5332. << &ND << Attr;
  5333. ND.setInvalidDecl();
  5334. }
  5335. }
  5336. // Virtual functions cannot be marked as 'notail'.
  5337. if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
  5338. if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
  5339. if (MD->isVirtual()) {
  5340. S.Diag(ND.getLocation(),
  5341. diag::err_invalid_attribute_on_virtual_function)
  5342. << Attr;
  5343. ND.dropAttr<NotTailCalledAttr>();
  5344. }
  5345. // Check the attributes on the function type, if any.
  5346. if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
  5347. // Don't declare this variable in the second operand of the for-statement;
  5348. // GCC miscompiles that by ending its lifetime before evaluating the
  5349. // third operand. See gcc.gnu.org/PR86769.
  5350. AttributedTypeLoc ATL;
  5351. for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
  5352. (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
  5353. TL = ATL.getModifiedLoc()) {
  5354. // The [[lifetimebound]] attribute can be applied to the implicit object
  5355. // parameter of a non-static member function (other than a ctor or dtor)
  5356. // by applying it to the function type.
  5357. if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
  5358. const auto *MD = dyn_cast<CXXMethodDecl>(FD);
  5359. if (!MD || MD->isStatic()) {
  5360. S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
  5361. << !MD << A->getRange();
  5362. } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
  5363. S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
  5364. << isa<CXXDestructorDecl>(MD) << A->getRange();
  5365. }
  5366. }
  5367. }
  5368. }
  5369. }
  5370. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  5371. NamedDecl *NewDecl,
  5372. bool IsSpecialization,
  5373. bool IsDefinition) {
  5374. if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
  5375. return;
  5376. bool IsTemplate = false;
  5377. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  5378. OldDecl = OldTD->getTemplatedDecl();
  5379. IsTemplate = true;
  5380. if (!IsSpecialization)
  5381. IsDefinition = false;
  5382. }
  5383. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  5384. NewDecl = NewTD->getTemplatedDecl();
  5385. IsTemplate = true;
  5386. }
  5387. if (!OldDecl || !NewDecl)
  5388. return;
  5389. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  5390. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5391. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5392. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5393. // dllimport and dllexport are inheritable attributes so we have to exclude
  5394. // inherited attribute instances.
  5395. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5396. (NewExportAttr && !NewExportAttr->isInherited());
  5397. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5398. // the only exception being explicit specializations.
  5399. // Implicitly generated declarations are also excluded for now because there
  5400. // is no other way to switch these to use dllimport or dllexport.
  5401. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5402. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5403. // Allow with a warning for free functions and global variables.
  5404. bool JustWarn = false;
  5405. if (!OldDecl->isCXXClassMember()) {
  5406. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5407. if (VD && !VD->getDescribedVarTemplate())
  5408. JustWarn = true;
  5409. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5410. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5411. JustWarn = true;
  5412. }
  5413. // We cannot change a declaration that's been used because IR has already
  5414. // been emitted. Dllimported functions will still work though (modulo
  5415. // address equality) as they can use the thunk.
  5416. if (OldDecl->isUsed())
  5417. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5418. JustWarn = false;
  5419. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5420. : diag::err_attribute_dll_redeclaration;
  5421. S.Diag(NewDecl->getLocation(), DiagID)
  5422. << NewDecl
  5423. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5424. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5425. if (!JustWarn) {
  5426. NewDecl->setInvalidDecl();
  5427. return;
  5428. }
  5429. }
  5430. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5431. // exceptions being inline function definitions (except for function
  5432. // templates), local extern declarations, qualified friend declarations or
  5433. // special MSVC extension: in the last case, the declaration is treated as if
  5434. // it were marked dllexport.
  5435. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5436. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5437. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5438. // Ignore static data because out-of-line definitions are diagnosed
  5439. // separately.
  5440. IsStaticDataMember = VD->isStaticDataMember();
  5441. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5442. VarDecl::DeclarationOnly;
  5443. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5444. IsInline = FD->isInlined();
  5445. IsQualifiedFriend = FD->getQualifier() &&
  5446. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5447. }
  5448. if (OldImportAttr && !HasNewAttr &&
  5449. (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
  5450. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5451. if (IsMicrosoft && IsDefinition) {
  5452. S.Diag(NewDecl->getLocation(),
  5453. diag::warn_redeclaration_without_import_attribute)
  5454. << NewDecl;
  5455. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5456. NewDecl->dropAttr<DLLImportAttr>();
  5457. NewDecl->addAttr(::new (S.Context) DLLExportAttr(
  5458. NewImportAttr->getRange(), S.Context,
  5459. NewImportAttr->getSpellingListIndex()));
  5460. } else {
  5461. S.Diag(NewDecl->getLocation(),
  5462. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5463. << NewDecl << OldImportAttr;
  5464. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5465. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5466. OldDecl->dropAttr<DLLImportAttr>();
  5467. NewDecl->dropAttr<DLLImportAttr>();
  5468. }
  5469. } else if (IsInline && OldImportAttr && !IsMicrosoft) {
  5470. // In MinGW, seeing a function declared inline drops the dllimport
  5471. // attribute.
  5472. OldDecl->dropAttr<DLLImportAttr>();
  5473. NewDecl->dropAttr<DLLImportAttr>();
  5474. S.Diag(NewDecl->getLocation(),
  5475. diag::warn_dllimport_dropped_from_inline_function)
  5476. << NewDecl << OldImportAttr;
  5477. }
  5478. // A specialization of a class template member function is processed here
  5479. // since it's a redeclaration. If the parent class is dllexport, the
  5480. // specialization inherits that attribute. This doesn't happen automatically
  5481. // since the parent class isn't instantiated until later.
  5482. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
  5483. if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
  5484. !NewImportAttr && !NewExportAttr) {
  5485. if (const DLLExportAttr *ParentExportAttr =
  5486. MD->getParent()->getAttr<DLLExportAttr>()) {
  5487. DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
  5488. NewAttr->setInherited(true);
  5489. NewDecl->addAttr(NewAttr);
  5490. }
  5491. }
  5492. }
  5493. }
  5494. /// Given that we are within the definition of the given function,
  5495. /// will that definition behave like C99's 'inline', where the
  5496. /// definition is discarded except for optimization purposes?
  5497. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  5498. // Try to avoid calling GetGVALinkageForFunction.
  5499. // All cases of this require the 'inline' keyword.
  5500. if (!FD->isInlined()) return false;
  5501. // This is only possible in C++ with the gnu_inline attribute.
  5502. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  5503. return false;
  5504. // Okay, go ahead and call the relatively-more-expensive function.
  5505. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  5506. }
  5507. /// Determine whether a variable is extern "C" prior to attaching
  5508. /// an initializer. We can't just call isExternC() here, because that
  5509. /// will also compute and cache whether the declaration is externally
  5510. /// visible, which might change when we attach the initializer.
  5511. ///
  5512. /// This can only be used if the declaration is known to not be a
  5513. /// redeclaration of an internal linkage declaration.
  5514. ///
  5515. /// For instance:
  5516. ///
  5517. /// auto x = []{};
  5518. ///
  5519. /// Attaching the initializer here makes this declaration not externally
  5520. /// visible, because its type has internal linkage.
  5521. ///
  5522. /// FIXME: This is a hack.
  5523. template<typename T>
  5524. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  5525. if (S.getLangOpts().CPlusPlus) {
  5526. // In C++, the overloadable attribute negates the effects of extern "C".
  5527. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  5528. return false;
  5529. // So do CUDA's host/device attributes.
  5530. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  5531. D->template hasAttr<CUDAHostAttr>()))
  5532. return false;
  5533. }
  5534. return D->isExternC();
  5535. }
  5536. static bool shouldConsiderLinkage(const VarDecl *VD) {
  5537. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  5538. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
  5539. isa<OMPDeclareMapperDecl>(DC))
  5540. return VD->hasExternalStorage();
  5541. if (DC->isFileContext())
  5542. return true;
  5543. if (DC->isRecord())
  5544. return false;
  5545. llvm_unreachable("Unexpected context");
  5546. }
  5547. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  5548. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  5549. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  5550. isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
  5551. return true;
  5552. if (DC->isRecord())
  5553. return false;
  5554. llvm_unreachable("Unexpected context");
  5555. }
  5556. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  5557. ParsedAttr::Kind Kind) {
  5558. // Check decl attributes on the DeclSpec.
  5559. if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
  5560. return true;
  5561. // Walk the declarator structure, checking decl attributes that were in a type
  5562. // position to the decl itself.
  5563. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  5564. if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
  5565. return true;
  5566. }
  5567. // Finally, check attributes on the decl itself.
  5568. return PD.getAttributes().hasAttribute(Kind);
  5569. }
  5570. /// Adjust the \c DeclContext for a function or variable that might be a
  5571. /// function-local external declaration.
  5572. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  5573. if (!DC->isFunctionOrMethod())
  5574. return false;
  5575. // If this is a local extern function or variable declared within a function
  5576. // template, don't add it into the enclosing namespace scope until it is
  5577. // instantiated; it might have a dependent type right now.
  5578. if (DC->isDependentContext())
  5579. return true;
  5580. // C++11 [basic.link]p7:
  5581. // When a block scope declaration of an entity with linkage is not found to
  5582. // refer to some other declaration, then that entity is a member of the
  5583. // innermost enclosing namespace.
  5584. //
  5585. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  5586. // semantically-enclosing namespace, not a lexically-enclosing one.
  5587. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  5588. DC = DC->getParent();
  5589. return true;
  5590. }
  5591. /// Returns true if given declaration has external C language linkage.
  5592. static bool isDeclExternC(const Decl *D) {
  5593. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  5594. return FD->isExternC();
  5595. if (const auto *VD = dyn_cast<VarDecl>(D))
  5596. return VD->isExternC();
  5597. llvm_unreachable("Unknown type of decl!");
  5598. }
  5599. NamedDecl *Sema::ActOnVariableDeclarator(
  5600. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  5601. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  5602. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  5603. QualType R = TInfo->getType();
  5604. DeclarationName Name = GetNameForDeclarator(D).getName();
  5605. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5606. if (D.isDecompositionDeclarator()) {
  5607. // Take the name of the first declarator as our name for diagnostic
  5608. // purposes.
  5609. auto &Decomp = D.getDecompositionDeclarator();
  5610. if (!Decomp.bindings().empty()) {
  5611. II = Decomp.bindings()[0].Name;
  5612. Name = II;
  5613. }
  5614. } else if (!II) {
  5615. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
  5616. return nullptr;
  5617. }
  5618. if (getLangOpts().OpenCL) {
  5619. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  5620. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  5621. // argument.
  5622. if (R->isImageType() || R->isPipeType()) {
  5623. Diag(D.getIdentifierLoc(),
  5624. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  5625. << R;
  5626. D.setInvalidType();
  5627. return nullptr;
  5628. }
  5629. // OpenCL v1.2 s6.9.r:
  5630. // The event type cannot be used to declare a program scope variable.
  5631. // OpenCL v2.0 s6.9.q:
  5632. // The clk_event_t and reserve_id_t types cannot be declared in program scope.
  5633. if (NULL == S->getParent()) {
  5634. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  5635. Diag(D.getIdentifierLoc(),
  5636. diag::err_invalid_type_for_program_scope_var) << R;
  5637. D.setInvalidType();
  5638. return nullptr;
  5639. }
  5640. }
  5641. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  5642. QualType NR = R;
  5643. while (NR->isPointerType()) {
  5644. if (NR->isFunctionPointerType()) {
  5645. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
  5646. D.setInvalidType();
  5647. break;
  5648. }
  5649. NR = NR->getPointeeType();
  5650. }
  5651. if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  5652. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5653. // half array type (unless the cl_khr_fp16 extension is enabled).
  5654. if (Context.getBaseElementType(R)->isHalfType()) {
  5655. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5656. D.setInvalidType();
  5657. }
  5658. }
  5659. if (R->isSamplerT()) {
  5660. // OpenCL v1.2 s6.9.b p4:
  5661. // The sampler type cannot be used with the __local and __global address
  5662. // space qualifiers.
  5663. if (R.getAddressSpace() == LangAS::opencl_local ||
  5664. R.getAddressSpace() == LangAS::opencl_global) {
  5665. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5666. }
  5667. // OpenCL v1.2 s6.12.14.1:
  5668. // A global sampler must be declared with either the constant address
  5669. // space qualifier or with the const qualifier.
  5670. if (DC->isTranslationUnit() &&
  5671. !(R.getAddressSpace() == LangAS::opencl_constant ||
  5672. R.isConstQualified())) {
  5673. Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
  5674. D.setInvalidType();
  5675. }
  5676. }
  5677. // OpenCL v1.2 s6.9.r:
  5678. // The event type cannot be used with the __local, __constant and __global
  5679. // address space qualifiers.
  5680. if (R->isEventT()) {
  5681. if (R.getAddressSpace() != LangAS::opencl_private) {
  5682. Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
  5683. D.setInvalidType();
  5684. }
  5685. }
  5686. // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
  5687. // supported. OpenCL C does not support thread_local either, and
  5688. // also reject all other thread storage class specifiers.
  5689. DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
  5690. if (TSC != TSCS_unspecified) {
  5691. bool IsCXX = getLangOpts().OpenCLCPlusPlus;
  5692. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5693. diag::err_opencl_unknown_type_specifier)
  5694. << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
  5695. << DeclSpec::getSpecifierName(TSC) << 1;
  5696. D.setInvalidType();
  5697. return nullptr;
  5698. }
  5699. }
  5700. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  5701. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  5702. // dllimport globals without explicit storage class are treated as extern. We
  5703. // have to change the storage class this early to get the right DeclContext.
  5704. if (SC == SC_None && !DC->isRecord() &&
  5705. hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
  5706. !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
  5707. SC = SC_Extern;
  5708. DeclContext *OriginalDC = DC;
  5709. bool IsLocalExternDecl = SC == SC_Extern &&
  5710. adjustContextForLocalExternDecl(DC);
  5711. if (SCSpec == DeclSpec::SCS_mutable) {
  5712. // mutable can only appear on non-static class members, so it's always
  5713. // an error here
  5714. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5715. D.setInvalidType();
  5716. SC = SC_None;
  5717. }
  5718. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5719. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5720. D.getDeclSpec().getStorageClassSpecLoc())) {
  5721. // In C++11, the 'register' storage class specifier is deprecated.
  5722. // Suppress the warning in system macros, it's used in macros in some
  5723. // popular C system headers, such as in glibc's htonl() macro.
  5724. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5725. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  5726. : diag::warn_deprecated_register)
  5727. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5728. }
  5729. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5730. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5731. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5732. // appear in the declaration specifiers in an external declaration.
  5733. // Global Register+Asm is a GNU extension we support.
  5734. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5735. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5736. D.setInvalidType();
  5737. }
  5738. }
  5739. bool IsMemberSpecialization = false;
  5740. bool IsVariableTemplateSpecialization = false;
  5741. bool IsPartialSpecialization = false;
  5742. bool IsVariableTemplate = false;
  5743. VarDecl *NewVD = nullptr;
  5744. VarTemplateDecl *NewTemplate = nullptr;
  5745. TemplateParameterList *TemplateParams = nullptr;
  5746. if (!getLangOpts().CPlusPlus) {
  5747. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
  5748. II, R, TInfo, SC);
  5749. if (R->getContainedDeducedType())
  5750. ParsingInitForAutoVars.insert(NewVD);
  5751. if (D.isInvalidType())
  5752. NewVD->setInvalidDecl();
  5753. if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
  5754. NewVD->hasLocalStorage())
  5755. checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
  5756. NTCUC_AutoVar, NTCUK_Destruct);
  5757. } else {
  5758. bool Invalid = false;
  5759. if (DC->isRecord() && !CurContext->isRecord()) {
  5760. // This is an out-of-line definition of a static data member.
  5761. switch (SC) {
  5762. case SC_None:
  5763. break;
  5764. case SC_Static:
  5765. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5766. diag::err_static_out_of_line)
  5767. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5768. break;
  5769. case SC_Auto:
  5770. case SC_Register:
  5771. case SC_Extern:
  5772. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5773. // to names of variables declared in a block or to function parameters.
  5774. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5775. // of class members
  5776. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5777. diag::err_storage_class_for_static_member)
  5778. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5779. break;
  5780. case SC_PrivateExtern:
  5781. llvm_unreachable("C storage class in c++!");
  5782. }
  5783. }
  5784. if (SC == SC_Static && CurContext->isRecord()) {
  5785. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5786. if (RD->isLocalClass())
  5787. Diag(D.getIdentifierLoc(),
  5788. diag::err_static_data_member_not_allowed_in_local_class)
  5789. << Name << RD->getDeclName();
  5790. // C++98 [class.union]p1: If a union contains a static data member,
  5791. // the program is ill-formed. C++11 drops this restriction.
  5792. if (RD->isUnion())
  5793. Diag(D.getIdentifierLoc(),
  5794. getLangOpts().CPlusPlus11
  5795. ? diag::warn_cxx98_compat_static_data_member_in_union
  5796. : diag::ext_static_data_member_in_union) << Name;
  5797. // We conservatively disallow static data members in anonymous structs.
  5798. else if (!RD->getDeclName())
  5799. Diag(D.getIdentifierLoc(),
  5800. diag::err_static_data_member_not_allowed_in_anon_struct)
  5801. << Name << RD->isUnion();
  5802. }
  5803. }
  5804. // Match up the template parameter lists with the scope specifier, then
  5805. // determine whether we have a template or a template specialization.
  5806. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5807. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  5808. D.getCXXScopeSpec(),
  5809. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  5810. ? D.getName().TemplateId
  5811. : nullptr,
  5812. TemplateParamLists,
  5813. /*never a friend*/ false, IsMemberSpecialization, Invalid);
  5814. if (TemplateParams) {
  5815. if (!TemplateParams->size() &&
  5816. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  5817. // There is an extraneous 'template<>' for this variable. Complain
  5818. // about it, but allow the declaration of the variable.
  5819. Diag(TemplateParams->getTemplateLoc(),
  5820. diag::err_template_variable_noparams)
  5821. << II
  5822. << SourceRange(TemplateParams->getTemplateLoc(),
  5823. TemplateParams->getRAngleLoc());
  5824. TemplateParams = nullptr;
  5825. } else {
  5826. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  5827. // This is an explicit specialization or a partial specialization.
  5828. // FIXME: Check that we can declare a specialization here.
  5829. IsVariableTemplateSpecialization = true;
  5830. IsPartialSpecialization = TemplateParams->size() > 0;
  5831. } else { // if (TemplateParams->size() > 0)
  5832. // This is a template declaration.
  5833. IsVariableTemplate = true;
  5834. // Check that we can declare a template here.
  5835. if (CheckTemplateDeclScope(S, TemplateParams))
  5836. return nullptr;
  5837. // Only C++1y supports variable templates (N3651).
  5838. Diag(D.getIdentifierLoc(),
  5839. getLangOpts().CPlusPlus14
  5840. ? diag::warn_cxx11_compat_variable_template
  5841. : diag::ext_variable_template);
  5842. }
  5843. }
  5844. } else {
  5845. assert((Invalid ||
  5846. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
  5847. "should have a 'template<>' for this decl");
  5848. }
  5849. if (IsVariableTemplateSpecialization) {
  5850. SourceLocation TemplateKWLoc =
  5851. TemplateParamLists.size() > 0
  5852. ? TemplateParamLists[0]->getTemplateLoc()
  5853. : SourceLocation();
  5854. DeclResult Res = ActOnVarTemplateSpecialization(
  5855. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5856. IsPartialSpecialization);
  5857. if (Res.isInvalid())
  5858. return nullptr;
  5859. NewVD = cast<VarDecl>(Res.get());
  5860. AddToScope = false;
  5861. } else if (D.isDecompositionDeclarator()) {
  5862. NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
  5863. D.getIdentifierLoc(), R, TInfo, SC,
  5864. Bindings);
  5865. } else
  5866. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
  5867. D.getIdentifierLoc(), II, R, TInfo, SC);
  5868. // If this is supposed to be a variable template, create it as such.
  5869. if (IsVariableTemplate) {
  5870. NewTemplate =
  5871. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5872. TemplateParams, NewVD);
  5873. NewVD->setDescribedVarTemplate(NewTemplate);
  5874. }
  5875. // If this decl has an auto type in need of deduction, make a note of the
  5876. // Decl so we can diagnose uses of it in its own initializer.
  5877. if (R->getContainedDeducedType())
  5878. ParsingInitForAutoVars.insert(NewVD);
  5879. if (D.isInvalidType() || Invalid) {
  5880. NewVD->setInvalidDecl();
  5881. if (NewTemplate)
  5882. NewTemplate->setInvalidDecl();
  5883. }
  5884. SetNestedNameSpecifier(*this, NewVD, D);
  5885. // If we have any template parameter lists that don't directly belong to
  5886. // the variable (matching the scope specifier), store them.
  5887. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5888. if (TemplateParamLists.size() > VDTemplateParamLists)
  5889. NewVD->setTemplateParameterListsInfo(
  5890. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  5891. if (D.getDeclSpec().hasConstexprSpecifier()) {
  5892. NewVD->setConstexpr(true);
  5893. // C++1z [dcl.spec.constexpr]p1:
  5894. // A static data member declared with the constexpr specifier is
  5895. // implicitly an inline variable.
  5896. if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
  5897. NewVD->setImplicitlyInline();
  5898. if (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval)
  5899. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  5900. diag::err_constexpr_wrong_decl_kind)
  5901. << /*consteval*/ 1;
  5902. }
  5903. }
  5904. if (D.getDeclSpec().isInlineSpecified()) {
  5905. if (!getLangOpts().CPlusPlus) {
  5906. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5907. << 0;
  5908. } else if (CurContext->isFunctionOrMethod()) {
  5909. // 'inline' is not allowed on block scope variable declaration.
  5910. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5911. diag::err_inline_declaration_block_scope) << Name
  5912. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  5913. } else {
  5914. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5915. getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
  5916. : diag::ext_inline_variable);
  5917. NewVD->setInlineSpecified();
  5918. }
  5919. }
  5920. // Set the lexical context. If the declarator has a C++ scope specifier, the
  5921. // lexical context will be different from the semantic context.
  5922. NewVD->setLexicalDeclContext(CurContext);
  5923. if (NewTemplate)
  5924. NewTemplate->setLexicalDeclContext(CurContext);
  5925. if (IsLocalExternDecl) {
  5926. if (D.isDecompositionDeclarator())
  5927. for (auto *B : Bindings)
  5928. B->setLocalExternDecl();
  5929. else
  5930. NewVD->setLocalExternDecl();
  5931. }
  5932. bool EmitTLSUnsupportedError = false;
  5933. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  5934. // C++11 [dcl.stc]p4:
  5935. // When thread_local is applied to a variable of block scope the
  5936. // storage-class-specifier static is implied if it does not appear
  5937. // explicitly.
  5938. // Core issue: 'static' is not implied if the variable is declared
  5939. // 'extern'.
  5940. if (NewVD->hasLocalStorage() &&
  5941. (SCSpec != DeclSpec::SCS_unspecified ||
  5942. TSCS != DeclSpec::TSCS_thread_local ||
  5943. !DC->isFunctionOrMethod()))
  5944. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5945. diag::err_thread_non_global)
  5946. << DeclSpec::getSpecifierName(TSCS);
  5947. else if (!Context.getTargetInfo().isTLSSupported()) {
  5948. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  5949. // Postpone error emission until we've collected attributes required to
  5950. // figure out whether it's a host or device variable and whether the
  5951. // error should be ignored.
  5952. EmitTLSUnsupportedError = true;
  5953. // We still need to mark the variable as TLS so it shows up in AST with
  5954. // proper storage class for other tools to use even if we're not going
  5955. // to emit any code for it.
  5956. NewVD->setTSCSpec(TSCS);
  5957. } else
  5958. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5959. diag::err_thread_unsupported);
  5960. } else
  5961. NewVD->setTSCSpec(TSCS);
  5962. }
  5963. // C99 6.7.4p3
  5964. // An inline definition of a function with external linkage shall
  5965. // not contain a definition of a modifiable object with static or
  5966. // thread storage duration...
  5967. // We only apply this when the function is required to be defined
  5968. // elsewhere, i.e. when the function is not 'extern inline'. Note
  5969. // that a local variable with thread storage duration still has to
  5970. // be marked 'static'. Also note that it's possible to get these
  5971. // semantics in C++ using __attribute__((gnu_inline)).
  5972. if (SC == SC_Static && S->getFnParent() != nullptr &&
  5973. !NewVD->getType().isConstQualified()) {
  5974. FunctionDecl *CurFD = getCurFunctionDecl();
  5975. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  5976. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5977. diag::warn_static_local_in_extern_inline);
  5978. MaybeSuggestAddingStaticToDecl(CurFD);
  5979. }
  5980. }
  5981. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5982. if (IsVariableTemplateSpecialization)
  5983. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5984. << (IsPartialSpecialization ? 1 : 0)
  5985. << FixItHint::CreateRemoval(
  5986. D.getDeclSpec().getModulePrivateSpecLoc());
  5987. else if (IsMemberSpecialization)
  5988. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5989. << 2
  5990. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5991. else if (NewVD->hasLocalStorage())
  5992. Diag(NewVD->getLocation(), diag::err_module_private_local)
  5993. << 0 << NewVD->getDeclName()
  5994. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5995. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5996. else {
  5997. NewVD->setModulePrivate();
  5998. if (NewTemplate)
  5999. NewTemplate->setModulePrivate();
  6000. for (auto *B : Bindings)
  6001. B->setModulePrivate();
  6002. }
  6003. }
  6004. // Handle attributes prior to checking for duplicates in MergeVarDecl
  6005. ProcessDeclAttributes(S, NewVD, D);
  6006. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  6007. if (EmitTLSUnsupportedError &&
  6008. ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
  6009. (getLangOpts().OpenMPIsDevice &&
  6010. NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
  6011. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6012. diag::err_thread_unsupported);
  6013. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  6014. // storage [duration]."
  6015. if (SC == SC_None && S->getFnParent() != nullptr &&
  6016. (NewVD->hasAttr<CUDASharedAttr>() ||
  6017. NewVD->hasAttr<CUDAConstantAttr>())) {
  6018. NewVD->setStorageClass(SC_Static);
  6019. }
  6020. }
  6021. // Ensure that dllimport globals without explicit storage class are treated as
  6022. // extern. The storage class is set above using parsed attributes. Now we can
  6023. // check the VarDecl itself.
  6024. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  6025. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  6026. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  6027. // In auto-retain/release, infer strong retension for variables of
  6028. // retainable type.
  6029. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  6030. NewVD->setInvalidDecl();
  6031. // Handle GNU asm-label extension (encoded as an attribute).
  6032. if (Expr *E = (Expr*)D.getAsmLabel()) {
  6033. // The parser guarantees this is a string.
  6034. StringLiteral *SE = cast<StringLiteral>(E);
  6035. StringRef Label = SE->getString();
  6036. if (S->getFnParent() != nullptr) {
  6037. switch (SC) {
  6038. case SC_None:
  6039. case SC_Auto:
  6040. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  6041. break;
  6042. case SC_Register:
  6043. // Local Named register
  6044. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  6045. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  6046. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6047. break;
  6048. case SC_Static:
  6049. case SC_Extern:
  6050. case SC_PrivateExtern:
  6051. break;
  6052. }
  6053. } else if (SC == SC_Register) {
  6054. // Global Named register
  6055. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  6056. const auto &TI = Context.getTargetInfo();
  6057. bool HasSizeMismatch;
  6058. if (!TI.isValidGCCRegisterName(Label))
  6059. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6060. else if (!TI.validateGlobalRegisterVariable(Label,
  6061. Context.getTypeSize(R),
  6062. HasSizeMismatch))
  6063. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  6064. else if (HasSizeMismatch)
  6065. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  6066. }
  6067. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  6068. Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
  6069. NewVD->setInvalidDecl(true);
  6070. }
  6071. }
  6072. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  6073. Context, Label, 0));
  6074. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  6075. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6076. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  6077. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6078. if (isDeclExternC(NewVD)) {
  6079. NewVD->addAttr(I->second);
  6080. ExtnameUndeclaredIdentifiers.erase(I);
  6081. } else
  6082. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  6083. << /*Variable*/1 << NewVD;
  6084. }
  6085. }
  6086. // Find the shadowed declaration before filtering for scope.
  6087. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  6088. ? getShadowedDeclaration(NewVD, Previous)
  6089. : nullptr;
  6090. // Don't consider existing declarations that are in a different
  6091. // scope and are out-of-semantic-context declarations (if the new
  6092. // declaration has linkage).
  6093. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  6094. D.getCXXScopeSpec().isNotEmpty() ||
  6095. IsMemberSpecialization ||
  6096. IsVariableTemplateSpecialization);
  6097. // Check whether the previous declaration is in the same block scope. This
  6098. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  6099. if (getLangOpts().CPlusPlus &&
  6100. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  6101. NewVD->setPreviousDeclInSameBlockScope(
  6102. Previous.isSingleResult() && !Previous.isShadowed() &&
  6103. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  6104. if (!getLangOpts().CPlusPlus) {
  6105. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6106. } else {
  6107. // If this is an explicit specialization of a static data member, check it.
  6108. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  6109. CheckMemberSpecialization(NewVD, Previous))
  6110. NewVD->setInvalidDecl();
  6111. // Merge the decl with the existing one if appropriate.
  6112. if (!Previous.empty()) {
  6113. if (Previous.isSingleResult() &&
  6114. isa<FieldDecl>(Previous.getFoundDecl()) &&
  6115. D.getCXXScopeSpec().isSet()) {
  6116. // The user tried to define a non-static data member
  6117. // out-of-line (C++ [dcl.meaning]p1).
  6118. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  6119. << D.getCXXScopeSpec().getRange();
  6120. Previous.clear();
  6121. NewVD->setInvalidDecl();
  6122. }
  6123. } else if (D.getCXXScopeSpec().isSet()) {
  6124. // No previous declaration in the qualifying scope.
  6125. Diag(D.getIdentifierLoc(), diag::err_no_member)
  6126. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  6127. << D.getCXXScopeSpec().getRange();
  6128. NewVD->setInvalidDecl();
  6129. }
  6130. if (!IsVariableTemplateSpecialization)
  6131. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6132. if (NewTemplate) {
  6133. VarTemplateDecl *PrevVarTemplate =
  6134. NewVD->getPreviousDecl()
  6135. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  6136. : nullptr;
  6137. // Check the template parameter list of this declaration, possibly
  6138. // merging in the template parameter list from the previous variable
  6139. // template declaration.
  6140. if (CheckTemplateParameterList(
  6141. TemplateParams,
  6142. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  6143. : nullptr,
  6144. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  6145. DC->isDependentContext())
  6146. ? TPC_ClassTemplateMember
  6147. : TPC_VarTemplate))
  6148. NewVD->setInvalidDecl();
  6149. // If we are providing an explicit specialization of a static variable
  6150. // template, make a note of that.
  6151. if (PrevVarTemplate &&
  6152. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  6153. PrevVarTemplate->setMemberSpecialization();
  6154. }
  6155. }
  6156. // Diagnose shadowed variables iff this isn't a redeclaration.
  6157. if (ShadowedDecl && !D.isRedeclaration())
  6158. CheckShadow(NewVD, ShadowedDecl, Previous);
  6159. ProcessPragmaWeak(S, NewVD);
  6160. // If this is the first declaration of an extern C variable, update
  6161. // the map of such variables.
  6162. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  6163. isIncompleteDeclExternC(*this, NewVD))
  6164. RegisterLocallyScopedExternCDecl(NewVD, S);
  6165. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  6166. Decl *ManglingContextDecl;
  6167. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  6168. NewVD->getDeclContext(), ManglingContextDecl)) {
  6169. Context.setManglingNumber(
  6170. NewVD, MCtx->getManglingNumber(
  6171. NewVD, getMSManglingNumber(getLangOpts(), S)));
  6172. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  6173. }
  6174. }
  6175. // Special handling of variable named 'main'.
  6176. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  6177. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  6178. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  6179. // C++ [basic.start.main]p3
  6180. // A program that declares a variable main at global scope is ill-formed.
  6181. if (getLangOpts().CPlusPlus)
  6182. Diag(D.getBeginLoc(), diag::err_main_global_variable);
  6183. // In C, and external-linkage variable named main results in undefined
  6184. // behavior.
  6185. else if (NewVD->hasExternalFormalLinkage())
  6186. Diag(D.getBeginLoc(), diag::warn_main_redefined);
  6187. }
  6188. if (D.isRedeclaration() && !Previous.empty()) {
  6189. NamedDecl *Prev = Previous.getRepresentativeDecl();
  6190. checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
  6191. D.isFunctionDefinition());
  6192. }
  6193. if (NewTemplate) {
  6194. if (NewVD->isInvalidDecl())
  6195. NewTemplate->setInvalidDecl();
  6196. ActOnDocumentableDecl(NewTemplate);
  6197. return NewTemplate;
  6198. }
  6199. if (IsMemberSpecialization && !NewVD->isInvalidDecl())
  6200. CompleteMemberSpecialization(NewVD, Previous);
  6201. return NewVD;
  6202. }
  6203. /// Enum describing the %select options in diag::warn_decl_shadow.
  6204. enum ShadowedDeclKind {
  6205. SDK_Local,
  6206. SDK_Global,
  6207. SDK_StaticMember,
  6208. SDK_Field,
  6209. SDK_Typedef,
  6210. SDK_Using
  6211. };
  6212. /// Determine what kind of declaration we're shadowing.
  6213. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  6214. const DeclContext *OldDC) {
  6215. if (isa<TypeAliasDecl>(ShadowedDecl))
  6216. return SDK_Using;
  6217. else if (isa<TypedefDecl>(ShadowedDecl))
  6218. return SDK_Typedef;
  6219. else if (isa<RecordDecl>(OldDC))
  6220. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  6221. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  6222. }
  6223. /// Return the location of the capture if the given lambda captures the given
  6224. /// variable \p VD, or an invalid source location otherwise.
  6225. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  6226. const VarDecl *VD) {
  6227. for (const Capture &Capture : LSI->Captures) {
  6228. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  6229. return Capture.getLocation();
  6230. }
  6231. return SourceLocation();
  6232. }
  6233. static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
  6234. const LookupResult &R) {
  6235. // Only diagnose if we're shadowing an unambiguous field or variable.
  6236. if (R.getResultKind() != LookupResult::Found)
  6237. return false;
  6238. // Return false if warning is ignored.
  6239. return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
  6240. }
  6241. /// Return the declaration shadowed by the given variable \p D, or null
  6242. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6243. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  6244. const LookupResult &R) {
  6245. if (!shouldWarnIfShadowedDecl(Diags, R))
  6246. return nullptr;
  6247. // Don't diagnose declarations at file scope.
  6248. if (D->hasGlobalStorage())
  6249. return nullptr;
  6250. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6251. return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
  6252. ? ShadowedDecl
  6253. : nullptr;
  6254. }
  6255. /// Return the declaration shadowed by the given typedef \p D, or null
  6256. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6257. NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
  6258. const LookupResult &R) {
  6259. // Don't warn if typedef declaration is part of a class
  6260. if (D->getDeclContext()->isRecord())
  6261. return nullptr;
  6262. if (!shouldWarnIfShadowedDecl(Diags, R))
  6263. return nullptr;
  6264. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6265. return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
  6266. }
  6267. /// Diagnose variable or built-in function shadowing. Implements
  6268. /// -Wshadow.
  6269. ///
  6270. /// This method is called whenever a VarDecl is added to a "useful"
  6271. /// scope.
  6272. ///
  6273. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  6274. /// \param R the lookup of the name
  6275. ///
  6276. void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
  6277. const LookupResult &R) {
  6278. DeclContext *NewDC = D->getDeclContext();
  6279. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  6280. // Fields are not shadowed by variables in C++ static methods.
  6281. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  6282. if (MD->isStatic())
  6283. return;
  6284. // Fields shadowed by constructor parameters are a special case. Usually
  6285. // the constructor initializes the field with the parameter.
  6286. if (isa<CXXConstructorDecl>(NewDC))
  6287. if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
  6288. // Remember that this was shadowed so we can either warn about its
  6289. // modification or its existence depending on warning settings.
  6290. ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
  6291. return;
  6292. }
  6293. }
  6294. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  6295. if (shadowedVar->isExternC()) {
  6296. // For shadowing external vars, make sure that we point to the global
  6297. // declaration, not a locally scoped extern declaration.
  6298. for (auto I : shadowedVar->redecls())
  6299. if (I->isFileVarDecl()) {
  6300. ShadowedDecl = I;
  6301. break;
  6302. }
  6303. }
  6304. DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
  6305. unsigned WarningDiag = diag::warn_decl_shadow;
  6306. SourceLocation CaptureLoc;
  6307. if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
  6308. isa<CXXMethodDecl>(NewDC)) {
  6309. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  6310. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  6311. if (RD->getLambdaCaptureDefault() == LCD_None) {
  6312. // Try to avoid warnings for lambdas with an explicit capture list.
  6313. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  6314. // Warn only when the lambda captures the shadowed decl explicitly.
  6315. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  6316. if (CaptureLoc.isInvalid())
  6317. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  6318. } else {
  6319. // Remember that this was shadowed so we can avoid the warning if the
  6320. // shadowed decl isn't captured and the warning settings allow it.
  6321. cast<LambdaScopeInfo>(getCurFunction())
  6322. ->ShadowingDecls.push_back(
  6323. {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
  6324. return;
  6325. }
  6326. }
  6327. if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
  6328. // A variable can't shadow a local variable in an enclosing scope, if
  6329. // they are separated by a non-capturing declaration context.
  6330. for (DeclContext *ParentDC = NewDC;
  6331. ParentDC && !ParentDC->Equals(OldDC);
  6332. ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
  6333. // Only block literals, captured statements, and lambda expressions
  6334. // can capture; other scopes don't.
  6335. if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
  6336. !isLambdaCallOperator(ParentDC)) {
  6337. return;
  6338. }
  6339. }
  6340. }
  6341. }
  6342. }
  6343. // Only warn about certain kinds of shadowing for class members.
  6344. if (NewDC && NewDC->isRecord()) {
  6345. // In particular, don't warn about shadowing non-class members.
  6346. if (!OldDC->isRecord())
  6347. return;
  6348. // TODO: should we warn about static data members shadowing
  6349. // static data members from base classes?
  6350. // TODO: don't diagnose for inaccessible shadowed members.
  6351. // This is hard to do perfectly because we might friend the
  6352. // shadowing context, but that's just a false negative.
  6353. }
  6354. DeclarationName Name = R.getLookupName();
  6355. // Emit warning and note.
  6356. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  6357. return;
  6358. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  6359. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  6360. if (!CaptureLoc.isInvalid())
  6361. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6362. << Name << /*explicitly*/ 1;
  6363. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6364. }
  6365. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  6366. /// when these variables are captured by the lambda.
  6367. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  6368. for (const auto &Shadow : LSI->ShadowingDecls) {
  6369. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  6370. // Try to avoid the warning when the shadowed decl isn't captured.
  6371. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  6372. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6373. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  6374. ? diag::warn_decl_shadow_uncaptured_local
  6375. : diag::warn_decl_shadow)
  6376. << Shadow.VD->getDeclName()
  6377. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  6378. if (!CaptureLoc.isInvalid())
  6379. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6380. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  6381. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6382. }
  6383. }
  6384. /// Check -Wshadow without the advantage of a previous lookup.
  6385. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  6386. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  6387. return;
  6388. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  6389. Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  6390. LookupName(R, S);
  6391. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  6392. CheckShadow(D, ShadowedDecl, R);
  6393. }
  6394. /// Check if 'E', which is an expression that is about to be modified, refers
  6395. /// to a constructor parameter that shadows a field.
  6396. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  6397. // Quickly ignore expressions that can't be shadowing ctor parameters.
  6398. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  6399. return;
  6400. E = E->IgnoreParenImpCasts();
  6401. auto *DRE = dyn_cast<DeclRefExpr>(E);
  6402. if (!DRE)
  6403. return;
  6404. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  6405. auto I = ShadowingDecls.find(D);
  6406. if (I == ShadowingDecls.end())
  6407. return;
  6408. const NamedDecl *ShadowedDecl = I->second;
  6409. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6410. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  6411. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  6412. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6413. // Avoid issuing multiple warnings about the same decl.
  6414. ShadowingDecls.erase(I);
  6415. }
  6416. /// Check for conflict between this global or extern "C" declaration and
  6417. /// previous global or extern "C" declarations. This is only used in C++.
  6418. template<typename T>
  6419. static bool checkGlobalOrExternCConflict(
  6420. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  6421. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  6422. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  6423. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  6424. // The common case: this global doesn't conflict with any extern "C"
  6425. // declaration.
  6426. return false;
  6427. }
  6428. if (Prev) {
  6429. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  6430. // Both the old and new declarations have C language linkage. This is a
  6431. // redeclaration.
  6432. Previous.clear();
  6433. Previous.addDecl(Prev);
  6434. return true;
  6435. }
  6436. // This is a global, non-extern "C" declaration, and there is a previous
  6437. // non-global extern "C" declaration. Diagnose if this is a variable
  6438. // declaration.
  6439. if (!isa<VarDecl>(ND))
  6440. return false;
  6441. } else {
  6442. // The declaration is extern "C". Check for any declaration in the
  6443. // translation unit which might conflict.
  6444. if (IsGlobal) {
  6445. // We have already performed the lookup into the translation unit.
  6446. IsGlobal = false;
  6447. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6448. I != E; ++I) {
  6449. if (isa<VarDecl>(*I)) {
  6450. Prev = *I;
  6451. break;
  6452. }
  6453. }
  6454. } else {
  6455. DeclContext::lookup_result R =
  6456. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  6457. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  6458. I != E; ++I) {
  6459. if (isa<VarDecl>(*I)) {
  6460. Prev = *I;
  6461. break;
  6462. }
  6463. // FIXME: If we have any other entity with this name in global scope,
  6464. // the declaration is ill-formed, but that is a defect: it breaks the
  6465. // 'stat' hack, for instance. Only variables can have mangled name
  6466. // clashes with extern "C" declarations, so only they deserve a
  6467. // diagnostic.
  6468. }
  6469. }
  6470. if (!Prev)
  6471. return false;
  6472. }
  6473. // Use the first declaration's location to ensure we point at something which
  6474. // is lexically inside an extern "C" linkage-spec.
  6475. assert(Prev && "should have found a previous declaration to diagnose");
  6476. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  6477. Prev = FD->getFirstDecl();
  6478. else
  6479. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  6480. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  6481. << IsGlobal << ND;
  6482. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  6483. << IsGlobal;
  6484. return false;
  6485. }
  6486. /// Apply special rules for handling extern "C" declarations. Returns \c true
  6487. /// if we have found that this is a redeclaration of some prior entity.
  6488. ///
  6489. /// Per C++ [dcl.link]p6:
  6490. /// Two declarations [for a function or variable] with C language linkage
  6491. /// with the same name that appear in different scopes refer to the same
  6492. /// [entity]. An entity with C language linkage shall not be declared with
  6493. /// the same name as an entity in global scope.
  6494. template<typename T>
  6495. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  6496. LookupResult &Previous) {
  6497. if (!S.getLangOpts().CPlusPlus) {
  6498. // In C, when declaring a global variable, look for a corresponding 'extern'
  6499. // variable declared in function scope. We don't need this in C++, because
  6500. // we find local extern decls in the surrounding file-scope DeclContext.
  6501. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6502. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  6503. Previous.clear();
  6504. Previous.addDecl(Prev);
  6505. return true;
  6506. }
  6507. }
  6508. return false;
  6509. }
  6510. // A declaration in the translation unit can conflict with an extern "C"
  6511. // declaration.
  6512. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  6513. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  6514. // An extern "C" declaration can conflict with a declaration in the
  6515. // translation unit or can be a redeclaration of an extern "C" declaration
  6516. // in another scope.
  6517. if (isIncompleteDeclExternC(S,ND))
  6518. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  6519. // Neither global nor extern "C": nothing to do.
  6520. return false;
  6521. }
  6522. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  6523. // If the decl is already known invalid, don't check it.
  6524. if (NewVD->isInvalidDecl())
  6525. return;
  6526. QualType T = NewVD->getType();
  6527. // Defer checking an 'auto' type until its initializer is attached.
  6528. if (T->isUndeducedType())
  6529. return;
  6530. if (NewVD->hasAttrs())
  6531. CheckAlignasUnderalignment(NewVD);
  6532. if (T->isObjCObjectType()) {
  6533. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  6534. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  6535. T = Context.getObjCObjectPointerType(T);
  6536. NewVD->setType(T);
  6537. }
  6538. // Emit an error if an address space was applied to decl with local storage.
  6539. // This includes arrays of objects with address space qualifiers, but not
  6540. // automatic variables that point to other address spaces.
  6541. // ISO/IEC TR 18037 S5.1.2
  6542. if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
  6543. T.getAddressSpace() != LangAS::Default) {
  6544. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
  6545. NewVD->setInvalidDecl();
  6546. return;
  6547. }
  6548. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  6549. // scope.
  6550. if (getLangOpts().OpenCLVersion == 120 &&
  6551. !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
  6552. NewVD->isStaticLocal()) {
  6553. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  6554. NewVD->setInvalidDecl();
  6555. return;
  6556. }
  6557. if (getLangOpts().OpenCL) {
  6558. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  6559. if (NewVD->hasAttr<BlocksAttr>()) {
  6560. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  6561. return;
  6562. }
  6563. if (T->isBlockPointerType()) {
  6564. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  6565. // can't use 'extern' storage class.
  6566. if (!T.isConstQualified()) {
  6567. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  6568. << 0 /*const*/;
  6569. NewVD->setInvalidDecl();
  6570. return;
  6571. }
  6572. if (NewVD->hasExternalStorage()) {
  6573. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  6574. NewVD->setInvalidDecl();
  6575. return;
  6576. }
  6577. }
  6578. // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
  6579. // __constant address space.
  6580. // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
  6581. // variables inside a function can also be declared in the global
  6582. // address space.
  6583. // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local
  6584. // address space additionally.
  6585. // FIXME: Add local AS for OpenCL C++.
  6586. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  6587. NewVD->hasExternalStorage()) {
  6588. if (!T->isSamplerT() &&
  6589. !(T.getAddressSpace() == LangAS::opencl_constant ||
  6590. (T.getAddressSpace() == LangAS::opencl_global &&
  6591. (getLangOpts().OpenCLVersion == 200 ||
  6592. getLangOpts().OpenCLCPlusPlus)))) {
  6593. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  6594. if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
  6595. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6596. << Scope << "global or constant";
  6597. else
  6598. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6599. << Scope << "constant";
  6600. NewVD->setInvalidDecl();
  6601. return;
  6602. }
  6603. } else {
  6604. if (T.getAddressSpace() == LangAS::opencl_global) {
  6605. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6606. << 1 /*is any function*/ << "global";
  6607. NewVD->setInvalidDecl();
  6608. return;
  6609. }
  6610. if (T.getAddressSpace() == LangAS::opencl_constant ||
  6611. T.getAddressSpace() == LangAS::opencl_local) {
  6612. FunctionDecl *FD = getCurFunctionDecl();
  6613. // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
  6614. // in functions.
  6615. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  6616. if (T.getAddressSpace() == LangAS::opencl_constant)
  6617. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6618. << 0 /*non-kernel only*/ << "constant";
  6619. else
  6620. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6621. << 0 /*non-kernel only*/ << "local";
  6622. NewVD->setInvalidDecl();
  6623. return;
  6624. }
  6625. // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
  6626. // in the outermost scope of a kernel function.
  6627. if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
  6628. if (!getCurScope()->isFunctionScope()) {
  6629. if (T.getAddressSpace() == LangAS::opencl_constant)
  6630. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6631. << "constant";
  6632. else
  6633. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6634. << "local";
  6635. NewVD->setInvalidDecl();
  6636. return;
  6637. }
  6638. }
  6639. } else if (T.getAddressSpace() != LangAS::opencl_private) {
  6640. // Do not allow other address spaces on automatic variable.
  6641. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
  6642. NewVD->setInvalidDecl();
  6643. return;
  6644. }
  6645. }
  6646. }
  6647. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  6648. && !NewVD->hasAttr<BlocksAttr>()) {
  6649. if (getLangOpts().getGC() != LangOptions::NonGC)
  6650. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  6651. else {
  6652. assert(!getLangOpts().ObjCAutoRefCount);
  6653. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  6654. }
  6655. }
  6656. bool isVM = T->isVariablyModifiedType();
  6657. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  6658. NewVD->hasAttr<BlocksAttr>())
  6659. setFunctionHasBranchProtectedScope();
  6660. if ((isVM && NewVD->hasLinkage()) ||
  6661. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  6662. bool SizeIsNegative;
  6663. llvm::APSInt Oversized;
  6664. TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
  6665. NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
  6666. QualType FixedT;
  6667. if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
  6668. FixedT = FixedTInfo->getType();
  6669. else if (FixedTInfo) {
  6670. // Type and type-as-written are canonically different. We need to fix up
  6671. // both types separately.
  6672. FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  6673. Oversized);
  6674. }
  6675. if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
  6676. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  6677. // FIXME: This won't give the correct result for
  6678. // int a[10][n];
  6679. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  6680. if (NewVD->isFileVarDecl())
  6681. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  6682. << SizeRange;
  6683. else if (NewVD->isStaticLocal())
  6684. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  6685. << SizeRange;
  6686. else
  6687. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  6688. << SizeRange;
  6689. NewVD->setInvalidDecl();
  6690. return;
  6691. }
  6692. if (!FixedTInfo) {
  6693. if (NewVD->isFileVarDecl())
  6694. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  6695. else
  6696. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  6697. NewVD->setInvalidDecl();
  6698. return;
  6699. }
  6700. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  6701. NewVD->setType(FixedT);
  6702. NewVD->setTypeSourceInfo(FixedTInfo);
  6703. }
  6704. if (T->isVoidType()) {
  6705. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  6706. // of objects and functions.
  6707. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  6708. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  6709. << T;
  6710. NewVD->setInvalidDecl();
  6711. return;
  6712. }
  6713. }
  6714. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  6715. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  6716. NewVD->setInvalidDecl();
  6717. return;
  6718. }
  6719. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  6720. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  6721. NewVD->setInvalidDecl();
  6722. return;
  6723. }
  6724. if (NewVD->isConstexpr() && !T->isDependentType() &&
  6725. RequireLiteralType(NewVD->getLocation(), T,
  6726. diag::err_constexpr_var_non_literal)) {
  6727. NewVD->setInvalidDecl();
  6728. return;
  6729. }
  6730. }
  6731. /// Perform semantic checking on a newly-created variable
  6732. /// declaration.
  6733. ///
  6734. /// This routine performs all of the type-checking required for a
  6735. /// variable declaration once it has been built. It is used both to
  6736. /// check variables after they have been parsed and their declarators
  6737. /// have been translated into a declaration, and to check variables
  6738. /// that have been instantiated from a template.
  6739. ///
  6740. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  6741. ///
  6742. /// Returns true if the variable declaration is a redeclaration.
  6743. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  6744. CheckVariableDeclarationType(NewVD);
  6745. // If the decl is already known invalid, don't check it.
  6746. if (NewVD->isInvalidDecl())
  6747. return false;
  6748. // If we did not find anything by this name, look for a non-visible
  6749. // extern "C" declaration with the same name.
  6750. if (Previous.empty() &&
  6751. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  6752. Previous.setShadowed();
  6753. if (!Previous.empty()) {
  6754. MergeVarDecl(NewVD, Previous);
  6755. return true;
  6756. }
  6757. return false;
  6758. }
  6759. namespace {
  6760. struct FindOverriddenMethod {
  6761. Sema *S;
  6762. CXXMethodDecl *Method;
  6763. /// Member lookup function that determines whether a given C++
  6764. /// method overrides a method in a base class, to be used with
  6765. /// CXXRecordDecl::lookupInBases().
  6766. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6767. RecordDecl *BaseRecord =
  6768. Specifier->getType()->getAs<RecordType>()->getDecl();
  6769. DeclarationName Name = Method->getDeclName();
  6770. // FIXME: Do we care about other names here too?
  6771. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6772. // We really want to find the base class destructor here.
  6773. QualType T = S->Context.getTypeDeclType(BaseRecord);
  6774. CanQualType CT = S->Context.getCanonicalType(T);
  6775. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  6776. }
  6777. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6778. Path.Decls = Path.Decls.slice(1)) {
  6779. NamedDecl *D = Path.Decls.front();
  6780. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6781. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  6782. return true;
  6783. }
  6784. }
  6785. return false;
  6786. }
  6787. };
  6788. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  6789. } // end anonymous namespace
  6790. /// Report an error regarding overriding, along with any relevant
  6791. /// overridden methods.
  6792. ///
  6793. /// \param DiagID the primary error to report.
  6794. /// \param MD the overriding method.
  6795. /// \param OEK which overrides to include as notes.
  6796. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  6797. OverrideErrorKind OEK = OEK_All) {
  6798. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  6799. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  6800. // This check (& the OEK parameter) could be replaced by a predicate, but
  6801. // without lambdas that would be overkill. This is still nicer than writing
  6802. // out the diag loop 3 times.
  6803. if ((OEK == OEK_All) ||
  6804. (OEK == OEK_NonDeleted && !O->isDeleted()) ||
  6805. (OEK == OEK_Deleted && O->isDeleted()))
  6806. S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
  6807. }
  6808. }
  6809. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  6810. /// and if so, check that it's a valid override and remember it.
  6811. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  6812. // Look for methods in base classes that this method might override.
  6813. CXXBasePaths Paths;
  6814. FindOverriddenMethod FOM;
  6815. FOM.Method = MD;
  6816. FOM.S = this;
  6817. bool hasDeletedOverridenMethods = false;
  6818. bool hasNonDeletedOverridenMethods = false;
  6819. bool AddedAny = false;
  6820. if (DC->lookupInBases(FOM, Paths)) {
  6821. for (auto *I : Paths.found_decls()) {
  6822. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  6823. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  6824. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  6825. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  6826. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  6827. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  6828. hasDeletedOverridenMethods |= OldMD->isDeleted();
  6829. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  6830. AddedAny = true;
  6831. }
  6832. }
  6833. }
  6834. }
  6835. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  6836. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  6837. }
  6838. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  6839. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  6840. }
  6841. return AddedAny;
  6842. }
  6843. namespace {
  6844. // Struct for holding all of the extra arguments needed by
  6845. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  6846. struct ActOnFDArgs {
  6847. Scope *S;
  6848. Declarator &D;
  6849. MultiTemplateParamsArg TemplateParamLists;
  6850. bool AddToScope;
  6851. };
  6852. } // end anonymous namespace
  6853. namespace {
  6854. // Callback to only accept typo corrections that have a non-zero edit distance.
  6855. // Also only accept corrections that have the same parent decl.
  6856. class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
  6857. public:
  6858. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  6859. CXXRecordDecl *Parent)
  6860. : Context(Context), OriginalFD(TypoFD),
  6861. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  6862. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6863. if (candidate.getEditDistance() == 0)
  6864. return false;
  6865. SmallVector<unsigned, 1> MismatchedParams;
  6866. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  6867. CDeclEnd = candidate.end();
  6868. CDecl != CDeclEnd; ++CDecl) {
  6869. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6870. if (FD && !FD->hasBody() &&
  6871. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  6872. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  6873. CXXRecordDecl *Parent = MD->getParent();
  6874. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  6875. return true;
  6876. } else if (!ExpectedParent) {
  6877. return true;
  6878. }
  6879. }
  6880. }
  6881. return false;
  6882. }
  6883. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  6884. return llvm::make_unique<DifferentNameValidatorCCC>(*this);
  6885. }
  6886. private:
  6887. ASTContext &Context;
  6888. FunctionDecl *OriginalFD;
  6889. CXXRecordDecl *ExpectedParent;
  6890. };
  6891. } // end anonymous namespace
  6892. void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
  6893. TypoCorrectedFunctionDefinitions.insert(F);
  6894. }
  6895. /// Generate diagnostics for an invalid function redeclaration.
  6896. ///
  6897. /// This routine handles generating the diagnostic messages for an invalid
  6898. /// function redeclaration, including finding possible similar declarations
  6899. /// or performing typo correction if there are no previous declarations with
  6900. /// the same name.
  6901. ///
  6902. /// Returns a NamedDecl iff typo correction was performed and substituting in
  6903. /// the new declaration name does not cause new errors.
  6904. static NamedDecl *DiagnoseInvalidRedeclaration(
  6905. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  6906. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  6907. DeclarationName Name = NewFD->getDeclName();
  6908. DeclContext *NewDC = NewFD->getDeclContext();
  6909. SmallVector<unsigned, 1> MismatchedParams;
  6910. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  6911. TypoCorrection Correction;
  6912. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  6913. unsigned DiagMsg =
  6914. IsLocalFriend ? diag::err_no_matching_local_friend :
  6915. NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
  6916. diag::err_member_decl_does_not_match;
  6917. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  6918. IsLocalFriend ? Sema::LookupLocalFriendName
  6919. : Sema::LookupOrdinaryName,
  6920. Sema::ForVisibleRedeclaration);
  6921. NewFD->setInvalidDecl();
  6922. if (IsLocalFriend)
  6923. SemaRef.LookupName(Prev, S);
  6924. else
  6925. SemaRef.LookupQualifiedName(Prev, NewDC);
  6926. assert(!Prev.isAmbiguous() &&
  6927. "Cannot have an ambiguity in previous-declaration lookup");
  6928. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  6929. DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
  6930. MD ? MD->getParent() : nullptr);
  6931. if (!Prev.empty()) {
  6932. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  6933. Func != FuncEnd; ++Func) {
  6934. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  6935. if (FD &&
  6936. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6937. // Add 1 to the index so that 0 can mean the mismatch didn't
  6938. // involve a parameter
  6939. unsigned ParamNum =
  6940. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  6941. NearMatches.push_back(std::make_pair(FD, ParamNum));
  6942. }
  6943. }
  6944. // If the qualified name lookup yielded nothing, try typo correction
  6945. } else if ((Correction = SemaRef.CorrectTypo(
  6946. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  6947. &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
  6948. IsLocalFriend ? nullptr : NewDC))) {
  6949. // Set up everything for the call to ActOnFunctionDeclarator
  6950. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  6951. ExtraArgs.D.getIdentifierLoc());
  6952. Previous.clear();
  6953. Previous.setLookupName(Correction.getCorrection());
  6954. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  6955. CDeclEnd = Correction.end();
  6956. CDecl != CDeclEnd; ++CDecl) {
  6957. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6958. if (FD && !FD->hasBody() &&
  6959. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6960. Previous.addDecl(FD);
  6961. }
  6962. }
  6963. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  6964. NamedDecl *Result;
  6965. // Retry building the function declaration with the new previous
  6966. // declarations, and with errors suppressed.
  6967. {
  6968. // Trap errors.
  6969. Sema::SFINAETrap Trap(SemaRef);
  6970. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  6971. // pieces need to verify the typo-corrected C++ declaration and hopefully
  6972. // eliminate the need for the parameter pack ExtraArgs.
  6973. Result = SemaRef.ActOnFunctionDeclarator(
  6974. ExtraArgs.S, ExtraArgs.D,
  6975. Correction.getCorrectionDecl()->getDeclContext(),
  6976. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  6977. ExtraArgs.AddToScope);
  6978. if (Trap.hasErrorOccurred())
  6979. Result = nullptr;
  6980. }
  6981. if (Result) {
  6982. // Determine which correction we picked.
  6983. Decl *Canonical = Result->getCanonicalDecl();
  6984. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6985. I != E; ++I)
  6986. if ((*I)->getCanonicalDecl() == Canonical)
  6987. Correction.setCorrectionDecl(*I);
  6988. // Let Sema know about the correction.
  6989. SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
  6990. SemaRef.diagnoseTypo(
  6991. Correction,
  6992. SemaRef.PDiag(IsLocalFriend
  6993. ? diag::err_no_matching_local_friend_suggest
  6994. : diag::err_member_decl_does_not_match_suggest)
  6995. << Name << NewDC << IsDefinition);
  6996. return Result;
  6997. }
  6998. // Pretend the typo correction never occurred
  6999. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  7000. ExtraArgs.D.getIdentifierLoc());
  7001. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  7002. Previous.clear();
  7003. Previous.setLookupName(Name);
  7004. }
  7005. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  7006. << Name << NewDC << IsDefinition << NewFD->getLocation();
  7007. bool NewFDisConst = false;
  7008. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  7009. NewFDisConst = NewMD->isConst();
  7010. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  7011. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  7012. NearMatch != NearMatchEnd; ++NearMatch) {
  7013. FunctionDecl *FD = NearMatch->first;
  7014. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  7015. bool FDisConst = MD && MD->isConst();
  7016. bool IsMember = MD || !IsLocalFriend;
  7017. // FIXME: These notes are poorly worded for the local friend case.
  7018. if (unsigned Idx = NearMatch->second) {
  7019. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  7020. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  7021. if (Loc.isInvalid()) Loc = FD->getLocation();
  7022. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  7023. : diag::note_local_decl_close_param_match)
  7024. << Idx << FDParam->getType()
  7025. << NewFD->getParamDecl(Idx - 1)->getType();
  7026. } else if (FDisConst != NewFDisConst) {
  7027. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  7028. << NewFDisConst << FD->getSourceRange().getEnd();
  7029. } else
  7030. SemaRef.Diag(FD->getLocation(),
  7031. IsMember ? diag::note_member_def_close_match
  7032. : diag::note_local_decl_close_match);
  7033. }
  7034. return nullptr;
  7035. }
  7036. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  7037. switch (D.getDeclSpec().getStorageClassSpec()) {
  7038. default: llvm_unreachable("Unknown storage class!");
  7039. case DeclSpec::SCS_auto:
  7040. case DeclSpec::SCS_register:
  7041. case DeclSpec::SCS_mutable:
  7042. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7043. diag::err_typecheck_sclass_func);
  7044. D.getMutableDeclSpec().ClearStorageClassSpecs();
  7045. D.setInvalidType();
  7046. break;
  7047. case DeclSpec::SCS_unspecified: break;
  7048. case DeclSpec::SCS_extern:
  7049. if (D.getDeclSpec().isExternInLinkageSpec())
  7050. return SC_None;
  7051. return SC_Extern;
  7052. case DeclSpec::SCS_static: {
  7053. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  7054. // C99 6.7.1p5:
  7055. // The declaration of an identifier for a function that has
  7056. // block scope shall have no explicit storage-class specifier
  7057. // other than extern
  7058. // See also (C++ [dcl.stc]p4).
  7059. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7060. diag::err_static_block_func);
  7061. break;
  7062. } else
  7063. return SC_Static;
  7064. }
  7065. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  7066. }
  7067. // No explicit storage class has already been returned
  7068. return SC_None;
  7069. }
  7070. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  7071. DeclContext *DC, QualType &R,
  7072. TypeSourceInfo *TInfo,
  7073. StorageClass SC,
  7074. bool &IsVirtualOkay) {
  7075. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  7076. DeclarationName Name = NameInfo.getName();
  7077. FunctionDecl *NewFD = nullptr;
  7078. bool isInline = D.getDeclSpec().isInlineSpecified();
  7079. if (!SemaRef.getLangOpts().CPlusPlus) {
  7080. // Determine whether the function was written with a
  7081. // prototype. This true when:
  7082. // - there is a prototype in the declarator, or
  7083. // - the type R of the function is some kind of typedef or other non-
  7084. // attributed reference to a type name (which eventually refers to a
  7085. // function type).
  7086. bool HasPrototype =
  7087. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  7088. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  7089. NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7090. R, TInfo, SC, isInline, HasPrototype,
  7091. CSK_unspecified);
  7092. if (D.isInvalidType())
  7093. NewFD->setInvalidDecl();
  7094. return NewFD;
  7095. }
  7096. ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
  7097. ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
  7098. // Check that the return type is not an abstract class type.
  7099. // For record types, this is done by the AbstractClassUsageDiagnoser once
  7100. // the class has been completely parsed.
  7101. if (!DC->isRecord() &&
  7102. SemaRef.RequireNonAbstractType(
  7103. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  7104. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  7105. D.setInvalidType();
  7106. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  7107. // This is a C++ constructor declaration.
  7108. assert(DC->isRecord() &&
  7109. "Constructors can only be declared in a member context");
  7110. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  7111. return CXXConstructorDecl::Create(
  7112. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7113. TInfo, ExplicitSpecifier, isInline,
  7114. /*isImplicitlyDeclared=*/false, ConstexprKind);
  7115. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7116. // This is a C++ destructor declaration.
  7117. if (DC->isRecord()) {
  7118. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  7119. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  7120. CXXDestructorDecl *NewDD =
  7121. CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
  7122. NameInfo, R, TInfo, isInline,
  7123. /*isImplicitlyDeclared=*/false);
  7124. // If the destructor needs an implicit exception specification, set it
  7125. // now. FIXME: It'd be nice to be able to create the right type to start
  7126. // with, but the type needs to reference the destructor declaration.
  7127. if (SemaRef.getLangOpts().CPlusPlus11)
  7128. SemaRef.AdjustDestructorExceptionSpec(NewDD);
  7129. IsVirtualOkay = true;
  7130. return NewDD;
  7131. } else {
  7132. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  7133. D.setInvalidType();
  7134. // Create a FunctionDecl to satisfy the function definition parsing
  7135. // code path.
  7136. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7137. D.getIdentifierLoc(), Name, R, TInfo, SC,
  7138. isInline,
  7139. /*hasPrototype=*/true, ConstexprKind);
  7140. }
  7141. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  7142. if (!DC->isRecord()) {
  7143. SemaRef.Diag(D.getIdentifierLoc(),
  7144. diag::err_conv_function_not_member);
  7145. return nullptr;
  7146. }
  7147. SemaRef.CheckConversionDeclarator(D, R, SC);
  7148. IsVirtualOkay = true;
  7149. return CXXConversionDecl::Create(
  7150. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7151. TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
  7152. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  7153. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  7154. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7155. ExplicitSpecifier, NameInfo, R, TInfo,
  7156. D.getEndLoc());
  7157. } else if (DC->isRecord()) {
  7158. // If the name of the function is the same as the name of the record,
  7159. // then this must be an invalid constructor that has a return type.
  7160. // (The parser checks for a return type and makes the declarator a
  7161. // constructor if it has no return type).
  7162. if (Name.getAsIdentifierInfo() &&
  7163. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  7164. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  7165. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7166. << SourceRange(D.getIdentifierLoc());
  7167. return nullptr;
  7168. }
  7169. // This is a C++ method declaration.
  7170. CXXMethodDecl *Ret = CXXMethodDecl::Create(
  7171. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7172. TInfo, SC, isInline, ConstexprKind, SourceLocation());
  7173. IsVirtualOkay = !Ret->isStatic();
  7174. return Ret;
  7175. } else {
  7176. bool isFriend =
  7177. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  7178. if (!isFriend && SemaRef.CurContext->isRecord())
  7179. return nullptr;
  7180. // Determine whether the function was written with a
  7181. // prototype. This true when:
  7182. // - we're in C++ (where every function has a prototype),
  7183. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7184. R, TInfo, SC, isInline, true /*HasPrototype*/,
  7185. ConstexprKind);
  7186. }
  7187. }
  7188. enum OpenCLParamType {
  7189. ValidKernelParam,
  7190. PtrPtrKernelParam,
  7191. PtrKernelParam,
  7192. InvalidAddrSpacePtrKernelParam,
  7193. InvalidKernelParam,
  7194. RecordKernelParam
  7195. };
  7196. static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
  7197. // Size dependent types are just typedefs to normal integer types
  7198. // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
  7199. // integers other than by their names.
  7200. StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
  7201. // Remove typedefs one by one until we reach a typedef
  7202. // for a size dependent type.
  7203. QualType DesugaredTy = Ty;
  7204. do {
  7205. ArrayRef<StringRef> Names(SizeTypeNames);
  7206. auto Match = llvm::find(Names, DesugaredTy.getAsString());
  7207. if (Names.end() != Match)
  7208. return true;
  7209. Ty = DesugaredTy;
  7210. DesugaredTy = Ty.getSingleStepDesugaredType(C);
  7211. } while (DesugaredTy != Ty);
  7212. return false;
  7213. }
  7214. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  7215. if (PT->isPointerType()) {
  7216. QualType PointeeType = PT->getPointeeType();
  7217. if (PointeeType->isPointerType())
  7218. return PtrPtrKernelParam;
  7219. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  7220. PointeeType.getAddressSpace() == LangAS::opencl_private ||
  7221. PointeeType.getAddressSpace() == LangAS::Default)
  7222. return InvalidAddrSpacePtrKernelParam;
  7223. return PtrKernelParam;
  7224. }
  7225. // OpenCL v1.2 s6.9.k:
  7226. // Arguments to kernel functions in a program cannot be declared with the
  7227. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7228. // uintptr_t or a struct and/or union that contain fields declared to be one
  7229. // of these built-in scalar types.
  7230. if (isOpenCLSizeDependentType(S.getASTContext(), PT))
  7231. return InvalidKernelParam;
  7232. if (PT->isImageType())
  7233. return PtrKernelParam;
  7234. if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
  7235. return InvalidKernelParam;
  7236. // OpenCL extension spec v1.2 s9.5:
  7237. // This extension adds support for half scalar and vector types as built-in
  7238. // types that can be used for arithmetic operations, conversions etc.
  7239. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
  7240. return InvalidKernelParam;
  7241. if (PT->isRecordType())
  7242. return RecordKernelParam;
  7243. // Look into an array argument to check if it has a forbidden type.
  7244. if (PT->isArrayType()) {
  7245. const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
  7246. // Call ourself to check an underlying type of an array. Since the
  7247. // getPointeeOrArrayElementType returns an innermost type which is not an
  7248. // array, this recursive call only happens once.
  7249. return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
  7250. }
  7251. return ValidKernelParam;
  7252. }
  7253. static void checkIsValidOpenCLKernelParameter(
  7254. Sema &S,
  7255. Declarator &D,
  7256. ParmVarDecl *Param,
  7257. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  7258. QualType PT = Param->getType();
  7259. // Cache the valid types we encounter to avoid rechecking structs that are
  7260. // used again
  7261. if (ValidTypes.count(PT.getTypePtr()))
  7262. return;
  7263. switch (getOpenCLKernelParameterType(S, PT)) {
  7264. case PtrPtrKernelParam:
  7265. // OpenCL v1.2 s6.9.a:
  7266. // A kernel function argument cannot be declared as a
  7267. // pointer to a pointer type.
  7268. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  7269. D.setInvalidType();
  7270. return;
  7271. case InvalidAddrSpacePtrKernelParam:
  7272. // OpenCL v1.0 s6.5:
  7273. // __kernel function arguments declared to be a pointer of a type can point
  7274. // to one of the following address spaces only : __global, __local or
  7275. // __constant.
  7276. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  7277. D.setInvalidType();
  7278. return;
  7279. // OpenCL v1.2 s6.9.k:
  7280. // Arguments to kernel functions in a program cannot be declared with the
  7281. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7282. // uintptr_t or a struct and/or union that contain fields declared to be
  7283. // one of these built-in scalar types.
  7284. case InvalidKernelParam:
  7285. // OpenCL v1.2 s6.8 n:
  7286. // A kernel function argument cannot be declared
  7287. // of event_t type.
  7288. // Do not diagnose half type since it is diagnosed as invalid argument
  7289. // type for any function elsewhere.
  7290. if (!PT->isHalfType()) {
  7291. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7292. // Explain what typedefs are involved.
  7293. const TypedefType *Typedef = nullptr;
  7294. while ((Typedef = PT->getAs<TypedefType>())) {
  7295. SourceLocation Loc = Typedef->getDecl()->getLocation();
  7296. // SourceLocation may be invalid for a built-in type.
  7297. if (Loc.isValid())
  7298. S.Diag(Loc, diag::note_entity_declared_at) << PT;
  7299. PT = Typedef->desugar();
  7300. }
  7301. }
  7302. D.setInvalidType();
  7303. return;
  7304. case PtrKernelParam:
  7305. case ValidKernelParam:
  7306. ValidTypes.insert(PT.getTypePtr());
  7307. return;
  7308. case RecordKernelParam:
  7309. break;
  7310. }
  7311. // Track nested structs we will inspect
  7312. SmallVector<const Decl *, 4> VisitStack;
  7313. // Track where we are in the nested structs. Items will migrate from
  7314. // VisitStack to HistoryStack as we do the DFS for bad field.
  7315. SmallVector<const FieldDecl *, 4> HistoryStack;
  7316. HistoryStack.push_back(nullptr);
  7317. // At this point we already handled everything except of a RecordType or
  7318. // an ArrayType of a RecordType.
  7319. assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
  7320. const RecordType *RecTy =
  7321. PT->getPointeeOrArrayElementType()->getAs<RecordType>();
  7322. const RecordDecl *OrigRecDecl = RecTy->getDecl();
  7323. VisitStack.push_back(RecTy->getDecl());
  7324. assert(VisitStack.back() && "First decl null?");
  7325. do {
  7326. const Decl *Next = VisitStack.pop_back_val();
  7327. if (!Next) {
  7328. assert(!HistoryStack.empty());
  7329. // Found a marker, we have gone up a level
  7330. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  7331. ValidTypes.insert(Hist->getType().getTypePtr());
  7332. continue;
  7333. }
  7334. // Adds everything except the original parameter declaration (which is not a
  7335. // field itself) to the history stack.
  7336. const RecordDecl *RD;
  7337. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  7338. HistoryStack.push_back(Field);
  7339. QualType FieldTy = Field->getType();
  7340. // Other field types (known to be valid or invalid) are handled while we
  7341. // walk around RecordDecl::fields().
  7342. assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
  7343. "Unexpected type.");
  7344. const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
  7345. RD = FieldRecTy->castAs<RecordType>()->getDecl();
  7346. } else {
  7347. RD = cast<RecordDecl>(Next);
  7348. }
  7349. // Add a null marker so we know when we've gone back up a level
  7350. VisitStack.push_back(nullptr);
  7351. for (const auto *FD : RD->fields()) {
  7352. QualType QT = FD->getType();
  7353. if (ValidTypes.count(QT.getTypePtr()))
  7354. continue;
  7355. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  7356. if (ParamType == ValidKernelParam)
  7357. continue;
  7358. if (ParamType == RecordKernelParam) {
  7359. VisitStack.push_back(FD);
  7360. continue;
  7361. }
  7362. // OpenCL v1.2 s6.9.p:
  7363. // Arguments to kernel functions that are declared to be a struct or union
  7364. // do not allow OpenCL objects to be passed as elements of the struct or
  7365. // union.
  7366. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  7367. ParamType == InvalidAddrSpacePtrKernelParam) {
  7368. S.Diag(Param->getLocation(),
  7369. diag::err_record_with_pointers_kernel_param)
  7370. << PT->isUnionType()
  7371. << PT;
  7372. } else {
  7373. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7374. }
  7375. S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
  7376. << OrigRecDecl->getDeclName();
  7377. // We have an error, now let's go back up through history and show where
  7378. // the offending field came from
  7379. for (ArrayRef<const FieldDecl *>::const_iterator
  7380. I = HistoryStack.begin() + 1,
  7381. E = HistoryStack.end();
  7382. I != E; ++I) {
  7383. const FieldDecl *OuterField = *I;
  7384. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  7385. << OuterField->getType();
  7386. }
  7387. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  7388. << QT->isPointerType()
  7389. << QT;
  7390. D.setInvalidType();
  7391. return;
  7392. }
  7393. } while (!VisitStack.empty());
  7394. }
  7395. /// Find the DeclContext in which a tag is implicitly declared if we see an
  7396. /// elaborated type specifier in the specified context, and lookup finds
  7397. /// nothing.
  7398. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  7399. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  7400. DC = DC->getParent();
  7401. return DC;
  7402. }
  7403. /// Find the Scope in which a tag is implicitly declared if we see an
  7404. /// elaborated type specifier in the specified context, and lookup finds
  7405. /// nothing.
  7406. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  7407. while (S->isClassScope() ||
  7408. (LangOpts.CPlusPlus &&
  7409. S->isFunctionPrototypeScope()) ||
  7410. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7411. (S->getEntity() && S->getEntity()->isTransparentContext()))
  7412. S = S->getParent();
  7413. return S;
  7414. }
  7415. NamedDecl*
  7416. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  7417. TypeSourceInfo *TInfo, LookupResult &Previous,
  7418. MultiTemplateParamsArg TemplateParamLists,
  7419. bool &AddToScope) {
  7420. QualType R = TInfo->getType();
  7421. assert(R->isFunctionType());
  7422. // TODO: consider using NameInfo for diagnostic.
  7423. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  7424. DeclarationName Name = NameInfo.getName();
  7425. StorageClass SC = getFunctionStorageClass(*this, D);
  7426. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  7427. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  7428. diag::err_invalid_thread)
  7429. << DeclSpec::getSpecifierName(TSCS);
  7430. if (D.isFirstDeclarationOfMember())
  7431. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  7432. D.getIdentifierLoc());
  7433. bool isFriend = false;
  7434. FunctionTemplateDecl *FunctionTemplate = nullptr;
  7435. bool isMemberSpecialization = false;
  7436. bool isFunctionTemplateSpecialization = false;
  7437. bool isDependentClassScopeExplicitSpecialization = false;
  7438. bool HasExplicitTemplateArgs = false;
  7439. TemplateArgumentListInfo TemplateArgs;
  7440. bool isVirtualOkay = false;
  7441. DeclContext *OriginalDC = DC;
  7442. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  7443. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  7444. isVirtualOkay);
  7445. if (!NewFD) return nullptr;
  7446. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  7447. NewFD->setTopLevelDeclInObjCContainer();
  7448. // Set the lexical context. If this is a function-scope declaration, or has a
  7449. // C++ scope specifier, or is the object of a friend declaration, the lexical
  7450. // context will be different from the semantic context.
  7451. NewFD->setLexicalDeclContext(CurContext);
  7452. if (IsLocalExternDecl)
  7453. NewFD->setLocalExternDecl();
  7454. if (getLangOpts().CPlusPlus) {
  7455. bool isInline = D.getDeclSpec().isInlineSpecified();
  7456. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7457. bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
  7458. ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
  7459. isFriend = D.getDeclSpec().isFriendSpecified();
  7460. if (isFriend && !isInline && D.isFunctionDefinition()) {
  7461. // C++ [class.friend]p5
  7462. // A function can be defined in a friend declaration of a
  7463. // class . . . . Such a function is implicitly inline.
  7464. NewFD->setImplicitlyInline();
  7465. }
  7466. // If this is a method defined in an __interface, and is not a constructor
  7467. // or an overloaded operator, then set the pure flag (isVirtual will already
  7468. // return true).
  7469. if (const CXXRecordDecl *Parent =
  7470. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  7471. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  7472. NewFD->setPure(true);
  7473. // C++ [class.union]p2
  7474. // A union can have member functions, but not virtual functions.
  7475. if (isVirtual && Parent->isUnion())
  7476. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  7477. }
  7478. SetNestedNameSpecifier(*this, NewFD, D);
  7479. isMemberSpecialization = false;
  7480. isFunctionTemplateSpecialization = false;
  7481. if (D.isInvalidType())
  7482. NewFD->setInvalidDecl();
  7483. // Match up the template parameter lists with the scope specifier, then
  7484. // determine whether we have a template or a template specialization.
  7485. bool Invalid = false;
  7486. if (TemplateParameterList *TemplateParams =
  7487. MatchTemplateParametersToScopeSpecifier(
  7488. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  7489. D.getCXXScopeSpec(),
  7490. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  7491. ? D.getName().TemplateId
  7492. : nullptr,
  7493. TemplateParamLists, isFriend, isMemberSpecialization,
  7494. Invalid)) {
  7495. if (TemplateParams->size() > 0) {
  7496. // This is a function template
  7497. // Check that we can declare a template here.
  7498. if (CheckTemplateDeclScope(S, TemplateParams))
  7499. NewFD->setInvalidDecl();
  7500. // A destructor cannot be a template.
  7501. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7502. Diag(NewFD->getLocation(), diag::err_destructor_template);
  7503. NewFD->setInvalidDecl();
  7504. }
  7505. // If we're adding a template to a dependent context, we may need to
  7506. // rebuilding some of the types used within the template parameter list,
  7507. // now that we know what the current instantiation is.
  7508. if (DC->isDependentContext()) {
  7509. ContextRAII SavedContext(*this, DC);
  7510. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  7511. Invalid = true;
  7512. }
  7513. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  7514. NewFD->getLocation(),
  7515. Name, TemplateParams,
  7516. NewFD);
  7517. FunctionTemplate->setLexicalDeclContext(CurContext);
  7518. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  7519. // For source fidelity, store the other template param lists.
  7520. if (TemplateParamLists.size() > 1) {
  7521. NewFD->setTemplateParameterListsInfo(Context,
  7522. TemplateParamLists.drop_back(1));
  7523. }
  7524. } else {
  7525. // This is a function template specialization.
  7526. isFunctionTemplateSpecialization = true;
  7527. // For source fidelity, store all the template param lists.
  7528. if (TemplateParamLists.size() > 0)
  7529. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7530. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  7531. if (isFriend) {
  7532. // We want to remove the "template<>", found here.
  7533. SourceRange RemoveRange = TemplateParams->getSourceRange();
  7534. // If we remove the template<> and the name is not a
  7535. // template-id, we're actually silently creating a problem:
  7536. // the friend declaration will refer to an untemplated decl,
  7537. // and clearly the user wants a template specialization. So
  7538. // we need to insert '<>' after the name.
  7539. SourceLocation InsertLoc;
  7540. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  7541. InsertLoc = D.getName().getSourceRange().getEnd();
  7542. InsertLoc = getLocForEndOfToken(InsertLoc);
  7543. }
  7544. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  7545. << Name << RemoveRange
  7546. << FixItHint::CreateRemoval(RemoveRange)
  7547. << FixItHint::CreateInsertion(InsertLoc, "<>");
  7548. }
  7549. }
  7550. } else {
  7551. // All template param lists were matched against the scope specifier:
  7552. // this is NOT (an explicit specialization of) a template.
  7553. if (TemplateParamLists.size() > 0)
  7554. // For source fidelity, store all the template param lists.
  7555. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7556. }
  7557. if (Invalid) {
  7558. NewFD->setInvalidDecl();
  7559. if (FunctionTemplate)
  7560. FunctionTemplate->setInvalidDecl();
  7561. }
  7562. // C++ [dcl.fct.spec]p5:
  7563. // The virtual specifier shall only be used in declarations of
  7564. // nonstatic class member functions that appear within a
  7565. // member-specification of a class declaration; see 10.3.
  7566. //
  7567. if (isVirtual && !NewFD->isInvalidDecl()) {
  7568. if (!isVirtualOkay) {
  7569. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7570. diag::err_virtual_non_function);
  7571. } else if (!CurContext->isRecord()) {
  7572. // 'virtual' was specified outside of the class.
  7573. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7574. diag::err_virtual_out_of_class)
  7575. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7576. } else if (NewFD->getDescribedFunctionTemplate()) {
  7577. // C++ [temp.mem]p3:
  7578. // A member function template shall not be virtual.
  7579. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7580. diag::err_virtual_member_function_template)
  7581. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7582. } else {
  7583. // Okay: Add virtual to the method.
  7584. NewFD->setVirtualAsWritten(true);
  7585. }
  7586. if (getLangOpts().CPlusPlus14 &&
  7587. NewFD->getReturnType()->isUndeducedType())
  7588. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  7589. }
  7590. if (getLangOpts().CPlusPlus14 &&
  7591. (NewFD->isDependentContext() ||
  7592. (isFriend && CurContext->isDependentContext())) &&
  7593. NewFD->getReturnType()->isUndeducedType()) {
  7594. // If the function template is referenced directly (for instance, as a
  7595. // member of the current instantiation), pretend it has a dependent type.
  7596. // This is not really justified by the standard, but is the only sane
  7597. // thing to do.
  7598. // FIXME: For a friend function, we have not marked the function as being
  7599. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  7600. const FunctionProtoType *FPT =
  7601. NewFD->getType()->castAs<FunctionProtoType>();
  7602. QualType Result =
  7603. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  7604. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  7605. FPT->getExtProtoInfo()));
  7606. }
  7607. // C++ [dcl.fct.spec]p3:
  7608. // The inline specifier shall not appear on a block scope function
  7609. // declaration.
  7610. if (isInline && !NewFD->isInvalidDecl()) {
  7611. if (CurContext->isFunctionOrMethod()) {
  7612. // 'inline' is not allowed on block scope function declaration.
  7613. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7614. diag::err_inline_declaration_block_scope) << Name
  7615. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7616. }
  7617. }
  7618. // C++ [dcl.fct.spec]p6:
  7619. // The explicit specifier shall be used only in the declaration of a
  7620. // constructor or conversion function within its class definition;
  7621. // see 12.3.1 and 12.3.2.
  7622. if (hasExplicit && !NewFD->isInvalidDecl() &&
  7623. !isa<CXXDeductionGuideDecl>(NewFD)) {
  7624. if (!CurContext->isRecord()) {
  7625. // 'explicit' was specified outside of the class.
  7626. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7627. diag::err_explicit_out_of_class)
  7628. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  7629. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  7630. !isa<CXXConversionDecl>(NewFD)) {
  7631. // 'explicit' was specified on a function that wasn't a constructor
  7632. // or conversion function.
  7633. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7634. diag::err_explicit_non_ctor_or_conv_function)
  7635. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  7636. }
  7637. }
  7638. if (ConstexprKind != CSK_unspecified) {
  7639. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  7640. // are implicitly inline.
  7641. NewFD->setImplicitlyInline();
  7642. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  7643. // be either constructors or to return a literal type. Therefore,
  7644. // destructors cannot be declared constexpr.
  7645. if (isa<CXXDestructorDecl>(NewFD))
  7646. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
  7647. << (ConstexprKind == CSK_consteval);
  7648. }
  7649. // If __module_private__ was specified, mark the function accordingly.
  7650. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7651. if (isFunctionTemplateSpecialization) {
  7652. SourceLocation ModulePrivateLoc
  7653. = D.getDeclSpec().getModulePrivateSpecLoc();
  7654. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  7655. << 0
  7656. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7657. } else {
  7658. NewFD->setModulePrivate();
  7659. if (FunctionTemplate)
  7660. FunctionTemplate->setModulePrivate();
  7661. }
  7662. }
  7663. if (isFriend) {
  7664. if (FunctionTemplate) {
  7665. FunctionTemplate->setObjectOfFriendDecl();
  7666. FunctionTemplate->setAccess(AS_public);
  7667. }
  7668. NewFD->setObjectOfFriendDecl();
  7669. NewFD->setAccess(AS_public);
  7670. }
  7671. // If a function is defined as defaulted or deleted, mark it as such now.
  7672. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  7673. // definition kind to FDK_Definition.
  7674. switch (D.getFunctionDefinitionKind()) {
  7675. case FDK_Declaration:
  7676. case FDK_Definition:
  7677. break;
  7678. case FDK_Defaulted:
  7679. NewFD->setDefaulted();
  7680. break;
  7681. case FDK_Deleted:
  7682. NewFD->setDeletedAsWritten();
  7683. break;
  7684. }
  7685. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  7686. D.isFunctionDefinition()) {
  7687. // C++ [class.mfct]p2:
  7688. // A member function may be defined (8.4) in its class definition, in
  7689. // which case it is an inline member function (7.1.2)
  7690. NewFD->setImplicitlyInline();
  7691. }
  7692. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  7693. !CurContext->isRecord()) {
  7694. // C++ [class.static]p1:
  7695. // A data or function member of a class may be declared static
  7696. // in a class definition, in which case it is a static member of
  7697. // the class.
  7698. // Complain about the 'static' specifier if it's on an out-of-line
  7699. // member function definition.
  7700. // MSVC permits the use of a 'static' storage specifier on an out-of-line
  7701. // member function template declaration and class member template
  7702. // declaration (MSVC versions before 2015), warn about this.
  7703. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7704. ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  7705. cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
  7706. (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
  7707. ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
  7708. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7709. }
  7710. // C++11 [except.spec]p15:
  7711. // A deallocation function with no exception-specification is treated
  7712. // as if it were specified with noexcept(true).
  7713. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  7714. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  7715. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  7716. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  7717. NewFD->setType(Context.getFunctionType(
  7718. FPT->getReturnType(), FPT->getParamTypes(),
  7719. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  7720. }
  7721. // Filter out previous declarations that don't match the scope.
  7722. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  7723. D.getCXXScopeSpec().isNotEmpty() ||
  7724. isMemberSpecialization ||
  7725. isFunctionTemplateSpecialization);
  7726. // Handle GNU asm-label extension (encoded as an attribute).
  7727. if (Expr *E = (Expr*) D.getAsmLabel()) {
  7728. // The parser guarantees this is a string.
  7729. StringLiteral *SE = cast<StringLiteral>(E);
  7730. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  7731. SE->getString(), 0));
  7732. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7733. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7734. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  7735. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7736. if (isDeclExternC(NewFD)) {
  7737. NewFD->addAttr(I->second);
  7738. ExtnameUndeclaredIdentifiers.erase(I);
  7739. } else
  7740. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  7741. << /*Variable*/0 << NewFD;
  7742. }
  7743. }
  7744. // Copy the parameter declarations from the declarator D to the function
  7745. // declaration NewFD, if they are available. First scavenge them into Params.
  7746. SmallVector<ParmVarDecl*, 16> Params;
  7747. unsigned FTIIdx;
  7748. if (D.isFunctionDeclarator(FTIIdx)) {
  7749. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  7750. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  7751. // function that takes no arguments, not a function that takes a
  7752. // single void argument.
  7753. // We let through "const void" here because Sema::GetTypeForDeclarator
  7754. // already checks for that case.
  7755. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  7756. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  7757. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  7758. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  7759. Param->setDeclContext(NewFD);
  7760. Params.push_back(Param);
  7761. if (Param->isInvalidDecl())
  7762. NewFD->setInvalidDecl();
  7763. }
  7764. }
  7765. if (!getLangOpts().CPlusPlus) {
  7766. // In C, find all the tag declarations from the prototype and move them
  7767. // into the function DeclContext. Remove them from the surrounding tag
  7768. // injection context of the function, which is typically but not always
  7769. // the TU.
  7770. DeclContext *PrototypeTagContext =
  7771. getTagInjectionContext(NewFD->getLexicalDeclContext());
  7772. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  7773. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  7774. // We don't want to reparent enumerators. Look at their parent enum
  7775. // instead.
  7776. if (!TD) {
  7777. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  7778. TD = cast<EnumDecl>(ECD->getDeclContext());
  7779. }
  7780. if (!TD)
  7781. continue;
  7782. DeclContext *TagDC = TD->getLexicalDeclContext();
  7783. if (!TagDC->containsDecl(TD))
  7784. continue;
  7785. TagDC->removeDecl(TD);
  7786. TD->setDeclContext(NewFD);
  7787. NewFD->addDecl(TD);
  7788. // Preserve the lexical DeclContext if it is not the surrounding tag
  7789. // injection context of the FD. In this example, the semantic context of
  7790. // E will be f and the lexical context will be S, while both the
  7791. // semantic and lexical contexts of S will be f:
  7792. // void f(struct S { enum E { a } f; } s);
  7793. if (TagDC != PrototypeTagContext)
  7794. TD->setLexicalDeclContext(TagDC);
  7795. }
  7796. }
  7797. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  7798. // When we're declaring a function with a typedef, typeof, etc as in the
  7799. // following example, we'll need to synthesize (unnamed)
  7800. // parameters for use in the declaration.
  7801. //
  7802. // @code
  7803. // typedef void fn(int);
  7804. // fn f;
  7805. // @endcode
  7806. // Synthesize a parameter for each argument type.
  7807. for (const auto &AI : FT->param_types()) {
  7808. ParmVarDecl *Param =
  7809. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  7810. Param->setScopeInfo(0, Params.size());
  7811. Params.push_back(Param);
  7812. }
  7813. } else {
  7814. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  7815. "Should not need args for typedef of non-prototype fn");
  7816. }
  7817. // Finally, we know we have the right number of parameters, install them.
  7818. NewFD->setParams(Params);
  7819. if (D.getDeclSpec().isNoreturnSpecified())
  7820. NewFD->addAttr(
  7821. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  7822. Context, 0));
  7823. // Functions returning a variably modified type violate C99 6.7.5.2p2
  7824. // because all functions have linkage.
  7825. if (!NewFD->isInvalidDecl() &&
  7826. NewFD->getReturnType()->isVariablyModifiedType()) {
  7827. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  7828. NewFD->setInvalidDecl();
  7829. }
  7830. // Apply an implicit SectionAttr if '#pragma clang section text' is active
  7831. if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
  7832. !NewFD->hasAttr<SectionAttr>()) {
  7833. NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
  7834. PragmaClangTextSection.SectionName,
  7835. PragmaClangTextSection.PragmaLocation));
  7836. }
  7837. // Apply an implicit SectionAttr if #pragma code_seg is active.
  7838. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  7839. !NewFD->hasAttr<SectionAttr>()) {
  7840. NewFD->addAttr(
  7841. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  7842. CodeSegStack.CurrentValue->getString(),
  7843. CodeSegStack.CurrentPragmaLocation));
  7844. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  7845. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  7846. ASTContext::PSF_Read,
  7847. NewFD))
  7848. NewFD->dropAttr<SectionAttr>();
  7849. }
  7850. // Apply an implicit CodeSegAttr from class declspec or
  7851. // apply an implicit SectionAttr from #pragma code_seg if active.
  7852. if (!NewFD->hasAttr<CodeSegAttr>()) {
  7853. if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
  7854. D.isFunctionDefinition())) {
  7855. NewFD->addAttr(SAttr);
  7856. }
  7857. }
  7858. // Handle attributes.
  7859. ProcessDeclAttributes(S, NewFD, D);
  7860. if (getLangOpts().OpenCL) {
  7861. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  7862. // type declaration will generate a compilation error.
  7863. LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
  7864. if (AddressSpace != LangAS::Default) {
  7865. Diag(NewFD->getLocation(),
  7866. diag::err_opencl_return_value_with_address_space);
  7867. NewFD->setInvalidDecl();
  7868. }
  7869. }
  7870. if (!getLangOpts().CPlusPlus) {
  7871. // Perform semantic checking on the function declaration.
  7872. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7873. CheckMain(NewFD, D.getDeclSpec());
  7874. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7875. CheckMSVCRTEntryPoint(NewFD);
  7876. if (!NewFD->isInvalidDecl())
  7877. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7878. isMemberSpecialization));
  7879. else if (!Previous.empty())
  7880. // Recover gracefully from an invalid redeclaration.
  7881. D.setRedeclaration(true);
  7882. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7883. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7884. "previous declaration set still overloaded");
  7885. // Diagnose no-prototype function declarations with calling conventions that
  7886. // don't support variadic calls. Only do this in C and do it after merging
  7887. // possibly prototyped redeclarations.
  7888. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  7889. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  7890. CallingConv CC = FT->getExtInfo().getCC();
  7891. if (!supportsVariadicCall(CC)) {
  7892. // Windows system headers sometimes accidentally use stdcall without
  7893. // (void) parameters, so we relax this to a warning.
  7894. int DiagID =
  7895. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  7896. Diag(NewFD->getLocation(), DiagID)
  7897. << FunctionType::getNameForCallConv(CC);
  7898. }
  7899. }
  7900. if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
  7901. NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
  7902. checkNonTrivialCUnion(NewFD->getReturnType(),
  7903. NewFD->getReturnTypeSourceRange().getBegin(),
  7904. NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
  7905. } else {
  7906. // C++11 [replacement.functions]p3:
  7907. // The program's definitions shall not be specified as inline.
  7908. //
  7909. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  7910. //
  7911. // Suppress the diagnostic if the function is __attribute__((used)), since
  7912. // that forces an external definition to be emitted.
  7913. if (D.getDeclSpec().isInlineSpecified() &&
  7914. NewFD->isReplaceableGlobalAllocationFunction() &&
  7915. !NewFD->hasAttr<UsedAttr>())
  7916. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7917. diag::ext_operator_new_delete_declared_inline)
  7918. << NewFD->getDeclName();
  7919. // If the declarator is a template-id, translate the parser's template
  7920. // argument list into our AST format.
  7921. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  7922. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  7923. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  7924. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  7925. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  7926. TemplateId->NumArgs);
  7927. translateTemplateArguments(TemplateArgsPtr,
  7928. TemplateArgs);
  7929. HasExplicitTemplateArgs = true;
  7930. if (NewFD->isInvalidDecl()) {
  7931. HasExplicitTemplateArgs = false;
  7932. } else if (FunctionTemplate) {
  7933. // Function template with explicit template arguments.
  7934. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  7935. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  7936. HasExplicitTemplateArgs = false;
  7937. } else {
  7938. assert((isFunctionTemplateSpecialization ||
  7939. D.getDeclSpec().isFriendSpecified()) &&
  7940. "should have a 'template<>' for this decl");
  7941. // "friend void foo<>(int);" is an implicit specialization decl.
  7942. isFunctionTemplateSpecialization = true;
  7943. }
  7944. } else if (isFriend && isFunctionTemplateSpecialization) {
  7945. // This combination is only possible in a recovery case; the user
  7946. // wrote something like:
  7947. // template <> friend void foo(int);
  7948. // which we're recovering from as if the user had written:
  7949. // friend void foo<>(int);
  7950. // Go ahead and fake up a template id.
  7951. HasExplicitTemplateArgs = true;
  7952. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  7953. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  7954. }
  7955. // We do not add HD attributes to specializations here because
  7956. // they may have different constexpr-ness compared to their
  7957. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  7958. // may end up with different effective targets. Instead, a
  7959. // specialization inherits its target attributes from its template
  7960. // in the CheckFunctionTemplateSpecialization() call below.
  7961. if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
  7962. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  7963. // If it's a friend (and only if it's a friend), it's possible
  7964. // that either the specialized function type or the specialized
  7965. // template is dependent, and therefore matching will fail. In
  7966. // this case, don't check the specialization yet.
  7967. bool InstantiationDependent = false;
  7968. if (isFunctionTemplateSpecialization && isFriend &&
  7969. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  7970. TemplateSpecializationType::anyDependentTemplateArguments(
  7971. TemplateArgs,
  7972. InstantiationDependent))) {
  7973. assert(HasExplicitTemplateArgs &&
  7974. "friend function specialization without template args");
  7975. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  7976. Previous))
  7977. NewFD->setInvalidDecl();
  7978. } else if (isFunctionTemplateSpecialization) {
  7979. if (CurContext->isDependentContext() && CurContext->isRecord()
  7980. && !isFriend) {
  7981. isDependentClassScopeExplicitSpecialization = true;
  7982. } else if (!NewFD->isInvalidDecl() &&
  7983. CheckFunctionTemplateSpecialization(
  7984. NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
  7985. Previous))
  7986. NewFD->setInvalidDecl();
  7987. // C++ [dcl.stc]p1:
  7988. // A storage-class-specifier shall not be specified in an explicit
  7989. // specialization (14.7.3)
  7990. FunctionTemplateSpecializationInfo *Info =
  7991. NewFD->getTemplateSpecializationInfo();
  7992. if (Info && SC != SC_None) {
  7993. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  7994. Diag(NewFD->getLocation(),
  7995. diag::err_explicit_specialization_inconsistent_storage_class)
  7996. << SC
  7997. << FixItHint::CreateRemoval(
  7998. D.getDeclSpec().getStorageClassSpecLoc());
  7999. else
  8000. Diag(NewFD->getLocation(),
  8001. diag::ext_explicit_specialization_storage_class)
  8002. << FixItHint::CreateRemoval(
  8003. D.getDeclSpec().getStorageClassSpecLoc());
  8004. }
  8005. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  8006. if (CheckMemberSpecialization(NewFD, Previous))
  8007. NewFD->setInvalidDecl();
  8008. }
  8009. // Perform semantic checking on the function declaration.
  8010. if (!isDependentClassScopeExplicitSpecialization) {
  8011. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  8012. CheckMain(NewFD, D.getDeclSpec());
  8013. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  8014. CheckMSVCRTEntryPoint(NewFD);
  8015. if (!NewFD->isInvalidDecl())
  8016. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  8017. isMemberSpecialization));
  8018. else if (!Previous.empty())
  8019. // Recover gracefully from an invalid redeclaration.
  8020. D.setRedeclaration(true);
  8021. }
  8022. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  8023. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  8024. "previous declaration set still overloaded");
  8025. NamedDecl *PrincipalDecl = (FunctionTemplate
  8026. ? cast<NamedDecl>(FunctionTemplate)
  8027. : NewFD);
  8028. if (isFriend && NewFD->getPreviousDecl()) {
  8029. AccessSpecifier Access = AS_public;
  8030. if (!NewFD->isInvalidDecl())
  8031. Access = NewFD->getPreviousDecl()->getAccess();
  8032. NewFD->setAccess(Access);
  8033. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  8034. }
  8035. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  8036. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  8037. PrincipalDecl->setNonMemberOperator();
  8038. // If we have a function template, check the template parameter
  8039. // list. This will check and merge default template arguments.
  8040. if (FunctionTemplate) {
  8041. FunctionTemplateDecl *PrevTemplate =
  8042. FunctionTemplate->getPreviousDecl();
  8043. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  8044. PrevTemplate ? PrevTemplate->getTemplateParameters()
  8045. : nullptr,
  8046. D.getDeclSpec().isFriendSpecified()
  8047. ? (D.isFunctionDefinition()
  8048. ? TPC_FriendFunctionTemplateDefinition
  8049. : TPC_FriendFunctionTemplate)
  8050. : (D.getCXXScopeSpec().isSet() &&
  8051. DC && DC->isRecord() &&
  8052. DC->isDependentContext())
  8053. ? TPC_ClassTemplateMember
  8054. : TPC_FunctionTemplate);
  8055. }
  8056. if (NewFD->isInvalidDecl()) {
  8057. // Ignore all the rest of this.
  8058. } else if (!D.isRedeclaration()) {
  8059. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  8060. AddToScope };
  8061. // Fake up an access specifier if it's supposed to be a class member.
  8062. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  8063. NewFD->setAccess(AS_public);
  8064. // Qualified decls generally require a previous declaration.
  8065. if (D.getCXXScopeSpec().isSet()) {
  8066. // ...with the major exception of templated-scope or
  8067. // dependent-scope friend declarations.
  8068. // TODO: we currently also suppress this check in dependent
  8069. // contexts because (1) the parameter depth will be off when
  8070. // matching friend templates and (2) we might actually be
  8071. // selecting a friend based on a dependent factor. But there
  8072. // are situations where these conditions don't apply and we
  8073. // can actually do this check immediately.
  8074. //
  8075. // Unless the scope is dependent, it's always an error if qualified
  8076. // redeclaration lookup found nothing at all. Diagnose that now;
  8077. // nothing will diagnose that error later.
  8078. if (isFriend &&
  8079. (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  8080. (!Previous.empty() && CurContext->isDependentContext()))) {
  8081. // ignore these
  8082. } else {
  8083. // The user tried to provide an out-of-line definition for a
  8084. // function that is a member of a class or namespace, but there
  8085. // was no such member function declared (C++ [class.mfct]p2,
  8086. // C++ [namespace.memdef]p2). For example:
  8087. //
  8088. // class X {
  8089. // void f() const;
  8090. // };
  8091. //
  8092. // void X::f() { } // ill-formed
  8093. //
  8094. // Complain about this problem, and attempt to suggest close
  8095. // matches (e.g., those that differ only in cv-qualifiers and
  8096. // whether the parameter types are references).
  8097. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8098. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  8099. AddToScope = ExtraArgs.AddToScope;
  8100. return Result;
  8101. }
  8102. }
  8103. // Unqualified local friend declarations are required to resolve
  8104. // to something.
  8105. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  8106. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8107. *this, Previous, NewFD, ExtraArgs, true, S)) {
  8108. AddToScope = ExtraArgs.AddToScope;
  8109. return Result;
  8110. }
  8111. }
  8112. } else if (!D.isFunctionDefinition() &&
  8113. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  8114. !isFriend && !isFunctionTemplateSpecialization &&
  8115. !isMemberSpecialization) {
  8116. // An out-of-line member function declaration must also be a
  8117. // definition (C++ [class.mfct]p2).
  8118. // Note that this is not the case for explicit specializations of
  8119. // function templates or member functions of class templates, per
  8120. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  8121. // extension for compatibility with old SWIG code which likes to
  8122. // generate them.
  8123. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  8124. << D.getCXXScopeSpec().getRange();
  8125. }
  8126. }
  8127. ProcessPragmaWeak(S, NewFD);
  8128. checkAttributesAfterMerging(*this, *NewFD);
  8129. AddKnownFunctionAttributes(NewFD);
  8130. if (NewFD->hasAttr<OverloadableAttr>() &&
  8131. !NewFD->getType()->getAs<FunctionProtoType>()) {
  8132. Diag(NewFD->getLocation(),
  8133. diag::err_attribute_overloadable_no_prototype)
  8134. << NewFD;
  8135. // Turn this into a variadic function with no parameters.
  8136. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  8137. FunctionProtoType::ExtProtoInfo EPI(
  8138. Context.getDefaultCallingConvention(true, false));
  8139. EPI.Variadic = true;
  8140. EPI.ExtInfo = FT->getExtInfo();
  8141. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  8142. NewFD->setType(R);
  8143. }
  8144. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8145. // member, set the visibility of this function.
  8146. if (!DC->isRecord() && NewFD->isExternallyVisible())
  8147. AddPushedVisibilityAttribute(NewFD);
  8148. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  8149. // marking the function.
  8150. AddCFAuditedAttribute(NewFD);
  8151. // If this is a function definition, check if we have to apply optnone due to
  8152. // a pragma.
  8153. if(D.isFunctionDefinition())
  8154. AddRangeBasedOptnone(NewFD);
  8155. // If this is the first declaration of an extern C variable, update
  8156. // the map of such variables.
  8157. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  8158. isIncompleteDeclExternC(*this, NewFD))
  8159. RegisterLocallyScopedExternCDecl(NewFD, S);
  8160. // Set this FunctionDecl's range up to the right paren.
  8161. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  8162. if (D.isRedeclaration() && !Previous.empty()) {
  8163. NamedDecl *Prev = Previous.getRepresentativeDecl();
  8164. checkDLLAttributeRedeclaration(*this, Prev, NewFD,
  8165. isMemberSpecialization ||
  8166. isFunctionTemplateSpecialization,
  8167. D.isFunctionDefinition());
  8168. }
  8169. if (getLangOpts().CUDA) {
  8170. IdentifierInfo *II = NewFD->getIdentifier();
  8171. if (II && II->isStr(getCudaConfigureFuncName()) &&
  8172. !NewFD->isInvalidDecl() &&
  8173. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  8174. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  8175. Diag(NewFD->getLocation(), diag::err_config_scalar_return)
  8176. << getCudaConfigureFuncName();
  8177. Context.setcudaConfigureCallDecl(NewFD);
  8178. }
  8179. // Variadic functions, other than a *declaration* of printf, are not allowed
  8180. // in device-side CUDA code, unless someone passed
  8181. // -fcuda-allow-variadic-functions.
  8182. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  8183. (NewFD->hasAttr<CUDADeviceAttr>() ||
  8184. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  8185. !(II && II->isStr("printf") && NewFD->isExternC() &&
  8186. !D.isFunctionDefinition())) {
  8187. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  8188. }
  8189. }
  8190. MarkUnusedFileScopedDecl(NewFD);
  8191. if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
  8192. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  8193. if ((getLangOpts().OpenCLVersion >= 120)
  8194. && (SC == SC_Static)) {
  8195. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  8196. D.setInvalidType();
  8197. }
  8198. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  8199. if (!NewFD->getReturnType()->isVoidType()) {
  8200. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  8201. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  8202. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  8203. : FixItHint());
  8204. D.setInvalidType();
  8205. }
  8206. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  8207. for (auto Param : NewFD->parameters())
  8208. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  8209. if (getLangOpts().OpenCLCPlusPlus) {
  8210. if (DC->isRecord()) {
  8211. Diag(D.getIdentifierLoc(), diag::err_method_kernel);
  8212. D.setInvalidType();
  8213. }
  8214. if (FunctionTemplate) {
  8215. Diag(D.getIdentifierLoc(), diag::err_template_kernel);
  8216. D.setInvalidType();
  8217. }
  8218. }
  8219. }
  8220. if (getLangOpts().CPlusPlus) {
  8221. if (FunctionTemplate) {
  8222. if (NewFD->isInvalidDecl())
  8223. FunctionTemplate->setInvalidDecl();
  8224. return FunctionTemplate;
  8225. }
  8226. if (isMemberSpecialization && !NewFD->isInvalidDecl())
  8227. CompleteMemberSpecialization(NewFD, Previous);
  8228. }
  8229. for (const ParmVarDecl *Param : NewFD->parameters()) {
  8230. QualType PT = Param->getType();
  8231. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  8232. // types.
  8233. if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
  8234. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  8235. QualType ElemTy = PipeTy->getElementType();
  8236. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  8237. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  8238. D.setInvalidType();
  8239. }
  8240. }
  8241. }
  8242. }
  8243. // Here we have an function template explicit specialization at class scope.
  8244. // The actual specialization will be postponed to template instatiation
  8245. // time via the ClassScopeFunctionSpecializationDecl node.
  8246. if (isDependentClassScopeExplicitSpecialization) {
  8247. ClassScopeFunctionSpecializationDecl *NewSpec =
  8248. ClassScopeFunctionSpecializationDecl::Create(
  8249. Context, CurContext, NewFD->getLocation(),
  8250. cast<CXXMethodDecl>(NewFD),
  8251. HasExplicitTemplateArgs, TemplateArgs);
  8252. CurContext->addDecl(NewSpec);
  8253. AddToScope = false;
  8254. }
  8255. // Diagnose availability attributes. Availability cannot be used on functions
  8256. // that are run during load/unload.
  8257. if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
  8258. if (NewFD->hasAttr<ConstructorAttr>()) {
  8259. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8260. << 1;
  8261. NewFD->dropAttr<AvailabilityAttr>();
  8262. }
  8263. if (NewFD->hasAttr<DestructorAttr>()) {
  8264. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8265. << 2;
  8266. NewFD->dropAttr<AvailabilityAttr>();
  8267. }
  8268. }
  8269. return NewFD;
  8270. }
  8271. /// Return a CodeSegAttr from a containing class. The Microsoft docs say
  8272. /// when __declspec(code_seg) "is applied to a class, all member functions of
  8273. /// the class and nested classes -- this includes compiler-generated special
  8274. /// member functions -- are put in the specified segment."
  8275. /// The actual behavior is a little more complicated. The Microsoft compiler
  8276. /// won't check outer classes if there is an active value from #pragma code_seg.
  8277. /// The CodeSeg is always applied from the direct parent but only from outer
  8278. /// classes when the #pragma code_seg stack is empty. See:
  8279. /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
  8280. /// available since MS has removed the page.
  8281. static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
  8282. const auto *Method = dyn_cast<CXXMethodDecl>(FD);
  8283. if (!Method)
  8284. return nullptr;
  8285. const CXXRecordDecl *Parent = Method->getParent();
  8286. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8287. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8288. NewAttr->setImplicit(true);
  8289. return NewAttr;
  8290. }
  8291. // The Microsoft compiler won't check outer classes for the CodeSeg
  8292. // when the #pragma code_seg stack is active.
  8293. if (S.CodeSegStack.CurrentValue)
  8294. return nullptr;
  8295. while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
  8296. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8297. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8298. NewAttr->setImplicit(true);
  8299. return NewAttr;
  8300. }
  8301. }
  8302. return nullptr;
  8303. }
  8304. /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
  8305. /// containing class. Otherwise it will return implicit SectionAttr if the
  8306. /// function is a definition and there is an active value on CodeSegStack
  8307. /// (from the current #pragma code-seg value).
  8308. ///
  8309. /// \param FD Function being declared.
  8310. /// \param IsDefinition Whether it is a definition or just a declarartion.
  8311. /// \returns A CodeSegAttr or SectionAttr to apply to the function or
  8312. /// nullptr if no attribute should be added.
  8313. Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
  8314. bool IsDefinition) {
  8315. if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
  8316. return A;
  8317. if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
  8318. CodeSegStack.CurrentValue) {
  8319. return SectionAttr::CreateImplicit(getASTContext(),
  8320. SectionAttr::Declspec_allocate,
  8321. CodeSegStack.CurrentValue->getString(),
  8322. CodeSegStack.CurrentPragmaLocation);
  8323. }
  8324. return nullptr;
  8325. }
  8326. /// Determines if we can perform a correct type check for \p D as a
  8327. /// redeclaration of \p PrevDecl. If not, we can generally still perform a
  8328. /// best-effort check.
  8329. ///
  8330. /// \param NewD The new declaration.
  8331. /// \param OldD The old declaration.
  8332. /// \param NewT The portion of the type of the new declaration to check.
  8333. /// \param OldT The portion of the type of the old declaration to check.
  8334. bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
  8335. QualType NewT, QualType OldT) {
  8336. if (!NewD->getLexicalDeclContext()->isDependentContext())
  8337. return true;
  8338. // For dependently-typed local extern declarations and friends, we can't
  8339. // perform a correct type check in general until instantiation:
  8340. //
  8341. // int f();
  8342. // template<typename T> void g() { T f(); }
  8343. //
  8344. // (valid if g() is only instantiated with T = int).
  8345. if (NewT->isDependentType() &&
  8346. (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
  8347. return false;
  8348. // Similarly, if the previous declaration was a dependent local extern
  8349. // declaration, we don't really know its type yet.
  8350. if (OldT->isDependentType() && OldD->isLocalExternDecl())
  8351. return false;
  8352. return true;
  8353. }
  8354. /// Checks if the new declaration declared in dependent context must be
  8355. /// put in the same redeclaration chain as the specified declaration.
  8356. ///
  8357. /// \param D Declaration that is checked.
  8358. /// \param PrevDecl Previous declaration found with proper lookup method for the
  8359. /// same declaration name.
  8360. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  8361. /// belongs to.
  8362. ///
  8363. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  8364. if (!D->getLexicalDeclContext()->isDependentContext())
  8365. return true;
  8366. // Don't chain dependent friend function definitions until instantiation, to
  8367. // permit cases like
  8368. //
  8369. // void func();
  8370. // template<typename T> class C1 { friend void func() {} };
  8371. // template<typename T> class C2 { friend void func() {} };
  8372. //
  8373. // ... which is valid if only one of C1 and C2 is ever instantiated.
  8374. //
  8375. // FIXME: This need only apply to function definitions. For now, we proxy
  8376. // this by checking for a file-scope function. We do not want this to apply
  8377. // to friend declarations nominating member functions, because that gets in
  8378. // the way of access checks.
  8379. if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
  8380. return false;
  8381. auto *VD = dyn_cast<ValueDecl>(D);
  8382. auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
  8383. return !VD || !PrevVD ||
  8384. canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
  8385. PrevVD->getType());
  8386. }
  8387. /// Check the target attribute of the function for MultiVersion
  8388. /// validity.
  8389. ///
  8390. /// Returns true if there was an error, false otherwise.
  8391. static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
  8392. const auto *TA = FD->getAttr<TargetAttr>();
  8393. assert(TA && "MultiVersion Candidate requires a target attribute");
  8394. TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
  8395. const TargetInfo &TargetInfo = S.Context.getTargetInfo();
  8396. enum ErrType { Feature = 0, Architecture = 1 };
  8397. if (!ParseInfo.Architecture.empty() &&
  8398. !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
  8399. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8400. << Architecture << ParseInfo.Architecture;
  8401. return true;
  8402. }
  8403. for (const auto &Feat : ParseInfo.Features) {
  8404. auto BareFeat = StringRef{Feat}.substr(1);
  8405. if (Feat[0] == '-') {
  8406. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8407. << Feature << ("no-" + BareFeat).str();
  8408. return true;
  8409. }
  8410. if (!TargetInfo.validateCpuSupports(BareFeat) ||
  8411. !TargetInfo.isValidFeatureName(BareFeat)) {
  8412. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8413. << Feature << BareFeat;
  8414. return true;
  8415. }
  8416. }
  8417. return false;
  8418. }
  8419. static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
  8420. MultiVersionKind MVType) {
  8421. for (const Attr *A : FD->attrs()) {
  8422. switch (A->getKind()) {
  8423. case attr::CPUDispatch:
  8424. case attr::CPUSpecific:
  8425. if (MVType != MultiVersionKind::CPUDispatch &&
  8426. MVType != MultiVersionKind::CPUSpecific)
  8427. return true;
  8428. break;
  8429. case attr::Target:
  8430. if (MVType != MultiVersionKind::Target)
  8431. return true;
  8432. break;
  8433. default:
  8434. return true;
  8435. }
  8436. }
  8437. return false;
  8438. }
  8439. static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
  8440. const FunctionDecl *NewFD,
  8441. bool CausesMV,
  8442. MultiVersionKind MVType) {
  8443. enum DoesntSupport {
  8444. FuncTemplates = 0,
  8445. VirtFuncs = 1,
  8446. DeducedReturn = 2,
  8447. Constructors = 3,
  8448. Destructors = 4,
  8449. DeletedFuncs = 5,
  8450. DefaultedFuncs = 6,
  8451. ConstexprFuncs = 7,
  8452. ConstevalFuncs = 8,
  8453. };
  8454. enum Different {
  8455. CallingConv = 0,
  8456. ReturnType = 1,
  8457. ConstexprSpec = 2,
  8458. InlineSpec = 3,
  8459. StorageClass = 4,
  8460. Linkage = 5
  8461. };
  8462. bool IsCPUSpecificCPUDispatchMVType =
  8463. MVType == MultiVersionKind::CPUDispatch ||
  8464. MVType == MultiVersionKind::CPUSpecific;
  8465. if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
  8466. S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
  8467. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8468. return true;
  8469. }
  8470. if (!NewFD->getType()->getAs<FunctionProtoType>())
  8471. return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
  8472. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8473. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8474. if (OldFD)
  8475. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8476. return true;
  8477. }
  8478. // For now, disallow all other attributes. These should be opt-in, but
  8479. // an analysis of all of them is a future FIXME.
  8480. if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
  8481. S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8482. << IsCPUSpecificCPUDispatchMVType;
  8483. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8484. return true;
  8485. }
  8486. if (HasNonMultiVersionAttributes(NewFD, MVType))
  8487. return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8488. << IsCPUSpecificCPUDispatchMVType;
  8489. if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  8490. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8491. << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
  8492. if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
  8493. if (NewCXXFD->isVirtual())
  8494. return S.Diag(NewCXXFD->getLocation(),
  8495. diag::err_multiversion_doesnt_support)
  8496. << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
  8497. if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
  8498. return S.Diag(NewCXXCtor->getLocation(),
  8499. diag::err_multiversion_doesnt_support)
  8500. << IsCPUSpecificCPUDispatchMVType << Constructors;
  8501. if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
  8502. return S.Diag(NewCXXDtor->getLocation(),
  8503. diag::err_multiversion_doesnt_support)
  8504. << IsCPUSpecificCPUDispatchMVType << Destructors;
  8505. }
  8506. if (NewFD->isDeleted())
  8507. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8508. << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
  8509. if (NewFD->isDefaulted())
  8510. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8511. << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
  8512. if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
  8513. MVType == MultiVersionKind::CPUSpecific))
  8514. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8515. << IsCPUSpecificCPUDispatchMVType
  8516. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  8517. QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
  8518. const auto *NewType = cast<FunctionType>(NewQType);
  8519. QualType NewReturnType = NewType->getReturnType();
  8520. if (NewReturnType->isUndeducedType())
  8521. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8522. << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
  8523. // Only allow transition to MultiVersion if it hasn't been used.
  8524. if (OldFD && CausesMV && OldFD->isUsed(false))
  8525. return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
  8526. // Ensure the return type is identical.
  8527. if (OldFD) {
  8528. QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
  8529. const auto *OldType = cast<FunctionType>(OldQType);
  8530. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  8531. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  8532. if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
  8533. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8534. << CallingConv;
  8535. QualType OldReturnType = OldType->getReturnType();
  8536. if (OldReturnType != NewReturnType)
  8537. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8538. << ReturnType;
  8539. if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
  8540. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8541. << ConstexprSpec;
  8542. if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
  8543. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8544. << InlineSpec;
  8545. if (OldFD->getStorageClass() != NewFD->getStorageClass())
  8546. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8547. << StorageClass;
  8548. if (OldFD->isExternC() != NewFD->isExternC())
  8549. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8550. << Linkage;
  8551. if (S.CheckEquivalentExceptionSpec(
  8552. OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
  8553. NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
  8554. return true;
  8555. }
  8556. return false;
  8557. }
  8558. /// Check the validity of a multiversion function declaration that is the
  8559. /// first of its kind. Also sets the multiversion'ness' of the function itself.
  8560. ///
  8561. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8562. ///
  8563. /// Returns true if there was an error, false otherwise.
  8564. static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
  8565. MultiVersionKind MVType,
  8566. const TargetAttr *TA) {
  8567. assert(MVType != MultiVersionKind::None &&
  8568. "Function lacks multiversion attribute");
  8569. // Target only causes MV if it is default, otherwise this is a normal
  8570. // function.
  8571. if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
  8572. return false;
  8573. if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
  8574. FD->setInvalidDecl();
  8575. return true;
  8576. }
  8577. if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
  8578. FD->setInvalidDecl();
  8579. return true;
  8580. }
  8581. FD->setIsMultiVersion();
  8582. return false;
  8583. }
  8584. static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
  8585. for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
  8586. if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
  8587. return true;
  8588. }
  8589. return false;
  8590. }
  8591. static bool CheckTargetCausesMultiVersioning(
  8592. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
  8593. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8594. LookupResult &Previous) {
  8595. const auto *OldTA = OldFD->getAttr<TargetAttr>();
  8596. TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
  8597. // Sort order doesn't matter, it just needs to be consistent.
  8598. llvm::sort(NewParsed.Features);
  8599. // If the old decl is NOT MultiVersioned yet, and we don't cause that
  8600. // to change, this is a simple redeclaration.
  8601. if (!NewTA->isDefaultVersion() &&
  8602. (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
  8603. return false;
  8604. // Otherwise, this decl causes MultiVersioning.
  8605. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8606. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8607. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8608. NewFD->setInvalidDecl();
  8609. return true;
  8610. }
  8611. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
  8612. MultiVersionKind::Target)) {
  8613. NewFD->setInvalidDecl();
  8614. return true;
  8615. }
  8616. if (CheckMultiVersionValue(S, NewFD)) {
  8617. NewFD->setInvalidDecl();
  8618. return true;
  8619. }
  8620. // If this is 'default', permit the forward declaration.
  8621. if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
  8622. Redeclaration = true;
  8623. OldDecl = OldFD;
  8624. OldFD->setIsMultiVersion();
  8625. NewFD->setIsMultiVersion();
  8626. return false;
  8627. }
  8628. if (CheckMultiVersionValue(S, OldFD)) {
  8629. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8630. NewFD->setInvalidDecl();
  8631. return true;
  8632. }
  8633. TargetAttr::ParsedTargetAttr OldParsed =
  8634. OldTA->parse(std::less<std::string>());
  8635. if (OldParsed == NewParsed) {
  8636. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8637. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8638. NewFD->setInvalidDecl();
  8639. return true;
  8640. }
  8641. for (const auto *FD : OldFD->redecls()) {
  8642. const auto *CurTA = FD->getAttr<TargetAttr>();
  8643. // We allow forward declarations before ANY multiversioning attributes, but
  8644. // nothing after the fact.
  8645. if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
  8646. (!CurTA || CurTA->isInherited())) {
  8647. S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
  8648. << 0;
  8649. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8650. NewFD->setInvalidDecl();
  8651. return true;
  8652. }
  8653. }
  8654. OldFD->setIsMultiVersion();
  8655. NewFD->setIsMultiVersion();
  8656. Redeclaration = false;
  8657. MergeTypeWithPrevious = false;
  8658. OldDecl = nullptr;
  8659. Previous.clear();
  8660. return false;
  8661. }
  8662. /// Check the validity of a new function declaration being added to an existing
  8663. /// multiversioned declaration collection.
  8664. static bool CheckMultiVersionAdditionalDecl(
  8665. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
  8666. MultiVersionKind NewMVType, const TargetAttr *NewTA,
  8667. const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
  8668. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8669. LookupResult &Previous) {
  8670. MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
  8671. // Disallow mixing of multiversioning types.
  8672. if ((OldMVType == MultiVersionKind::Target &&
  8673. NewMVType != MultiVersionKind::Target) ||
  8674. (NewMVType == MultiVersionKind::Target &&
  8675. OldMVType != MultiVersionKind::Target)) {
  8676. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8677. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8678. NewFD->setInvalidDecl();
  8679. return true;
  8680. }
  8681. TargetAttr::ParsedTargetAttr NewParsed;
  8682. if (NewTA) {
  8683. NewParsed = NewTA->parse();
  8684. llvm::sort(NewParsed.Features);
  8685. }
  8686. bool UseMemberUsingDeclRules =
  8687. S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
  8688. // Next, check ALL non-overloads to see if this is a redeclaration of a
  8689. // previous member of the MultiVersion set.
  8690. for (NamedDecl *ND : Previous) {
  8691. FunctionDecl *CurFD = ND->getAsFunction();
  8692. if (!CurFD)
  8693. continue;
  8694. if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
  8695. continue;
  8696. if (NewMVType == MultiVersionKind::Target) {
  8697. const auto *CurTA = CurFD->getAttr<TargetAttr>();
  8698. if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
  8699. NewFD->setIsMultiVersion();
  8700. Redeclaration = true;
  8701. OldDecl = ND;
  8702. return false;
  8703. }
  8704. TargetAttr::ParsedTargetAttr CurParsed =
  8705. CurTA->parse(std::less<std::string>());
  8706. if (CurParsed == NewParsed) {
  8707. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8708. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8709. NewFD->setInvalidDecl();
  8710. return true;
  8711. }
  8712. } else {
  8713. const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
  8714. const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
  8715. // Handle CPUDispatch/CPUSpecific versions.
  8716. // Only 1 CPUDispatch function is allowed, this will make it go through
  8717. // the redeclaration errors.
  8718. if (NewMVType == MultiVersionKind::CPUDispatch &&
  8719. CurFD->hasAttr<CPUDispatchAttr>()) {
  8720. if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
  8721. std::equal(
  8722. CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
  8723. NewCPUDisp->cpus_begin(),
  8724. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8725. return Cur->getName() == New->getName();
  8726. })) {
  8727. NewFD->setIsMultiVersion();
  8728. Redeclaration = true;
  8729. OldDecl = ND;
  8730. return false;
  8731. }
  8732. // If the declarations don't match, this is an error condition.
  8733. S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
  8734. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8735. NewFD->setInvalidDecl();
  8736. return true;
  8737. }
  8738. if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
  8739. if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
  8740. std::equal(
  8741. CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
  8742. NewCPUSpec->cpus_begin(),
  8743. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8744. return Cur->getName() == New->getName();
  8745. })) {
  8746. NewFD->setIsMultiVersion();
  8747. Redeclaration = true;
  8748. OldDecl = ND;
  8749. return false;
  8750. }
  8751. // Only 1 version of CPUSpecific is allowed for each CPU.
  8752. for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
  8753. for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
  8754. if (CurII == NewII) {
  8755. S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
  8756. << NewII;
  8757. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8758. NewFD->setInvalidDecl();
  8759. return true;
  8760. }
  8761. }
  8762. }
  8763. }
  8764. // If the two decls aren't the same MVType, there is no possible error
  8765. // condition.
  8766. }
  8767. }
  8768. // Else, this is simply a non-redecl case. Checking the 'value' is only
  8769. // necessary in the Target case, since The CPUSpecific/Dispatch cases are
  8770. // handled in the attribute adding step.
  8771. if (NewMVType == MultiVersionKind::Target &&
  8772. CheckMultiVersionValue(S, NewFD)) {
  8773. NewFD->setInvalidDecl();
  8774. return true;
  8775. }
  8776. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
  8777. !OldFD->isMultiVersion(), NewMVType)) {
  8778. NewFD->setInvalidDecl();
  8779. return true;
  8780. }
  8781. // Permit forward declarations in the case where these two are compatible.
  8782. if (!OldFD->isMultiVersion()) {
  8783. OldFD->setIsMultiVersion();
  8784. NewFD->setIsMultiVersion();
  8785. Redeclaration = true;
  8786. OldDecl = OldFD;
  8787. return false;
  8788. }
  8789. NewFD->setIsMultiVersion();
  8790. Redeclaration = false;
  8791. MergeTypeWithPrevious = false;
  8792. OldDecl = nullptr;
  8793. Previous.clear();
  8794. return false;
  8795. }
  8796. /// Check the validity of a mulitversion function declaration.
  8797. /// Also sets the multiversion'ness' of the function itself.
  8798. ///
  8799. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8800. ///
  8801. /// Returns true if there was an error, false otherwise.
  8802. static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
  8803. bool &Redeclaration, NamedDecl *&OldDecl,
  8804. bool &MergeTypeWithPrevious,
  8805. LookupResult &Previous) {
  8806. const auto *NewTA = NewFD->getAttr<TargetAttr>();
  8807. const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
  8808. const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
  8809. // Mixing Multiversioning types is prohibited.
  8810. if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
  8811. (NewCPUDisp && NewCPUSpec)) {
  8812. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8813. NewFD->setInvalidDecl();
  8814. return true;
  8815. }
  8816. MultiVersionKind MVType = NewFD->getMultiVersionKind();
  8817. // Main isn't allowed to become a multiversion function, however it IS
  8818. // permitted to have 'main' be marked with the 'target' optimization hint.
  8819. if (NewFD->isMain()) {
  8820. if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
  8821. MVType == MultiVersionKind::CPUDispatch ||
  8822. MVType == MultiVersionKind::CPUSpecific) {
  8823. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
  8824. NewFD->setInvalidDecl();
  8825. return true;
  8826. }
  8827. return false;
  8828. }
  8829. if (!OldDecl || !OldDecl->getAsFunction() ||
  8830. OldDecl->getDeclContext()->getRedeclContext() !=
  8831. NewFD->getDeclContext()->getRedeclContext()) {
  8832. // If there's no previous declaration, AND this isn't attempting to cause
  8833. // multiversioning, this isn't an error condition.
  8834. if (MVType == MultiVersionKind::None)
  8835. return false;
  8836. return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
  8837. }
  8838. FunctionDecl *OldFD = OldDecl->getAsFunction();
  8839. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
  8840. return false;
  8841. if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
  8842. S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
  8843. << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
  8844. NewFD->setInvalidDecl();
  8845. return true;
  8846. }
  8847. // Handle the target potentially causes multiversioning case.
  8848. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
  8849. return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
  8850. Redeclaration, OldDecl,
  8851. MergeTypeWithPrevious, Previous);
  8852. // At this point, we have a multiversion function decl (in OldFD) AND an
  8853. // appropriate attribute in the current function decl. Resolve that these are
  8854. // still compatible with previous declarations.
  8855. return CheckMultiVersionAdditionalDecl(
  8856. S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
  8857. OldDecl, MergeTypeWithPrevious, Previous);
  8858. }
  8859. /// Perform semantic checking of a new function declaration.
  8860. ///
  8861. /// Performs semantic analysis of the new function declaration
  8862. /// NewFD. This routine performs all semantic checking that does not
  8863. /// require the actual declarator involved in the declaration, and is
  8864. /// used both for the declaration of functions as they are parsed
  8865. /// (called via ActOnDeclarator) and for the declaration of functions
  8866. /// that have been instantiated via C++ template instantiation (called
  8867. /// via InstantiateDecl).
  8868. ///
  8869. /// \param IsMemberSpecialization whether this new function declaration is
  8870. /// a member specialization (that replaces any definition provided by the
  8871. /// previous declaration).
  8872. ///
  8873. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8874. ///
  8875. /// \returns true if the function declaration is a redeclaration.
  8876. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  8877. LookupResult &Previous,
  8878. bool IsMemberSpecialization) {
  8879. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  8880. "Variably modified return types are not handled here");
  8881. // Determine whether the type of this function should be merged with
  8882. // a previous visible declaration. This never happens for functions in C++,
  8883. // and always happens in C if the previous declaration was visible.
  8884. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  8885. !Previous.isShadowed();
  8886. bool Redeclaration = false;
  8887. NamedDecl *OldDecl = nullptr;
  8888. bool MayNeedOverloadableChecks = false;
  8889. // Merge or overload the declaration with an existing declaration of
  8890. // the same name, if appropriate.
  8891. if (!Previous.empty()) {
  8892. // Determine whether NewFD is an overload of PrevDecl or
  8893. // a declaration that requires merging. If it's an overload,
  8894. // there's no more work to do here; we'll just add the new
  8895. // function to the scope.
  8896. if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
  8897. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  8898. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  8899. Redeclaration = true;
  8900. OldDecl = Candidate;
  8901. }
  8902. } else {
  8903. MayNeedOverloadableChecks = true;
  8904. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  8905. /*NewIsUsingDecl*/ false)) {
  8906. case Ovl_Match:
  8907. Redeclaration = true;
  8908. break;
  8909. case Ovl_NonFunction:
  8910. Redeclaration = true;
  8911. break;
  8912. case Ovl_Overload:
  8913. Redeclaration = false;
  8914. break;
  8915. }
  8916. }
  8917. }
  8918. // Check for a previous extern "C" declaration with this name.
  8919. if (!Redeclaration &&
  8920. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  8921. if (!Previous.empty()) {
  8922. // This is an extern "C" declaration with the same name as a previous
  8923. // declaration, and thus redeclares that entity...
  8924. Redeclaration = true;
  8925. OldDecl = Previous.getFoundDecl();
  8926. MergeTypeWithPrevious = false;
  8927. // ... except in the presence of __attribute__((overloadable)).
  8928. if (OldDecl->hasAttr<OverloadableAttr>() ||
  8929. NewFD->hasAttr<OverloadableAttr>()) {
  8930. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  8931. MayNeedOverloadableChecks = true;
  8932. Redeclaration = false;
  8933. OldDecl = nullptr;
  8934. }
  8935. }
  8936. }
  8937. }
  8938. if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
  8939. MergeTypeWithPrevious, Previous))
  8940. return Redeclaration;
  8941. // C++11 [dcl.constexpr]p8:
  8942. // A constexpr specifier for a non-static member function that is not
  8943. // a constructor declares that member function to be const.
  8944. //
  8945. // This needs to be delayed until we know whether this is an out-of-line
  8946. // definition of a static member function.
  8947. //
  8948. // This rule is not present in C++1y, so we produce a backwards
  8949. // compatibility warning whenever it happens in C++11.
  8950. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  8951. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  8952. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  8953. !MD->getMethodQualifiers().hasConst()) {
  8954. CXXMethodDecl *OldMD = nullptr;
  8955. if (OldDecl)
  8956. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  8957. if (!OldMD || !OldMD->isStatic()) {
  8958. const FunctionProtoType *FPT =
  8959. MD->getType()->castAs<FunctionProtoType>();
  8960. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  8961. EPI.TypeQuals.addConst();
  8962. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  8963. FPT->getParamTypes(), EPI));
  8964. // Warn that we did this, if we're not performing template instantiation.
  8965. // In that case, we'll have warned already when the template was defined.
  8966. if (!inTemplateInstantiation()) {
  8967. SourceLocation AddConstLoc;
  8968. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  8969. .IgnoreParens().getAs<FunctionTypeLoc>())
  8970. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  8971. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  8972. << FixItHint::CreateInsertion(AddConstLoc, " const");
  8973. }
  8974. }
  8975. }
  8976. if (Redeclaration) {
  8977. // NewFD and OldDecl represent declarations that need to be
  8978. // merged.
  8979. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  8980. NewFD->setInvalidDecl();
  8981. return Redeclaration;
  8982. }
  8983. Previous.clear();
  8984. Previous.addDecl(OldDecl);
  8985. if (FunctionTemplateDecl *OldTemplateDecl =
  8986. dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  8987. auto *OldFD = OldTemplateDecl->getTemplatedDecl();
  8988. FunctionTemplateDecl *NewTemplateDecl
  8989. = NewFD->getDescribedFunctionTemplate();
  8990. assert(NewTemplateDecl && "Template/non-template mismatch");
  8991. // The call to MergeFunctionDecl above may have created some state in
  8992. // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
  8993. // can add it as a redeclaration.
  8994. NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
  8995. NewFD->setPreviousDeclaration(OldFD);
  8996. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  8997. if (NewFD->isCXXClassMember()) {
  8998. NewFD->setAccess(OldTemplateDecl->getAccess());
  8999. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  9000. }
  9001. // If this is an explicit specialization of a member that is a function
  9002. // template, mark it as a member specialization.
  9003. if (IsMemberSpecialization &&
  9004. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  9005. NewTemplateDecl->setMemberSpecialization();
  9006. assert(OldTemplateDecl->isMemberSpecialization());
  9007. // Explicit specializations of a member template do not inherit deleted
  9008. // status from the parent member template that they are specializing.
  9009. if (OldFD->isDeleted()) {
  9010. // FIXME: This assert will not hold in the presence of modules.
  9011. assert(OldFD->getCanonicalDecl() == OldFD);
  9012. // FIXME: We need an update record for this AST mutation.
  9013. OldFD->setDeletedAsWritten(false);
  9014. }
  9015. }
  9016. } else {
  9017. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  9018. auto *OldFD = cast<FunctionDecl>(OldDecl);
  9019. // This needs to happen first so that 'inline' propagates.
  9020. NewFD->setPreviousDeclaration(OldFD);
  9021. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  9022. if (NewFD->isCXXClassMember())
  9023. NewFD->setAccess(OldFD->getAccess());
  9024. }
  9025. }
  9026. } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
  9027. !NewFD->getAttr<OverloadableAttr>()) {
  9028. assert((Previous.empty() ||
  9029. llvm::any_of(Previous,
  9030. [](const NamedDecl *ND) {
  9031. return ND->hasAttr<OverloadableAttr>();
  9032. })) &&
  9033. "Non-redecls shouldn't happen without overloadable present");
  9034. auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
  9035. const auto *FD = dyn_cast<FunctionDecl>(ND);
  9036. return FD && !FD->hasAttr<OverloadableAttr>();
  9037. });
  9038. if (OtherUnmarkedIter != Previous.end()) {
  9039. Diag(NewFD->getLocation(),
  9040. diag::err_attribute_overloadable_multiple_unmarked_overloads);
  9041. Diag((*OtherUnmarkedIter)->getLocation(),
  9042. diag::note_attribute_overloadable_prev_overload)
  9043. << false;
  9044. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  9045. }
  9046. }
  9047. // Semantic checking for this function declaration (in isolation).
  9048. if (getLangOpts().CPlusPlus) {
  9049. // C++-specific checks.
  9050. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  9051. CheckConstructor(Constructor);
  9052. } else if (CXXDestructorDecl *Destructor =
  9053. dyn_cast<CXXDestructorDecl>(NewFD)) {
  9054. CXXRecordDecl *Record = Destructor->getParent();
  9055. QualType ClassType = Context.getTypeDeclType(Record);
  9056. // FIXME: Shouldn't we be able to perform this check even when the class
  9057. // type is dependent? Both gcc and edg can handle that.
  9058. if (!ClassType->isDependentType()) {
  9059. DeclarationName Name
  9060. = Context.DeclarationNames.getCXXDestructorName(
  9061. Context.getCanonicalType(ClassType));
  9062. if (NewFD->getDeclName() != Name) {
  9063. Diag(NewFD->getLocation(), diag::err_destructor_name);
  9064. NewFD->setInvalidDecl();
  9065. return Redeclaration;
  9066. }
  9067. }
  9068. } else if (CXXConversionDecl *Conversion
  9069. = dyn_cast<CXXConversionDecl>(NewFD)) {
  9070. ActOnConversionDeclarator(Conversion);
  9071. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  9072. if (auto *TD = Guide->getDescribedFunctionTemplate())
  9073. CheckDeductionGuideTemplate(TD);
  9074. // A deduction guide is not on the list of entities that can be
  9075. // explicitly specialized.
  9076. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  9077. Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
  9078. << /*explicit specialization*/ 1;
  9079. }
  9080. // Find any virtual functions that this function overrides.
  9081. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  9082. if (!Method->isFunctionTemplateSpecialization() &&
  9083. !Method->getDescribedFunctionTemplate() &&
  9084. Method->isCanonicalDecl()) {
  9085. if (AddOverriddenMethods(Method->getParent(), Method)) {
  9086. // If the function was marked as "static", we have a problem.
  9087. if (NewFD->getStorageClass() == SC_Static) {
  9088. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  9089. }
  9090. }
  9091. }
  9092. if (Method->isStatic())
  9093. checkThisInStaticMemberFunctionType(Method);
  9094. }
  9095. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  9096. if (NewFD->isOverloadedOperator() &&
  9097. CheckOverloadedOperatorDeclaration(NewFD)) {
  9098. NewFD->setInvalidDecl();
  9099. return Redeclaration;
  9100. }
  9101. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  9102. if (NewFD->getLiteralIdentifier() &&
  9103. CheckLiteralOperatorDeclaration(NewFD)) {
  9104. NewFD->setInvalidDecl();
  9105. return Redeclaration;
  9106. }
  9107. // In C++, check default arguments now that we have merged decls. Unless
  9108. // the lexical context is the class, because in this case this is done
  9109. // during delayed parsing anyway.
  9110. if (!CurContext->isRecord())
  9111. CheckCXXDefaultArguments(NewFD);
  9112. // If this function declares a builtin function, check the type of this
  9113. // declaration against the expected type for the builtin.
  9114. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  9115. ASTContext::GetBuiltinTypeError Error;
  9116. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  9117. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  9118. // If the type of the builtin differs only in its exception
  9119. // specification, that's OK.
  9120. // FIXME: If the types do differ in this way, it would be better to
  9121. // retain the 'noexcept' form of the type.
  9122. if (!T.isNull() &&
  9123. !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
  9124. NewFD->getType()))
  9125. // The type of this function differs from the type of the builtin,
  9126. // so forget about the builtin entirely.
  9127. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  9128. }
  9129. // If this function is declared as being extern "C", then check to see if
  9130. // the function returns a UDT (class, struct, or union type) that is not C
  9131. // compatible, and if it does, warn the user.
  9132. // But, issue any diagnostic on the first declaration only.
  9133. if (Previous.empty() && NewFD->isExternC()) {
  9134. QualType R = NewFD->getReturnType();
  9135. if (R->isIncompleteType() && !R->isVoidType())
  9136. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  9137. << NewFD << R;
  9138. else if (!R.isPODType(Context) && !R->isVoidType() &&
  9139. !R->isObjCObjectPointerType())
  9140. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  9141. }
  9142. // C++1z [dcl.fct]p6:
  9143. // [...] whether the function has a non-throwing exception-specification
  9144. // [is] part of the function type
  9145. //
  9146. // This results in an ABI break between C++14 and C++17 for functions whose
  9147. // declared type includes an exception-specification in a parameter or
  9148. // return type. (Exception specifications on the function itself are OK in
  9149. // most cases, and exception specifications are not permitted in most other
  9150. // contexts where they could make it into a mangling.)
  9151. if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
  9152. auto HasNoexcept = [&](QualType T) -> bool {
  9153. // Strip off declarator chunks that could be between us and a function
  9154. // type. We don't need to look far, exception specifications are very
  9155. // restricted prior to C++17.
  9156. if (auto *RT = T->getAs<ReferenceType>())
  9157. T = RT->getPointeeType();
  9158. else if (T->isAnyPointerType())
  9159. T = T->getPointeeType();
  9160. else if (auto *MPT = T->getAs<MemberPointerType>())
  9161. T = MPT->getPointeeType();
  9162. if (auto *FPT = T->getAs<FunctionProtoType>())
  9163. if (FPT->isNothrow())
  9164. return true;
  9165. return false;
  9166. };
  9167. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  9168. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  9169. for (QualType T : FPT->param_types())
  9170. AnyNoexcept |= HasNoexcept(T);
  9171. if (AnyNoexcept)
  9172. Diag(NewFD->getLocation(),
  9173. diag::warn_cxx17_compat_exception_spec_in_signature)
  9174. << NewFD;
  9175. }
  9176. if (!Redeclaration && LangOpts.CUDA)
  9177. checkCUDATargetOverload(NewFD, Previous);
  9178. }
  9179. return Redeclaration;
  9180. }
  9181. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  9182. // C++11 [basic.start.main]p3:
  9183. // A program that [...] declares main to be inline, static or
  9184. // constexpr is ill-formed.
  9185. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  9186. // appear in a declaration of main.
  9187. // static main is not an error under C99, but we should warn about it.
  9188. // We accept _Noreturn main as an extension.
  9189. if (FD->getStorageClass() == SC_Static)
  9190. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  9191. ? diag::err_static_main : diag::warn_static_main)
  9192. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  9193. if (FD->isInlineSpecified())
  9194. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  9195. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  9196. if (DS.isNoreturnSpecified()) {
  9197. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  9198. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  9199. Diag(NoreturnLoc, diag::ext_noreturn_main);
  9200. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  9201. << FixItHint::CreateRemoval(NoreturnRange);
  9202. }
  9203. if (FD->isConstexpr()) {
  9204. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  9205. << FD->isConsteval()
  9206. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  9207. FD->setConstexprKind(CSK_unspecified);
  9208. }
  9209. if (getLangOpts().OpenCL) {
  9210. Diag(FD->getLocation(), diag::err_opencl_no_main)
  9211. << FD->hasAttr<OpenCLKernelAttr>();
  9212. FD->setInvalidDecl();
  9213. return;
  9214. }
  9215. QualType T = FD->getType();
  9216. assert(T->isFunctionType() && "function decl is not of function type");
  9217. const FunctionType* FT = T->castAs<FunctionType>();
  9218. // Set default calling convention for main()
  9219. if (FT->getCallConv() != CC_C) {
  9220. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
  9221. FD->setType(QualType(FT, 0));
  9222. T = Context.getCanonicalType(FD->getType());
  9223. }
  9224. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  9225. // In C with GNU extensions we allow main() to have non-integer return
  9226. // type, but we should warn about the extension, and we disable the
  9227. // implicit-return-zero rule.
  9228. // GCC in C mode accepts qualified 'int'.
  9229. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  9230. FD->setHasImplicitReturnZero(true);
  9231. else {
  9232. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  9233. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9234. if (RTRange.isValid())
  9235. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  9236. << FixItHint::CreateReplacement(RTRange, "int");
  9237. }
  9238. } else {
  9239. // In C and C++, main magically returns 0 if you fall off the end;
  9240. // set the flag which tells us that.
  9241. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  9242. // All the standards say that main() should return 'int'.
  9243. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  9244. FD->setHasImplicitReturnZero(true);
  9245. else {
  9246. // Otherwise, this is just a flat-out error.
  9247. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9248. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  9249. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  9250. : FixItHint());
  9251. FD->setInvalidDecl(true);
  9252. }
  9253. }
  9254. // Treat protoless main() as nullary.
  9255. if (isa<FunctionNoProtoType>(FT)) return;
  9256. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  9257. unsigned nparams = FTP->getNumParams();
  9258. assert(FD->getNumParams() == nparams);
  9259. bool HasExtraParameters = (nparams > 3);
  9260. if (FTP->isVariadic()) {
  9261. Diag(FD->getLocation(), diag::ext_variadic_main);
  9262. // FIXME: if we had information about the location of the ellipsis, we
  9263. // could add a FixIt hint to remove it as a parameter.
  9264. }
  9265. // Darwin passes an undocumented fourth argument of type char**. If
  9266. // other platforms start sprouting these, the logic below will start
  9267. // getting shifty.
  9268. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  9269. HasExtraParameters = false;
  9270. if (HasExtraParameters) {
  9271. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  9272. FD->setInvalidDecl(true);
  9273. nparams = 3;
  9274. }
  9275. // FIXME: a lot of the following diagnostics would be improved
  9276. // if we had some location information about types.
  9277. QualType CharPP =
  9278. Context.getPointerType(Context.getPointerType(Context.CharTy));
  9279. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  9280. for (unsigned i = 0; i < nparams; ++i) {
  9281. QualType AT = FTP->getParamType(i);
  9282. bool mismatch = true;
  9283. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  9284. mismatch = false;
  9285. else if (Expected[i] == CharPP) {
  9286. // As an extension, the following forms are okay:
  9287. // char const **
  9288. // char const * const *
  9289. // char * const *
  9290. QualifierCollector qs;
  9291. const PointerType* PT;
  9292. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  9293. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  9294. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  9295. Context.CharTy)) {
  9296. qs.removeConst();
  9297. mismatch = !qs.empty();
  9298. }
  9299. }
  9300. if (mismatch) {
  9301. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  9302. // TODO: suggest replacing given type with expected type
  9303. FD->setInvalidDecl(true);
  9304. }
  9305. }
  9306. if (nparams == 1 && !FD->isInvalidDecl()) {
  9307. Diag(FD->getLocation(), diag::warn_main_one_arg);
  9308. }
  9309. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9310. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9311. FD->setInvalidDecl();
  9312. }
  9313. }
  9314. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  9315. QualType T = FD->getType();
  9316. assert(T->isFunctionType() && "function decl is not of function type");
  9317. const FunctionType *FT = T->castAs<FunctionType>();
  9318. // Set an implicit return of 'zero' if the function can return some integral,
  9319. // enumeration, pointer or nullptr type.
  9320. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  9321. FT->getReturnType()->isAnyPointerType() ||
  9322. FT->getReturnType()->isNullPtrType())
  9323. // DllMain is exempt because a return value of zero means it failed.
  9324. if (FD->getName() != "DllMain")
  9325. FD->setHasImplicitReturnZero(true);
  9326. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9327. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9328. FD->setInvalidDecl();
  9329. }
  9330. }
  9331. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  9332. // FIXME: Need strict checking. In C89, we need to check for
  9333. // any assignment, increment, decrement, function-calls, or
  9334. // commas outside of a sizeof. In C99, it's the same list,
  9335. // except that the aforementioned are allowed in unevaluated
  9336. // expressions. Everything else falls under the
  9337. // "may accept other forms of constant expressions" exception.
  9338. // (We never end up here for C++, so the constant expression
  9339. // rules there don't matter.)
  9340. const Expr *Culprit;
  9341. if (Init->isConstantInitializer(Context, false, &Culprit))
  9342. return false;
  9343. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  9344. << Culprit->getSourceRange();
  9345. return true;
  9346. }
  9347. namespace {
  9348. // Visits an initialization expression to see if OrigDecl is evaluated in
  9349. // its own initialization and throws a warning if it does.
  9350. class SelfReferenceChecker
  9351. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  9352. Sema &S;
  9353. Decl *OrigDecl;
  9354. bool isRecordType;
  9355. bool isPODType;
  9356. bool isReferenceType;
  9357. bool isInitList;
  9358. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  9359. public:
  9360. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  9361. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  9362. S(S), OrigDecl(OrigDecl) {
  9363. isPODType = false;
  9364. isRecordType = false;
  9365. isReferenceType = false;
  9366. isInitList = false;
  9367. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  9368. isPODType = VD->getType().isPODType(S.Context);
  9369. isRecordType = VD->getType()->isRecordType();
  9370. isReferenceType = VD->getType()->isReferenceType();
  9371. }
  9372. }
  9373. // For most expressions, just call the visitor. For initializer lists,
  9374. // track the index of the field being initialized since fields are
  9375. // initialized in order allowing use of previously initialized fields.
  9376. void CheckExpr(Expr *E) {
  9377. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  9378. if (!InitList) {
  9379. Visit(E);
  9380. return;
  9381. }
  9382. // Track and increment the index here.
  9383. isInitList = true;
  9384. InitFieldIndex.push_back(0);
  9385. for (auto Child : InitList->children()) {
  9386. CheckExpr(cast<Expr>(Child));
  9387. ++InitFieldIndex.back();
  9388. }
  9389. InitFieldIndex.pop_back();
  9390. }
  9391. // Returns true if MemberExpr is checked and no further checking is needed.
  9392. // Returns false if additional checking is required.
  9393. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  9394. llvm::SmallVector<FieldDecl*, 4> Fields;
  9395. Expr *Base = E;
  9396. bool ReferenceField = false;
  9397. // Get the field members used.
  9398. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9399. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  9400. if (!FD)
  9401. return false;
  9402. Fields.push_back(FD);
  9403. if (FD->getType()->isReferenceType())
  9404. ReferenceField = true;
  9405. Base = ME->getBase()->IgnoreParenImpCasts();
  9406. }
  9407. // Keep checking only if the base Decl is the same.
  9408. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  9409. if (!DRE || DRE->getDecl() != OrigDecl)
  9410. return false;
  9411. // A reference field can be bound to an unininitialized field.
  9412. if (CheckReference && !ReferenceField)
  9413. return true;
  9414. // Convert FieldDecls to their index number.
  9415. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  9416. for (const FieldDecl *I : llvm::reverse(Fields))
  9417. UsedFieldIndex.push_back(I->getFieldIndex());
  9418. // See if a warning is needed by checking the first difference in index
  9419. // numbers. If field being used has index less than the field being
  9420. // initialized, then the use is safe.
  9421. for (auto UsedIter = UsedFieldIndex.begin(),
  9422. UsedEnd = UsedFieldIndex.end(),
  9423. OrigIter = InitFieldIndex.begin(),
  9424. OrigEnd = InitFieldIndex.end();
  9425. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  9426. if (*UsedIter < *OrigIter)
  9427. return true;
  9428. if (*UsedIter > *OrigIter)
  9429. break;
  9430. }
  9431. // TODO: Add a different warning which will print the field names.
  9432. HandleDeclRefExpr(DRE);
  9433. return true;
  9434. }
  9435. // For most expressions, the cast is directly above the DeclRefExpr.
  9436. // For conditional operators, the cast can be outside the conditional
  9437. // operator if both expressions are DeclRefExpr's.
  9438. void HandleValue(Expr *E) {
  9439. E = E->IgnoreParens();
  9440. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  9441. HandleDeclRefExpr(DRE);
  9442. return;
  9443. }
  9444. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  9445. Visit(CO->getCond());
  9446. HandleValue(CO->getTrueExpr());
  9447. HandleValue(CO->getFalseExpr());
  9448. return;
  9449. }
  9450. if (BinaryConditionalOperator *BCO =
  9451. dyn_cast<BinaryConditionalOperator>(E)) {
  9452. Visit(BCO->getCond());
  9453. HandleValue(BCO->getFalseExpr());
  9454. return;
  9455. }
  9456. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  9457. HandleValue(OVE->getSourceExpr());
  9458. return;
  9459. }
  9460. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9461. if (BO->getOpcode() == BO_Comma) {
  9462. Visit(BO->getLHS());
  9463. HandleValue(BO->getRHS());
  9464. return;
  9465. }
  9466. }
  9467. if (isa<MemberExpr>(E)) {
  9468. if (isInitList) {
  9469. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  9470. false /*CheckReference*/))
  9471. return;
  9472. }
  9473. Expr *Base = E->IgnoreParenImpCasts();
  9474. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9475. // Check for static member variables and don't warn on them.
  9476. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9477. return;
  9478. Base = ME->getBase()->IgnoreParenImpCasts();
  9479. }
  9480. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  9481. HandleDeclRefExpr(DRE);
  9482. return;
  9483. }
  9484. Visit(E);
  9485. }
  9486. // Reference types not handled in HandleValue are handled here since all
  9487. // uses of references are bad, not just r-value uses.
  9488. void VisitDeclRefExpr(DeclRefExpr *E) {
  9489. if (isReferenceType)
  9490. HandleDeclRefExpr(E);
  9491. }
  9492. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  9493. if (E->getCastKind() == CK_LValueToRValue) {
  9494. HandleValue(E->getSubExpr());
  9495. return;
  9496. }
  9497. Inherited::VisitImplicitCastExpr(E);
  9498. }
  9499. void VisitMemberExpr(MemberExpr *E) {
  9500. if (isInitList) {
  9501. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  9502. return;
  9503. }
  9504. // Don't warn on arrays since they can be treated as pointers.
  9505. if (E->getType()->canDecayToPointerType()) return;
  9506. // Warn when a non-static method call is followed by non-static member
  9507. // field accesses, which is followed by a DeclRefExpr.
  9508. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  9509. bool Warn = (MD && !MD->isStatic());
  9510. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  9511. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9512. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9513. Warn = false;
  9514. Base = ME->getBase()->IgnoreParenImpCasts();
  9515. }
  9516. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  9517. if (Warn)
  9518. HandleDeclRefExpr(DRE);
  9519. return;
  9520. }
  9521. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  9522. // Visit that expression.
  9523. Visit(Base);
  9524. }
  9525. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  9526. Expr *Callee = E->getCallee();
  9527. if (isa<UnresolvedLookupExpr>(Callee))
  9528. return Inherited::VisitCXXOperatorCallExpr(E);
  9529. Visit(Callee);
  9530. for (auto Arg: E->arguments())
  9531. HandleValue(Arg->IgnoreParenImpCasts());
  9532. }
  9533. void VisitUnaryOperator(UnaryOperator *E) {
  9534. // For POD record types, addresses of its own members are well-defined.
  9535. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  9536. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  9537. if (!isPODType)
  9538. HandleValue(E->getSubExpr());
  9539. return;
  9540. }
  9541. if (E->isIncrementDecrementOp()) {
  9542. HandleValue(E->getSubExpr());
  9543. return;
  9544. }
  9545. Inherited::VisitUnaryOperator(E);
  9546. }
  9547. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  9548. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  9549. if (E->getConstructor()->isCopyConstructor()) {
  9550. Expr *ArgExpr = E->getArg(0);
  9551. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  9552. if (ILE->getNumInits() == 1)
  9553. ArgExpr = ILE->getInit(0);
  9554. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  9555. if (ICE->getCastKind() == CK_NoOp)
  9556. ArgExpr = ICE->getSubExpr();
  9557. HandleValue(ArgExpr);
  9558. return;
  9559. }
  9560. Inherited::VisitCXXConstructExpr(E);
  9561. }
  9562. void VisitCallExpr(CallExpr *E) {
  9563. // Treat std::move as a use.
  9564. if (E->isCallToStdMove()) {
  9565. HandleValue(E->getArg(0));
  9566. return;
  9567. }
  9568. Inherited::VisitCallExpr(E);
  9569. }
  9570. void VisitBinaryOperator(BinaryOperator *E) {
  9571. if (E->isCompoundAssignmentOp()) {
  9572. HandleValue(E->getLHS());
  9573. Visit(E->getRHS());
  9574. return;
  9575. }
  9576. Inherited::VisitBinaryOperator(E);
  9577. }
  9578. // A custom visitor for BinaryConditionalOperator is needed because the
  9579. // regular visitor would check the condition and true expression separately
  9580. // but both point to the same place giving duplicate diagnostics.
  9581. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  9582. Visit(E->getCond());
  9583. Visit(E->getFalseExpr());
  9584. }
  9585. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  9586. Decl* ReferenceDecl = DRE->getDecl();
  9587. if (OrigDecl != ReferenceDecl) return;
  9588. unsigned diag;
  9589. if (isReferenceType) {
  9590. diag = diag::warn_uninit_self_reference_in_reference_init;
  9591. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  9592. diag = diag::warn_static_self_reference_in_init;
  9593. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  9594. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  9595. DRE->getDecl()->getType()->isRecordType()) {
  9596. diag = diag::warn_uninit_self_reference_in_init;
  9597. } else {
  9598. // Local variables will be handled by the CFG analysis.
  9599. return;
  9600. }
  9601. S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
  9602. S.PDiag(diag)
  9603. << DRE->getDecl() << OrigDecl->getLocation()
  9604. << DRE->getSourceRange());
  9605. }
  9606. };
  9607. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  9608. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  9609. bool DirectInit) {
  9610. // Parameters arguments are occassionially constructed with itself,
  9611. // for instance, in recursive functions. Skip them.
  9612. if (isa<ParmVarDecl>(OrigDecl))
  9613. return;
  9614. E = E->IgnoreParens();
  9615. // Skip checking T a = a where T is not a record or reference type.
  9616. // Doing so is a way to silence uninitialized warnings.
  9617. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  9618. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  9619. if (ICE->getCastKind() == CK_LValueToRValue)
  9620. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  9621. if (DRE->getDecl() == OrigDecl)
  9622. return;
  9623. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  9624. }
  9625. } // end anonymous namespace
  9626. namespace {
  9627. // Simple wrapper to add the name of a variable or (if no variable is
  9628. // available) a DeclarationName into a diagnostic.
  9629. struct VarDeclOrName {
  9630. VarDecl *VDecl;
  9631. DeclarationName Name;
  9632. friend const Sema::SemaDiagnosticBuilder &
  9633. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  9634. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  9635. }
  9636. };
  9637. } // end anonymous namespace
  9638. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  9639. DeclarationName Name, QualType Type,
  9640. TypeSourceInfo *TSI,
  9641. SourceRange Range, bool DirectInit,
  9642. Expr *Init) {
  9643. bool IsInitCapture = !VDecl;
  9644. assert((!VDecl || !VDecl->isInitCapture()) &&
  9645. "init captures are expected to be deduced prior to initialization");
  9646. VarDeclOrName VN{VDecl, Name};
  9647. DeducedType *Deduced = Type->getContainedDeducedType();
  9648. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  9649. // C++11 [dcl.spec.auto]p3
  9650. if (!Init) {
  9651. assert(VDecl && "no init for init capture deduction?");
  9652. // Except for class argument deduction, and then for an initializing
  9653. // declaration only, i.e. no static at class scope or extern.
  9654. if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
  9655. VDecl->hasExternalStorage() ||
  9656. VDecl->isStaticDataMember()) {
  9657. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  9658. << VDecl->getDeclName() << Type;
  9659. return QualType();
  9660. }
  9661. }
  9662. ArrayRef<Expr*> DeduceInits;
  9663. if (Init)
  9664. DeduceInits = Init;
  9665. if (DirectInit) {
  9666. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  9667. DeduceInits = PL->exprs();
  9668. }
  9669. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  9670. assert(VDecl && "non-auto type for init capture deduction?");
  9671. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9672. InitializationKind Kind = InitializationKind::CreateForInit(
  9673. VDecl->getLocation(), DirectInit, Init);
  9674. // FIXME: Initialization should not be taking a mutable list of inits.
  9675. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  9676. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  9677. InitsCopy);
  9678. }
  9679. if (DirectInit) {
  9680. if (auto *IL = dyn_cast<InitListExpr>(Init))
  9681. DeduceInits = IL->inits();
  9682. }
  9683. // Deduction only works if we have exactly one source expression.
  9684. if (DeduceInits.empty()) {
  9685. // It isn't possible to write this directly, but it is possible to
  9686. // end up in this situation with "auto x(some_pack...);"
  9687. Diag(Init->getBeginLoc(), IsInitCapture
  9688. ? diag::err_init_capture_no_expression
  9689. : diag::err_auto_var_init_no_expression)
  9690. << VN << Type << Range;
  9691. return QualType();
  9692. }
  9693. if (DeduceInits.size() > 1) {
  9694. Diag(DeduceInits[1]->getBeginLoc(),
  9695. IsInitCapture ? diag::err_init_capture_multiple_expressions
  9696. : diag::err_auto_var_init_multiple_expressions)
  9697. << VN << Type << Range;
  9698. return QualType();
  9699. }
  9700. Expr *DeduceInit = DeduceInits[0];
  9701. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  9702. Diag(Init->getBeginLoc(), IsInitCapture
  9703. ? diag::err_init_capture_paren_braces
  9704. : diag::err_auto_var_init_paren_braces)
  9705. << isa<InitListExpr>(Init) << VN << Type << Range;
  9706. return QualType();
  9707. }
  9708. // Expressions default to 'id' when we're in a debugger.
  9709. bool DefaultedAnyToId = false;
  9710. if (getLangOpts().DebuggerCastResultToId &&
  9711. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  9712. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9713. if (Result.isInvalid()) {
  9714. return QualType();
  9715. }
  9716. Init = Result.get();
  9717. DefaultedAnyToId = true;
  9718. }
  9719. // C++ [dcl.decomp]p1:
  9720. // If the assignment-expression [...] has array type A and no ref-qualifier
  9721. // is present, e has type cv A
  9722. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  9723. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  9724. DeduceInit->getType()->isConstantArrayType())
  9725. return Context.getQualifiedType(DeduceInit->getType(),
  9726. Type.getQualifiers());
  9727. QualType DeducedType;
  9728. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  9729. if (!IsInitCapture)
  9730. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  9731. else if (isa<InitListExpr>(Init))
  9732. Diag(Range.getBegin(),
  9733. diag::err_init_capture_deduction_failure_from_init_list)
  9734. << VN
  9735. << (DeduceInit->getType().isNull() ? TSI->getType()
  9736. : DeduceInit->getType())
  9737. << DeduceInit->getSourceRange();
  9738. else
  9739. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  9740. << VN << TSI->getType()
  9741. << (DeduceInit->getType().isNull() ? TSI->getType()
  9742. : DeduceInit->getType())
  9743. << DeduceInit->getSourceRange();
  9744. }
  9745. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  9746. // 'id' instead of a specific object type prevents most of our usual
  9747. // checks.
  9748. // We only want to warn outside of template instantiations, though:
  9749. // inside a template, the 'id' could have come from a parameter.
  9750. if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
  9751. !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  9752. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  9753. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  9754. }
  9755. return DeducedType;
  9756. }
  9757. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  9758. Expr *Init) {
  9759. QualType DeducedType = deduceVarTypeFromInitializer(
  9760. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  9761. VDecl->getSourceRange(), DirectInit, Init);
  9762. if (DeducedType.isNull()) {
  9763. VDecl->setInvalidDecl();
  9764. return true;
  9765. }
  9766. VDecl->setType(DeducedType);
  9767. assert(VDecl->isLinkageValid());
  9768. // In ARC, infer lifetime.
  9769. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  9770. VDecl->setInvalidDecl();
  9771. // If this is a redeclaration, check that the type we just deduced matches
  9772. // the previously declared type.
  9773. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  9774. // We never need to merge the type, because we cannot form an incomplete
  9775. // array of auto, nor deduce such a type.
  9776. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  9777. }
  9778. // Check the deduced type is valid for a variable declaration.
  9779. CheckVariableDeclarationType(VDecl);
  9780. return VDecl->isInvalidDecl();
  9781. }
  9782. void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
  9783. SourceLocation Loc) {
  9784. if (auto *CE = dyn_cast<ConstantExpr>(Init))
  9785. Init = CE->getSubExpr();
  9786. QualType InitType = Init->getType();
  9787. assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  9788. InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
  9789. "shouldn't be called if type doesn't have a non-trivial C struct");
  9790. if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
  9791. for (auto I : ILE->inits()) {
  9792. if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
  9793. !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
  9794. continue;
  9795. SourceLocation SL = I->getExprLoc();
  9796. checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
  9797. }
  9798. return;
  9799. }
  9800. if (isa<ImplicitValueInitExpr>(Init)) {
  9801. if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  9802. checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
  9803. NTCUK_Init);
  9804. } else {
  9805. // Assume all other explicit initializers involving copying some existing
  9806. // object.
  9807. // TODO: ignore any explicit initializers where we can guarantee
  9808. // copy-elision.
  9809. if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
  9810. checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
  9811. }
  9812. }
  9813. namespace {
  9814. struct DiagNonTrivalCUnionDefaultInitializeVisitor
  9815. : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
  9816. void> {
  9817. using Super =
  9818. DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
  9819. void>;
  9820. DiagNonTrivalCUnionDefaultInitializeVisitor(
  9821. QualType OrigTy, SourceLocation OrigLoc,
  9822. Sema::NonTrivialCUnionContext UseContext, Sema &S)
  9823. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  9824. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
  9825. const FieldDecl *FD, bool InNonTrivialUnion) {
  9826. if (const auto *AT = S.Context.getAsArrayType(QT))
  9827. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  9828. InNonTrivialUnion);
  9829. return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
  9830. }
  9831. void visitARCStrong(QualType QT, const FieldDecl *FD,
  9832. bool InNonTrivialUnion) {
  9833. if (InNonTrivialUnion)
  9834. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9835. << 1 << 0 << QT << FD->getName();
  9836. }
  9837. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9838. if (InNonTrivialUnion)
  9839. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9840. << 1 << 0 << QT << FD->getName();
  9841. }
  9842. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9843. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  9844. if (RD->isUnion()) {
  9845. if (OrigLoc.isValid()) {
  9846. bool IsUnion = false;
  9847. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  9848. IsUnion = OrigRD->isUnion();
  9849. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  9850. << 0 << OrigTy << IsUnion << UseContext;
  9851. // Reset OrigLoc so that this diagnostic is emitted only once.
  9852. OrigLoc = SourceLocation();
  9853. }
  9854. InNonTrivialUnion = true;
  9855. }
  9856. if (InNonTrivialUnion)
  9857. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  9858. << 0 << 0 << QT.getUnqualifiedType() << "";
  9859. for (const FieldDecl *FD : RD->fields())
  9860. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  9861. }
  9862. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  9863. // The non-trivial C union type or the struct/union type that contains a
  9864. // non-trivial C union.
  9865. QualType OrigTy;
  9866. SourceLocation OrigLoc;
  9867. Sema::NonTrivialCUnionContext UseContext;
  9868. Sema &S;
  9869. };
  9870. struct DiagNonTrivalCUnionDestructedTypeVisitor
  9871. : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
  9872. using Super =
  9873. DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
  9874. DiagNonTrivalCUnionDestructedTypeVisitor(
  9875. QualType OrigTy, SourceLocation OrigLoc,
  9876. Sema::NonTrivialCUnionContext UseContext, Sema &S)
  9877. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  9878. void visitWithKind(QualType::DestructionKind DK, QualType QT,
  9879. const FieldDecl *FD, bool InNonTrivialUnion) {
  9880. if (const auto *AT = S.Context.getAsArrayType(QT))
  9881. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  9882. InNonTrivialUnion);
  9883. return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
  9884. }
  9885. void visitARCStrong(QualType QT, const FieldDecl *FD,
  9886. bool InNonTrivialUnion) {
  9887. if (InNonTrivialUnion)
  9888. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9889. << 1 << 1 << QT << FD->getName();
  9890. }
  9891. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9892. if (InNonTrivialUnion)
  9893. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9894. << 1 << 1 << QT << FD->getName();
  9895. }
  9896. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9897. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  9898. if (RD->isUnion()) {
  9899. if (OrigLoc.isValid()) {
  9900. bool IsUnion = false;
  9901. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  9902. IsUnion = OrigRD->isUnion();
  9903. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  9904. << 1 << OrigTy << IsUnion << UseContext;
  9905. // Reset OrigLoc so that this diagnostic is emitted only once.
  9906. OrigLoc = SourceLocation();
  9907. }
  9908. InNonTrivialUnion = true;
  9909. }
  9910. if (InNonTrivialUnion)
  9911. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  9912. << 0 << 1 << QT.getUnqualifiedType() << "";
  9913. for (const FieldDecl *FD : RD->fields())
  9914. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  9915. }
  9916. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  9917. void visitCXXDestructor(QualType QT, const FieldDecl *FD,
  9918. bool InNonTrivialUnion) {}
  9919. // The non-trivial C union type or the struct/union type that contains a
  9920. // non-trivial C union.
  9921. QualType OrigTy;
  9922. SourceLocation OrigLoc;
  9923. Sema::NonTrivialCUnionContext UseContext;
  9924. Sema &S;
  9925. };
  9926. struct DiagNonTrivalCUnionCopyVisitor
  9927. : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
  9928. using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
  9929. DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
  9930. Sema::NonTrivialCUnionContext UseContext,
  9931. Sema &S)
  9932. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  9933. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
  9934. const FieldDecl *FD, bool InNonTrivialUnion) {
  9935. if (const auto *AT = S.Context.getAsArrayType(QT))
  9936. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  9937. InNonTrivialUnion);
  9938. return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
  9939. }
  9940. void visitARCStrong(QualType QT, const FieldDecl *FD,
  9941. bool InNonTrivialUnion) {
  9942. if (InNonTrivialUnion)
  9943. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9944. << 1 << 2 << QT << FD->getName();
  9945. }
  9946. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9947. if (InNonTrivialUnion)
  9948. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9949. << 1 << 2 << QT << FD->getName();
  9950. }
  9951. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9952. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  9953. if (RD->isUnion()) {
  9954. if (OrigLoc.isValid()) {
  9955. bool IsUnion = false;
  9956. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  9957. IsUnion = OrigRD->isUnion();
  9958. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  9959. << 2 << OrigTy << IsUnion << UseContext;
  9960. // Reset OrigLoc so that this diagnostic is emitted only once.
  9961. OrigLoc = SourceLocation();
  9962. }
  9963. InNonTrivialUnion = true;
  9964. }
  9965. if (InNonTrivialUnion)
  9966. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  9967. << 0 << 2 << QT.getUnqualifiedType() << "";
  9968. for (const FieldDecl *FD : RD->fields())
  9969. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  9970. }
  9971. void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
  9972. const FieldDecl *FD, bool InNonTrivialUnion) {}
  9973. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  9974. void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
  9975. bool InNonTrivialUnion) {}
  9976. // The non-trivial C union type or the struct/union type that contains a
  9977. // non-trivial C union.
  9978. QualType OrigTy;
  9979. SourceLocation OrigLoc;
  9980. Sema::NonTrivialCUnionContext UseContext;
  9981. Sema &S;
  9982. };
  9983. } // namespace
  9984. void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
  9985. NonTrivialCUnionContext UseContext,
  9986. unsigned NonTrivialKind) {
  9987. assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  9988. QT.hasNonTrivialToPrimitiveDestructCUnion() ||
  9989. QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
  9990. "shouldn't be called if type doesn't have a non-trivial C union");
  9991. if ((NonTrivialKind & NTCUK_Init) &&
  9992. QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  9993. DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
  9994. .visit(QT, nullptr, false);
  9995. if ((NonTrivialKind & NTCUK_Destruct) &&
  9996. QT.hasNonTrivialToPrimitiveDestructCUnion())
  9997. DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
  9998. .visit(QT, nullptr, false);
  9999. if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
  10000. DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
  10001. .visit(QT, nullptr, false);
  10002. }
  10003. /// AddInitializerToDecl - Adds the initializer Init to the
  10004. /// declaration dcl. If DirectInit is true, this is C++ direct
  10005. /// initialization rather than copy initialization.
  10006. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  10007. // If there is no declaration, there was an error parsing it. Just ignore
  10008. // the initializer.
  10009. if (!RealDecl || RealDecl->isInvalidDecl()) {
  10010. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  10011. return;
  10012. }
  10013. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  10014. // Pure-specifiers are handled in ActOnPureSpecifier.
  10015. Diag(Method->getLocation(), diag::err_member_function_initialization)
  10016. << Method->getDeclName() << Init->getSourceRange();
  10017. Method->setInvalidDecl();
  10018. return;
  10019. }
  10020. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  10021. if (!VDecl) {
  10022. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  10023. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  10024. RealDecl->setInvalidDecl();
  10025. return;
  10026. }
  10027. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  10028. if (VDecl->getType()->isUndeducedType()) {
  10029. // Attempt typo correction early so that the type of the init expression can
  10030. // be deduced based on the chosen correction if the original init contains a
  10031. // TypoExpr.
  10032. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  10033. if (!Res.isUsable()) {
  10034. RealDecl->setInvalidDecl();
  10035. return;
  10036. }
  10037. Init = Res.get();
  10038. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  10039. return;
  10040. }
  10041. // dllimport cannot be used on variable definitions.
  10042. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  10043. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  10044. VDecl->setInvalidDecl();
  10045. return;
  10046. }
  10047. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  10048. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  10049. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  10050. VDecl->setInvalidDecl();
  10051. return;
  10052. }
  10053. if (!VDecl->getType()->isDependentType()) {
  10054. // A definition must end up with a complete type, which means it must be
  10055. // complete with the restriction that an array type might be completed by
  10056. // the initializer; note that later code assumes this restriction.
  10057. QualType BaseDeclType = VDecl->getType();
  10058. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  10059. BaseDeclType = Array->getElementType();
  10060. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  10061. diag::err_typecheck_decl_incomplete_type)) {
  10062. RealDecl->setInvalidDecl();
  10063. return;
  10064. }
  10065. // The variable can not have an abstract class type.
  10066. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  10067. diag::err_abstract_type_in_decl,
  10068. AbstractVariableType))
  10069. VDecl->setInvalidDecl();
  10070. }
  10071. // If adding the initializer will turn this declaration into a definition,
  10072. // and we already have a definition for this variable, diagnose or otherwise
  10073. // handle the situation.
  10074. VarDecl *Def;
  10075. if ((Def = VDecl->getDefinition()) && Def != VDecl &&
  10076. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  10077. !VDecl->isThisDeclarationADemotedDefinition() &&
  10078. checkVarDeclRedefinition(Def, VDecl))
  10079. return;
  10080. if (getLangOpts().CPlusPlus) {
  10081. // C++ [class.static.data]p4
  10082. // If a static data member is of const integral or const
  10083. // enumeration type, its declaration in the class definition can
  10084. // specify a constant-initializer which shall be an integral
  10085. // constant expression (5.19). In that case, the member can appear
  10086. // in integral constant expressions. The member shall still be
  10087. // defined in a namespace scope if it is used in the program and the
  10088. // namespace scope definition shall not contain an initializer.
  10089. //
  10090. // We already performed a redefinition check above, but for static
  10091. // data members we also need to check whether there was an in-class
  10092. // declaration with an initializer.
  10093. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  10094. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  10095. << VDecl->getDeclName();
  10096. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  10097. diag::note_previous_initializer)
  10098. << 0;
  10099. return;
  10100. }
  10101. if (VDecl->hasLocalStorage())
  10102. setFunctionHasBranchProtectedScope();
  10103. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  10104. VDecl->setInvalidDecl();
  10105. return;
  10106. }
  10107. }
  10108. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  10109. // a kernel function cannot be initialized."
  10110. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  10111. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  10112. VDecl->setInvalidDecl();
  10113. return;
  10114. }
  10115. // Get the decls type and save a reference for later, since
  10116. // CheckInitializerTypes may change it.
  10117. QualType DclT = VDecl->getType(), SavT = DclT;
  10118. // Expressions default to 'id' when we're in a debugger
  10119. // and we are assigning it to a variable of Objective-C pointer type.
  10120. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  10121. Init->getType() == Context.UnknownAnyTy) {
  10122. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  10123. if (Result.isInvalid()) {
  10124. VDecl->setInvalidDecl();
  10125. return;
  10126. }
  10127. Init = Result.get();
  10128. }
  10129. // Perform the initialization.
  10130. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  10131. if (!VDecl->isInvalidDecl()) {
  10132. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  10133. InitializationKind Kind = InitializationKind::CreateForInit(
  10134. VDecl->getLocation(), DirectInit, Init);
  10135. MultiExprArg Args = Init;
  10136. if (CXXDirectInit)
  10137. Args = MultiExprArg(CXXDirectInit->getExprs(),
  10138. CXXDirectInit->getNumExprs());
  10139. // Try to correct any TypoExprs in the initialization arguments.
  10140. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  10141. ExprResult Res = CorrectDelayedTyposInExpr(
  10142. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  10143. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  10144. return Init.Failed() ? ExprError() : E;
  10145. });
  10146. if (Res.isInvalid()) {
  10147. VDecl->setInvalidDecl();
  10148. } else if (Res.get() != Args[Idx]) {
  10149. Args[Idx] = Res.get();
  10150. }
  10151. }
  10152. if (VDecl->isInvalidDecl())
  10153. return;
  10154. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  10155. /*TopLevelOfInitList=*/false,
  10156. /*TreatUnavailableAsInvalid=*/false);
  10157. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  10158. if (Result.isInvalid()) {
  10159. VDecl->setInvalidDecl();
  10160. return;
  10161. }
  10162. Init = Result.getAs<Expr>();
  10163. }
  10164. // Check for self-references within variable initializers.
  10165. // Variables declared within a function/method body (except for references)
  10166. // are handled by a dataflow analysis.
  10167. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  10168. VDecl->getType()->isReferenceType()) {
  10169. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  10170. }
  10171. // If the type changed, it means we had an incomplete type that was
  10172. // completed by the initializer. For example:
  10173. // int ary[] = { 1, 3, 5 };
  10174. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  10175. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  10176. VDecl->setType(DclT);
  10177. if (!VDecl->isInvalidDecl()) {
  10178. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  10179. if (VDecl->hasAttr<BlocksAttr>())
  10180. checkRetainCycles(VDecl, Init);
  10181. // It is safe to assign a weak reference into a strong variable.
  10182. // Although this code can still have problems:
  10183. // id x = self.weakProp;
  10184. // id y = self.weakProp;
  10185. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  10186. // paths through the function. This should be revisited if
  10187. // -Wrepeated-use-of-weak is made flow-sensitive.
  10188. if (FunctionScopeInfo *FSI = getCurFunction())
  10189. if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
  10190. VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
  10191. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  10192. Init->getBeginLoc()))
  10193. FSI->markSafeWeakUse(Init);
  10194. }
  10195. // The initialization is usually a full-expression.
  10196. //
  10197. // FIXME: If this is a braced initialization of an aggregate, it is not
  10198. // an expression, and each individual field initializer is a separate
  10199. // full-expression. For instance, in:
  10200. //
  10201. // struct Temp { ~Temp(); };
  10202. // struct S { S(Temp); };
  10203. // struct T { S a, b; } t = { Temp(), Temp() }
  10204. //
  10205. // we should destroy the first Temp before constructing the second.
  10206. ExprResult Result =
  10207. ActOnFinishFullExpr(Init, VDecl->getLocation(),
  10208. /*DiscardedValue*/ false, VDecl->isConstexpr());
  10209. if (Result.isInvalid()) {
  10210. VDecl->setInvalidDecl();
  10211. return;
  10212. }
  10213. Init = Result.get();
  10214. // Attach the initializer to the decl.
  10215. VDecl->setInit(Init);
  10216. if (VDecl->isLocalVarDecl()) {
  10217. // Don't check the initializer if the declaration is malformed.
  10218. if (VDecl->isInvalidDecl()) {
  10219. // do nothing
  10220. // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
  10221. // This is true even in OpenCL C++.
  10222. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
  10223. CheckForConstantInitializer(Init, DclT);
  10224. // Otherwise, C++ does not restrict the initializer.
  10225. } else if (getLangOpts().CPlusPlus) {
  10226. // do nothing
  10227. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  10228. // static storage duration shall be constant expressions or string literals.
  10229. } else if (VDecl->getStorageClass() == SC_Static) {
  10230. CheckForConstantInitializer(Init, DclT);
  10231. // C89 is stricter than C99 for aggregate initializers.
  10232. // C89 6.5.7p3: All the expressions [...] in an initializer list
  10233. // for an object that has aggregate or union type shall be
  10234. // constant expressions.
  10235. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  10236. isa<InitListExpr>(Init)) {
  10237. const Expr *Culprit;
  10238. if (!Init->isConstantInitializer(Context, false, &Culprit)) {
  10239. Diag(Culprit->getExprLoc(),
  10240. diag::ext_aggregate_init_not_constant)
  10241. << Culprit->getSourceRange();
  10242. }
  10243. }
  10244. if (auto *E = dyn_cast<ExprWithCleanups>(Init))
  10245. if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
  10246. if (VDecl->hasLocalStorage())
  10247. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  10248. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  10249. VDecl->getLexicalDeclContext()->isRecord()) {
  10250. // This is an in-class initialization for a static data member, e.g.,
  10251. //
  10252. // struct S {
  10253. // static const int value = 17;
  10254. // };
  10255. // C++ [class.mem]p4:
  10256. // A member-declarator can contain a constant-initializer only
  10257. // if it declares a static member (9.4) of const integral or
  10258. // const enumeration type, see 9.4.2.
  10259. //
  10260. // C++11 [class.static.data]p3:
  10261. // If a non-volatile non-inline const static data member is of integral
  10262. // or enumeration type, its declaration in the class definition can
  10263. // specify a brace-or-equal-initializer in which every initializer-clause
  10264. // that is an assignment-expression is a constant expression. A static
  10265. // data member of literal type can be declared in the class definition
  10266. // with the constexpr specifier; if so, its declaration shall specify a
  10267. // brace-or-equal-initializer in which every initializer-clause that is
  10268. // an assignment-expression is a constant expression.
  10269. // Do nothing on dependent types.
  10270. if (DclT->isDependentType()) {
  10271. // Allow any 'static constexpr' members, whether or not they are of literal
  10272. // type. We separately check that every constexpr variable is of literal
  10273. // type.
  10274. } else if (VDecl->isConstexpr()) {
  10275. // Require constness.
  10276. } else if (!DclT.isConstQualified()) {
  10277. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  10278. << Init->getSourceRange();
  10279. VDecl->setInvalidDecl();
  10280. // We allow integer constant expressions in all cases.
  10281. } else if (DclT->isIntegralOrEnumerationType()) {
  10282. // Check whether the expression is a constant expression.
  10283. SourceLocation Loc;
  10284. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  10285. // In C++11, a non-constexpr const static data member with an
  10286. // in-class initializer cannot be volatile.
  10287. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  10288. else if (Init->isValueDependent())
  10289. ; // Nothing to check.
  10290. else if (Init->isIntegerConstantExpr(Context, &Loc))
  10291. ; // Ok, it's an ICE!
  10292. else if (Init->getType()->isScopedEnumeralType() &&
  10293. Init->isCXX11ConstantExpr(Context))
  10294. ; // Ok, it is a scoped-enum constant expression.
  10295. else if (Init->isEvaluatable(Context)) {
  10296. // If we can constant fold the initializer through heroics, accept it,
  10297. // but report this as a use of an extension for -pedantic.
  10298. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  10299. << Init->getSourceRange();
  10300. } else {
  10301. // Otherwise, this is some crazy unknown case. Report the issue at the
  10302. // location provided by the isIntegerConstantExpr failed check.
  10303. Diag(Loc, diag::err_in_class_initializer_non_constant)
  10304. << Init->getSourceRange();
  10305. VDecl->setInvalidDecl();
  10306. }
  10307. // We allow foldable floating-point constants as an extension.
  10308. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  10309. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  10310. // it anyway and provide a fixit to add the 'constexpr'.
  10311. if (getLangOpts().CPlusPlus11) {
  10312. Diag(VDecl->getLocation(),
  10313. diag::ext_in_class_initializer_float_type_cxx11)
  10314. << DclT << Init->getSourceRange();
  10315. Diag(VDecl->getBeginLoc(),
  10316. diag::note_in_class_initializer_float_type_cxx11)
  10317. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10318. } else {
  10319. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  10320. << DclT << Init->getSourceRange();
  10321. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  10322. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  10323. << Init->getSourceRange();
  10324. VDecl->setInvalidDecl();
  10325. }
  10326. }
  10327. // Suggest adding 'constexpr' in C++11 for literal types.
  10328. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  10329. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  10330. << DclT << Init->getSourceRange()
  10331. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10332. VDecl->setConstexpr(true);
  10333. } else {
  10334. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  10335. << DclT << Init->getSourceRange();
  10336. VDecl->setInvalidDecl();
  10337. }
  10338. } else if (VDecl->isFileVarDecl()) {
  10339. // In C, extern is typically used to avoid tentative definitions when
  10340. // declaring variables in headers, but adding an intializer makes it a
  10341. // definition. This is somewhat confusing, so GCC and Clang both warn on it.
  10342. // In C++, extern is often used to give implictly static const variables
  10343. // external linkage, so don't warn in that case. If selectany is present,
  10344. // this might be header code intended for C and C++ inclusion, so apply the
  10345. // C++ rules.
  10346. if (VDecl->getStorageClass() == SC_Extern &&
  10347. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  10348. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  10349. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  10350. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  10351. Diag(VDecl->getLocation(), diag::warn_extern_init);
  10352. // In Microsoft C++ mode, a const variable defined in namespace scope has
  10353. // external linkage by default if the variable is declared with
  10354. // __declspec(dllexport).
  10355. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  10356. getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
  10357. VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
  10358. VDecl->setStorageClass(SC_Extern);
  10359. // C99 6.7.8p4. All file scoped initializers need to be constant.
  10360. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  10361. CheckForConstantInitializer(Init, DclT);
  10362. }
  10363. QualType InitType = Init->getType();
  10364. if (!InitType.isNull() &&
  10365. (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  10366. InitType.hasNonTrivialToPrimitiveCopyCUnion()))
  10367. checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
  10368. // We will represent direct-initialization similarly to copy-initialization:
  10369. // int x(1); -as-> int x = 1;
  10370. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  10371. //
  10372. // Clients that want to distinguish between the two forms, can check for
  10373. // direct initializer using VarDecl::getInitStyle().
  10374. // A major benefit is that clients that don't particularly care about which
  10375. // exactly form was it (like the CodeGen) can handle both cases without
  10376. // special case code.
  10377. // C++ 8.5p11:
  10378. // The form of initialization (using parentheses or '=') is generally
  10379. // insignificant, but does matter when the entity being initialized has a
  10380. // class type.
  10381. if (CXXDirectInit) {
  10382. assert(DirectInit && "Call-style initializer must be direct init.");
  10383. VDecl->setInitStyle(VarDecl::CallInit);
  10384. } else if (DirectInit) {
  10385. // This must be list-initialization. No other way is direct-initialization.
  10386. VDecl->setInitStyle(VarDecl::ListInit);
  10387. }
  10388. CheckCompleteVariableDeclaration(VDecl);
  10389. }
  10390. /// ActOnInitializerError - Given that there was an error parsing an
  10391. /// initializer for the given declaration, try to return to some form
  10392. /// of sanity.
  10393. void Sema::ActOnInitializerError(Decl *D) {
  10394. // Our main concern here is re-establishing invariants like "a
  10395. // variable's type is either dependent or complete".
  10396. if (!D || D->isInvalidDecl()) return;
  10397. VarDecl *VD = dyn_cast<VarDecl>(D);
  10398. if (!VD) return;
  10399. // Bindings are not usable if we can't make sense of the initializer.
  10400. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  10401. for (auto *BD : DD->bindings())
  10402. BD->setInvalidDecl();
  10403. // Auto types are meaningless if we can't make sense of the initializer.
  10404. if (ParsingInitForAutoVars.count(D)) {
  10405. D->setInvalidDecl();
  10406. return;
  10407. }
  10408. QualType Ty = VD->getType();
  10409. if (Ty->isDependentType()) return;
  10410. // Require a complete type.
  10411. if (RequireCompleteType(VD->getLocation(),
  10412. Context.getBaseElementType(Ty),
  10413. diag::err_typecheck_decl_incomplete_type)) {
  10414. VD->setInvalidDecl();
  10415. return;
  10416. }
  10417. // Require a non-abstract type.
  10418. if (RequireNonAbstractType(VD->getLocation(), Ty,
  10419. diag::err_abstract_type_in_decl,
  10420. AbstractVariableType)) {
  10421. VD->setInvalidDecl();
  10422. return;
  10423. }
  10424. // Don't bother complaining about constructors or destructors,
  10425. // though.
  10426. }
  10427. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  10428. // If there is no declaration, there was an error parsing it. Just ignore it.
  10429. if (!RealDecl)
  10430. return;
  10431. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  10432. QualType Type = Var->getType();
  10433. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  10434. if (isa<DecompositionDecl>(RealDecl)) {
  10435. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  10436. Var->setInvalidDecl();
  10437. return;
  10438. }
  10439. if (Type->isUndeducedType() &&
  10440. DeduceVariableDeclarationType(Var, false, nullptr))
  10441. return;
  10442. // C++11 [class.static.data]p3: A static data member can be declared with
  10443. // the constexpr specifier; if so, its declaration shall specify
  10444. // a brace-or-equal-initializer.
  10445. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  10446. // the definition of a variable [...] or the declaration of a static data
  10447. // member.
  10448. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  10449. !Var->isThisDeclarationADemotedDefinition()) {
  10450. if (Var->isStaticDataMember()) {
  10451. // C++1z removes the relevant rule; the in-class declaration is always
  10452. // a definition there.
  10453. if (!getLangOpts().CPlusPlus17) {
  10454. Diag(Var->getLocation(),
  10455. diag::err_constexpr_static_mem_var_requires_init)
  10456. << Var->getDeclName();
  10457. Var->setInvalidDecl();
  10458. return;
  10459. }
  10460. } else {
  10461. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  10462. Var->setInvalidDecl();
  10463. return;
  10464. }
  10465. }
  10466. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  10467. // be initialized.
  10468. if (!Var->isInvalidDecl() &&
  10469. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  10470. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  10471. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  10472. Var->setInvalidDecl();
  10473. return;
  10474. }
  10475. VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
  10476. if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
  10477. Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  10478. checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
  10479. NTCUC_DefaultInitializedObject, NTCUK_Init);
  10480. switch (DefKind) {
  10481. case VarDecl::Definition:
  10482. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  10483. break;
  10484. // We have an out-of-line definition of a static data member
  10485. // that has an in-class initializer, so we type-check this like
  10486. // a declaration.
  10487. //
  10488. LLVM_FALLTHROUGH;
  10489. case VarDecl::DeclarationOnly:
  10490. // It's only a declaration.
  10491. // Block scope. C99 6.7p7: If an identifier for an object is
  10492. // declared with no linkage (C99 6.2.2p6), the type for the
  10493. // object shall be complete.
  10494. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  10495. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  10496. RequireCompleteType(Var->getLocation(), Type,
  10497. diag::err_typecheck_decl_incomplete_type))
  10498. Var->setInvalidDecl();
  10499. // Make sure that the type is not abstract.
  10500. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10501. RequireNonAbstractType(Var->getLocation(), Type,
  10502. diag::err_abstract_type_in_decl,
  10503. AbstractVariableType))
  10504. Var->setInvalidDecl();
  10505. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10506. Var->getStorageClass() == SC_PrivateExtern) {
  10507. Diag(Var->getLocation(), diag::warn_private_extern);
  10508. Diag(Var->getLocation(), diag::note_private_extern);
  10509. }
  10510. return;
  10511. case VarDecl::TentativeDefinition:
  10512. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  10513. // object that has file scope without an initializer, and without a
  10514. // storage-class specifier or with the storage-class specifier "static",
  10515. // constitutes a tentative definition. Note: A tentative definition with
  10516. // external linkage is valid (C99 6.2.2p5).
  10517. if (!Var->isInvalidDecl()) {
  10518. if (const IncompleteArrayType *ArrayT
  10519. = Context.getAsIncompleteArrayType(Type)) {
  10520. if (RequireCompleteType(Var->getLocation(),
  10521. ArrayT->getElementType(),
  10522. diag::err_illegal_decl_array_incomplete_type))
  10523. Var->setInvalidDecl();
  10524. } else if (Var->getStorageClass() == SC_Static) {
  10525. // C99 6.9.2p3: If the declaration of an identifier for an object is
  10526. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  10527. // declared type shall not be an incomplete type.
  10528. // NOTE: code such as the following
  10529. // static struct s;
  10530. // struct s { int a; };
  10531. // is accepted by gcc. Hence here we issue a warning instead of
  10532. // an error and we do not invalidate the static declaration.
  10533. // NOTE: to avoid multiple warnings, only check the first declaration.
  10534. if (Var->isFirstDecl())
  10535. RequireCompleteType(Var->getLocation(), Type,
  10536. diag::ext_typecheck_decl_incomplete_type);
  10537. }
  10538. }
  10539. // Record the tentative definition; we're done.
  10540. if (!Var->isInvalidDecl())
  10541. TentativeDefinitions.push_back(Var);
  10542. return;
  10543. }
  10544. // Provide a specific diagnostic for uninitialized variable
  10545. // definitions with incomplete array type.
  10546. if (Type->isIncompleteArrayType()) {
  10547. Diag(Var->getLocation(),
  10548. diag::err_typecheck_incomplete_array_needs_initializer);
  10549. Var->setInvalidDecl();
  10550. return;
  10551. }
  10552. // Provide a specific diagnostic for uninitialized variable
  10553. // definitions with reference type.
  10554. if (Type->isReferenceType()) {
  10555. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  10556. << Var->getDeclName()
  10557. << SourceRange(Var->getLocation(), Var->getLocation());
  10558. Var->setInvalidDecl();
  10559. return;
  10560. }
  10561. // Do not attempt to type-check the default initializer for a
  10562. // variable with dependent type.
  10563. if (Type->isDependentType())
  10564. return;
  10565. if (Var->isInvalidDecl())
  10566. return;
  10567. if (!Var->hasAttr<AliasAttr>()) {
  10568. if (RequireCompleteType(Var->getLocation(),
  10569. Context.getBaseElementType(Type),
  10570. diag::err_typecheck_decl_incomplete_type)) {
  10571. Var->setInvalidDecl();
  10572. return;
  10573. }
  10574. } else {
  10575. return;
  10576. }
  10577. // The variable can not have an abstract class type.
  10578. if (RequireNonAbstractType(Var->getLocation(), Type,
  10579. diag::err_abstract_type_in_decl,
  10580. AbstractVariableType)) {
  10581. Var->setInvalidDecl();
  10582. return;
  10583. }
  10584. // Check for jumps past the implicit initializer. C++0x
  10585. // clarifies that this applies to a "variable with automatic
  10586. // storage duration", not a "local variable".
  10587. // C++11 [stmt.dcl]p3
  10588. // A program that jumps from a point where a variable with automatic
  10589. // storage duration is not in scope to a point where it is in scope is
  10590. // ill-formed unless the variable has scalar type, class type with a
  10591. // trivial default constructor and a trivial destructor, a cv-qualified
  10592. // version of one of these types, or an array of one of the preceding
  10593. // types and is declared without an initializer.
  10594. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  10595. if (const RecordType *Record
  10596. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  10597. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  10598. // Mark the function (if we're in one) for further checking even if the
  10599. // looser rules of C++11 do not require such checks, so that we can
  10600. // diagnose incompatibilities with C++98.
  10601. if (!CXXRecord->isPOD())
  10602. setFunctionHasBranchProtectedScope();
  10603. }
  10604. }
  10605. // In OpenCL, we can't initialize objects in the __local address space,
  10606. // even implicitly, so don't synthesize an implicit initializer.
  10607. if (getLangOpts().OpenCL &&
  10608. Var->getType().getAddressSpace() == LangAS::opencl_local)
  10609. return;
  10610. // C++03 [dcl.init]p9:
  10611. // If no initializer is specified for an object, and the
  10612. // object is of (possibly cv-qualified) non-POD class type (or
  10613. // array thereof), the object shall be default-initialized; if
  10614. // the object is of const-qualified type, the underlying class
  10615. // type shall have a user-declared default
  10616. // constructor. Otherwise, if no initializer is specified for
  10617. // a non- static object, the object and its subobjects, if
  10618. // any, have an indeterminate initial value); if the object
  10619. // or any of its subobjects are of const-qualified type, the
  10620. // program is ill-formed.
  10621. // C++0x [dcl.init]p11:
  10622. // If no initializer is specified for an object, the object is
  10623. // default-initialized; [...].
  10624. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  10625. InitializationKind Kind
  10626. = InitializationKind::CreateDefault(Var->getLocation());
  10627. InitializationSequence InitSeq(*this, Entity, Kind, None);
  10628. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  10629. if (Init.isInvalid())
  10630. Var->setInvalidDecl();
  10631. else if (Init.get()) {
  10632. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  10633. // This is important for template substitution.
  10634. Var->setInitStyle(VarDecl::CallInit);
  10635. }
  10636. CheckCompleteVariableDeclaration(Var);
  10637. }
  10638. }
  10639. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  10640. // If there is no declaration, there was an error parsing it. Ignore it.
  10641. if (!D)
  10642. return;
  10643. VarDecl *VD = dyn_cast<VarDecl>(D);
  10644. if (!VD) {
  10645. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  10646. D->setInvalidDecl();
  10647. return;
  10648. }
  10649. VD->setCXXForRangeDecl(true);
  10650. // for-range-declaration cannot be given a storage class specifier.
  10651. int Error = -1;
  10652. switch (VD->getStorageClass()) {
  10653. case SC_None:
  10654. break;
  10655. case SC_Extern:
  10656. Error = 0;
  10657. break;
  10658. case SC_Static:
  10659. Error = 1;
  10660. break;
  10661. case SC_PrivateExtern:
  10662. Error = 2;
  10663. break;
  10664. case SC_Auto:
  10665. Error = 3;
  10666. break;
  10667. case SC_Register:
  10668. Error = 4;
  10669. break;
  10670. }
  10671. if (Error != -1) {
  10672. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  10673. << VD->getDeclName() << Error;
  10674. D->setInvalidDecl();
  10675. }
  10676. }
  10677. StmtResult
  10678. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  10679. IdentifierInfo *Ident,
  10680. ParsedAttributes &Attrs,
  10681. SourceLocation AttrEnd) {
  10682. // C++1y [stmt.iter]p1:
  10683. // A range-based for statement of the form
  10684. // for ( for-range-identifier : for-range-initializer ) statement
  10685. // is equivalent to
  10686. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  10687. DeclSpec DS(Attrs.getPool().getFactory());
  10688. const char *PrevSpec;
  10689. unsigned DiagID;
  10690. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  10691. getPrintingPolicy());
  10692. Declarator D(DS, DeclaratorContext::ForContext);
  10693. D.SetIdentifier(Ident, IdentLoc);
  10694. D.takeAttributes(Attrs, AttrEnd);
  10695. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
  10696. IdentLoc);
  10697. Decl *Var = ActOnDeclarator(S, D);
  10698. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  10699. FinalizeDeclaration(Var);
  10700. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  10701. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  10702. }
  10703. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  10704. if (var->isInvalidDecl()) return;
  10705. if (getLangOpts().OpenCL) {
  10706. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  10707. // initialiser
  10708. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  10709. !var->hasInit()) {
  10710. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  10711. << 1 /*Init*/;
  10712. var->setInvalidDecl();
  10713. return;
  10714. }
  10715. }
  10716. // In Objective-C, don't allow jumps past the implicit initialization of a
  10717. // local retaining variable.
  10718. if (getLangOpts().ObjC &&
  10719. var->hasLocalStorage()) {
  10720. switch (var->getType().getObjCLifetime()) {
  10721. case Qualifiers::OCL_None:
  10722. case Qualifiers::OCL_ExplicitNone:
  10723. case Qualifiers::OCL_Autoreleasing:
  10724. break;
  10725. case Qualifiers::OCL_Weak:
  10726. case Qualifiers::OCL_Strong:
  10727. setFunctionHasBranchProtectedScope();
  10728. break;
  10729. }
  10730. }
  10731. if (var->hasLocalStorage() &&
  10732. var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  10733. setFunctionHasBranchProtectedScope();
  10734. // Warn about externally-visible variables being defined without a
  10735. // prior declaration. We only want to do this for global
  10736. // declarations, but we also specifically need to avoid doing it for
  10737. // class members because the linkage of an anonymous class can
  10738. // change if it's later given a typedef name.
  10739. if (var->isThisDeclarationADefinition() &&
  10740. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  10741. var->isExternallyVisible() && var->hasLinkage() &&
  10742. !var->isInline() && !var->getDescribedVarTemplate() &&
  10743. !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
  10744. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  10745. var->getLocation())) {
  10746. // Find a previous declaration that's not a definition.
  10747. VarDecl *prev = var->getPreviousDecl();
  10748. while (prev && prev->isThisDeclarationADefinition())
  10749. prev = prev->getPreviousDecl();
  10750. if (!prev) {
  10751. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  10752. Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
  10753. << /* variable */ 0;
  10754. }
  10755. }
  10756. // Cache the result of checking for constant initialization.
  10757. Optional<bool> CacheHasConstInit;
  10758. const Expr *CacheCulprit = nullptr;
  10759. auto checkConstInit = [&]() mutable {
  10760. if (!CacheHasConstInit)
  10761. CacheHasConstInit = var->getInit()->isConstantInitializer(
  10762. Context, var->getType()->isReferenceType(), &CacheCulprit);
  10763. return *CacheHasConstInit;
  10764. };
  10765. if (var->getTLSKind() == VarDecl::TLS_Static) {
  10766. if (var->getType().isDestructedType()) {
  10767. // GNU C++98 edits for __thread, [basic.start.term]p3:
  10768. // The type of an object with thread storage duration shall not
  10769. // have a non-trivial destructor.
  10770. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  10771. if (getLangOpts().CPlusPlus11)
  10772. Diag(var->getLocation(), diag::note_use_thread_local);
  10773. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  10774. if (!checkConstInit()) {
  10775. // GNU C++98 edits for __thread, [basic.start.init]p4:
  10776. // An object of thread storage duration shall not require dynamic
  10777. // initialization.
  10778. // FIXME: Need strict checking here.
  10779. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  10780. << CacheCulprit->getSourceRange();
  10781. if (getLangOpts().CPlusPlus11)
  10782. Diag(var->getLocation(), diag::note_use_thread_local);
  10783. }
  10784. }
  10785. }
  10786. // Apply section attributes and pragmas to global variables.
  10787. bool GlobalStorage = var->hasGlobalStorage();
  10788. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  10789. !inTemplateInstantiation()) {
  10790. PragmaStack<StringLiteral *> *Stack = nullptr;
  10791. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  10792. if (var->getType().isConstQualified())
  10793. Stack = &ConstSegStack;
  10794. else if (!var->getInit()) {
  10795. Stack = &BSSSegStack;
  10796. SectionFlags |= ASTContext::PSF_Write;
  10797. } else {
  10798. Stack = &DataSegStack;
  10799. SectionFlags |= ASTContext::PSF_Write;
  10800. }
  10801. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  10802. var->addAttr(SectionAttr::CreateImplicit(
  10803. Context, SectionAttr::Declspec_allocate,
  10804. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  10805. }
  10806. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  10807. if (UnifySection(SA->getName(), SectionFlags, var))
  10808. var->dropAttr<SectionAttr>();
  10809. // Apply the init_seg attribute if this has an initializer. If the
  10810. // initializer turns out to not be dynamic, we'll end up ignoring this
  10811. // attribute.
  10812. if (CurInitSeg && var->getInit())
  10813. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  10814. CurInitSegLoc));
  10815. }
  10816. // All the following checks are C++ only.
  10817. if (!getLangOpts().CPlusPlus) {
  10818. // If this variable must be emitted, add it as an initializer for the
  10819. // current module.
  10820. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10821. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10822. return;
  10823. }
  10824. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  10825. CheckCompleteDecompositionDeclaration(DD);
  10826. QualType type = var->getType();
  10827. if (type->isDependentType()) return;
  10828. if (var->hasAttr<BlocksAttr>())
  10829. getCurFunction()->addByrefBlockVar(var);
  10830. Expr *Init = var->getInit();
  10831. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  10832. QualType baseType = Context.getBaseElementType(type);
  10833. if (Init && !Init->isValueDependent()) {
  10834. if (var->isConstexpr()) {
  10835. SmallVector<PartialDiagnosticAt, 8> Notes;
  10836. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  10837. SourceLocation DiagLoc = var->getLocation();
  10838. // If the note doesn't add any useful information other than a source
  10839. // location, fold it into the primary diagnostic.
  10840. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10841. diag::note_invalid_subexpr_in_const_expr) {
  10842. DiagLoc = Notes[0].first;
  10843. Notes.clear();
  10844. }
  10845. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  10846. << var << Init->getSourceRange();
  10847. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10848. Diag(Notes[I].first, Notes[I].second);
  10849. }
  10850. } else if (var->mightBeUsableInConstantExpressions(Context)) {
  10851. // Check whether the initializer of a const variable of integral or
  10852. // enumeration type is an ICE now, since we can't tell whether it was
  10853. // initialized by a constant expression if we check later.
  10854. var->checkInitIsICE();
  10855. }
  10856. // Don't emit further diagnostics about constexpr globals since they
  10857. // were just diagnosed.
  10858. if (!var->isConstexpr() && GlobalStorage &&
  10859. var->hasAttr<RequireConstantInitAttr>()) {
  10860. // FIXME: Need strict checking in C++03 here.
  10861. bool DiagErr = getLangOpts().CPlusPlus11
  10862. ? !var->checkInitIsICE() : !checkConstInit();
  10863. if (DiagErr) {
  10864. auto attr = var->getAttr<RequireConstantInitAttr>();
  10865. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  10866. << Init->getSourceRange();
  10867. Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
  10868. << attr->getRange();
  10869. if (getLangOpts().CPlusPlus11) {
  10870. APValue Value;
  10871. SmallVector<PartialDiagnosticAt, 8> Notes;
  10872. Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
  10873. for (auto &it : Notes)
  10874. Diag(it.first, it.second);
  10875. } else {
  10876. Diag(CacheCulprit->getExprLoc(),
  10877. diag::note_invalid_subexpr_in_const_expr)
  10878. << CacheCulprit->getSourceRange();
  10879. }
  10880. }
  10881. }
  10882. else if (!var->isConstexpr() && IsGlobal &&
  10883. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  10884. var->getLocation())) {
  10885. // Warn about globals which don't have a constant initializer. Don't
  10886. // warn about globals with a non-trivial destructor because we already
  10887. // warned about them.
  10888. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  10889. if (!(RD && !RD->hasTrivialDestructor())) {
  10890. if (!checkConstInit())
  10891. Diag(var->getLocation(), diag::warn_global_constructor)
  10892. << Init->getSourceRange();
  10893. }
  10894. }
  10895. }
  10896. // Require the destructor.
  10897. if (const RecordType *recordType = baseType->getAs<RecordType>())
  10898. FinalizeVarWithDestructor(var, recordType);
  10899. // If this variable must be emitted, add it as an initializer for the current
  10900. // module.
  10901. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10902. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10903. }
  10904. /// Determines if a variable's alignment is dependent.
  10905. static bool hasDependentAlignment(VarDecl *VD) {
  10906. if (VD->getType()->isDependentType())
  10907. return true;
  10908. for (auto *I : VD->specific_attrs<AlignedAttr>())
  10909. if (I->isAlignmentDependent())
  10910. return true;
  10911. return false;
  10912. }
  10913. /// Check if VD needs to be dllexport/dllimport due to being in a
  10914. /// dllexport/import function.
  10915. void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
  10916. assert(VD->isStaticLocal());
  10917. auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  10918. // Find outermost function when VD is in lambda function.
  10919. while (FD && !getDLLAttr(FD) &&
  10920. !FD->hasAttr<DLLExportStaticLocalAttr>() &&
  10921. !FD->hasAttr<DLLImportStaticLocalAttr>()) {
  10922. FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
  10923. }
  10924. if (!FD)
  10925. return;
  10926. // Static locals inherit dll attributes from their function.
  10927. if (Attr *A = getDLLAttr(FD)) {
  10928. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  10929. NewAttr->setInherited(true);
  10930. VD->addAttr(NewAttr);
  10931. } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
  10932. auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
  10933. getASTContext(),
  10934. A->getSpellingListIndex());
  10935. NewAttr->setInherited(true);
  10936. VD->addAttr(NewAttr);
  10937. // Export this function to enforce exporting this static variable even
  10938. // if it is not used in this compilation unit.
  10939. if (!FD->hasAttr<DLLExportAttr>())
  10940. FD->addAttr(NewAttr);
  10941. } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
  10942. auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
  10943. getASTContext(),
  10944. A->getSpellingListIndex());
  10945. NewAttr->setInherited(true);
  10946. VD->addAttr(NewAttr);
  10947. }
  10948. }
  10949. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  10950. /// any semantic actions necessary after any initializer has been attached.
  10951. void Sema::FinalizeDeclaration(Decl *ThisDecl) {
  10952. // Note that we are no longer parsing the initializer for this declaration.
  10953. ParsingInitForAutoVars.erase(ThisDecl);
  10954. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  10955. if (!VD)
  10956. return;
  10957. // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
  10958. if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
  10959. !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
  10960. if (PragmaClangBSSSection.Valid)
  10961. VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
  10962. PragmaClangBSSSection.SectionName,
  10963. PragmaClangBSSSection.PragmaLocation));
  10964. if (PragmaClangDataSection.Valid)
  10965. VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
  10966. PragmaClangDataSection.SectionName,
  10967. PragmaClangDataSection.PragmaLocation));
  10968. if (PragmaClangRodataSection.Valid)
  10969. VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
  10970. PragmaClangRodataSection.SectionName,
  10971. PragmaClangRodataSection.PragmaLocation));
  10972. }
  10973. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  10974. for (auto *BD : DD->bindings()) {
  10975. FinalizeDeclaration(BD);
  10976. }
  10977. }
  10978. checkAttributesAfterMerging(*this, *VD);
  10979. // Perform TLS alignment check here after attributes attached to the variable
  10980. // which may affect the alignment have been processed. Only perform the check
  10981. // if the target has a maximum TLS alignment (zero means no constraints).
  10982. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  10983. // Protect the check so that it's not performed on dependent types and
  10984. // dependent alignments (we can't determine the alignment in that case).
  10985. if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
  10986. !VD->isInvalidDecl()) {
  10987. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  10988. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  10989. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  10990. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  10991. << (unsigned)MaxAlignChars.getQuantity();
  10992. }
  10993. }
  10994. }
  10995. if (VD->isStaticLocal()) {
  10996. CheckStaticLocalForDllExport(VD);
  10997. if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  10998. // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
  10999. // function, only __shared__ variables or variables without any device
  11000. // memory qualifiers may be declared with static storage class.
  11001. // Note: It is unclear how a function-scope non-const static variable
  11002. // without device memory qualifier is implemented, therefore only static
  11003. // const variable without device memory qualifier is allowed.
  11004. [&]() {
  11005. if (!getLangOpts().CUDA)
  11006. return;
  11007. if (VD->hasAttr<CUDASharedAttr>())
  11008. return;
  11009. if (VD->getType().isConstQualified() &&
  11010. !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  11011. return;
  11012. if (CUDADiagIfDeviceCode(VD->getLocation(),
  11013. diag::err_device_static_local_var)
  11014. << CurrentCUDATarget())
  11015. VD->setInvalidDecl();
  11016. }();
  11017. }
  11018. }
  11019. // Perform check for initializers of device-side global variables.
  11020. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  11021. // 7.5). We must also apply the same checks to all __shared__
  11022. // variables whether they are local or not. CUDA also allows
  11023. // constant initializers for __constant__ and __device__ variables.
  11024. if (getLangOpts().CUDA)
  11025. checkAllowedCUDAInitializer(VD);
  11026. // Grab the dllimport or dllexport attribute off of the VarDecl.
  11027. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  11028. // Imported static data members cannot be defined out-of-line.
  11029. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  11030. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  11031. VD->isThisDeclarationADefinition()) {
  11032. // We allow definitions of dllimport class template static data members
  11033. // with a warning.
  11034. CXXRecordDecl *Context =
  11035. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  11036. bool IsClassTemplateMember =
  11037. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  11038. Context->getDescribedClassTemplate();
  11039. Diag(VD->getLocation(),
  11040. IsClassTemplateMember
  11041. ? diag::warn_attribute_dllimport_static_field_definition
  11042. : diag::err_attribute_dllimport_static_field_definition);
  11043. Diag(IA->getLocation(), diag::note_attribute);
  11044. if (!IsClassTemplateMember)
  11045. VD->setInvalidDecl();
  11046. }
  11047. }
  11048. // dllimport/dllexport variables cannot be thread local, their TLS index
  11049. // isn't exported with the variable.
  11050. if (DLLAttr && VD->getTLSKind()) {
  11051. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  11052. if (F && getDLLAttr(F)) {
  11053. assert(VD->isStaticLocal());
  11054. // But if this is a static local in a dlimport/dllexport function, the
  11055. // function will never be inlined, which means the var would never be
  11056. // imported, so having it marked import/export is safe.
  11057. } else {
  11058. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  11059. << DLLAttr;
  11060. VD->setInvalidDecl();
  11061. }
  11062. }
  11063. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  11064. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  11065. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  11066. VD->dropAttr<UsedAttr>();
  11067. }
  11068. }
  11069. const DeclContext *DC = VD->getDeclContext();
  11070. // If there's a #pragma GCC visibility in scope, and this isn't a class
  11071. // member, set the visibility of this variable.
  11072. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  11073. AddPushedVisibilityAttribute(VD);
  11074. // FIXME: Warn on unused var template partial specializations.
  11075. if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
  11076. MarkUnusedFileScopedDecl(VD);
  11077. // Now we have parsed the initializer and can update the table of magic
  11078. // tag values.
  11079. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  11080. !VD->getType()->isIntegralOrEnumerationType())
  11081. return;
  11082. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  11083. const Expr *MagicValueExpr = VD->getInit();
  11084. if (!MagicValueExpr) {
  11085. continue;
  11086. }
  11087. llvm::APSInt MagicValueInt;
  11088. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  11089. Diag(I->getRange().getBegin(),
  11090. diag::err_type_tag_for_datatype_not_ice)
  11091. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  11092. continue;
  11093. }
  11094. if (MagicValueInt.getActiveBits() > 64) {
  11095. Diag(I->getRange().getBegin(),
  11096. diag::err_type_tag_for_datatype_too_large)
  11097. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  11098. continue;
  11099. }
  11100. uint64_t MagicValue = MagicValueInt.getZExtValue();
  11101. RegisterTypeTagForDatatype(I->getArgumentKind(),
  11102. MagicValue,
  11103. I->getMatchingCType(),
  11104. I->getLayoutCompatible(),
  11105. I->getMustBeNull());
  11106. }
  11107. }
  11108. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  11109. auto *VD = dyn_cast<VarDecl>(DD);
  11110. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  11111. }
  11112. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  11113. ArrayRef<Decl *> Group) {
  11114. SmallVector<Decl*, 8> Decls;
  11115. if (DS.isTypeSpecOwned())
  11116. Decls.push_back(DS.getRepAsDecl());
  11117. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  11118. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  11119. bool DiagnosedMultipleDecomps = false;
  11120. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  11121. bool DiagnosedNonDeducedAuto = false;
  11122. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  11123. if (Decl *D = Group[i]) {
  11124. // For declarators, there are some additional syntactic-ish checks we need
  11125. // to perform.
  11126. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  11127. if (!FirstDeclaratorInGroup)
  11128. FirstDeclaratorInGroup = DD;
  11129. if (!FirstDecompDeclaratorInGroup)
  11130. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  11131. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  11132. !hasDeducedAuto(DD))
  11133. FirstNonDeducedAutoInGroup = DD;
  11134. if (FirstDeclaratorInGroup != DD) {
  11135. // A decomposition declaration cannot be combined with any other
  11136. // declaration in the same group.
  11137. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  11138. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  11139. diag::err_decomp_decl_not_alone)
  11140. << FirstDeclaratorInGroup->getSourceRange()
  11141. << DD->getSourceRange();
  11142. DiagnosedMultipleDecomps = true;
  11143. }
  11144. // A declarator that uses 'auto' in any way other than to declare a
  11145. // variable with a deduced type cannot be combined with any other
  11146. // declarator in the same group.
  11147. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  11148. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  11149. diag::err_auto_non_deduced_not_alone)
  11150. << FirstNonDeducedAutoInGroup->getType()
  11151. ->hasAutoForTrailingReturnType()
  11152. << FirstDeclaratorInGroup->getSourceRange()
  11153. << DD->getSourceRange();
  11154. DiagnosedNonDeducedAuto = true;
  11155. }
  11156. }
  11157. }
  11158. Decls.push_back(D);
  11159. }
  11160. }
  11161. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  11162. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  11163. handleTagNumbering(Tag, S);
  11164. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  11165. getLangOpts().CPlusPlus)
  11166. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  11167. }
  11168. }
  11169. return BuildDeclaratorGroup(Decls);
  11170. }
  11171. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  11172. /// group, performing any necessary semantic checking.
  11173. Sema::DeclGroupPtrTy
  11174. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  11175. // C++14 [dcl.spec.auto]p7: (DR1347)
  11176. // If the type that replaces the placeholder type is not the same in each
  11177. // deduction, the program is ill-formed.
  11178. if (Group.size() > 1) {
  11179. QualType Deduced;
  11180. VarDecl *DeducedDecl = nullptr;
  11181. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  11182. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  11183. if (!D || D->isInvalidDecl())
  11184. break;
  11185. DeducedType *DT = D->getType()->getContainedDeducedType();
  11186. if (!DT || DT->getDeducedType().isNull())
  11187. continue;
  11188. if (Deduced.isNull()) {
  11189. Deduced = DT->getDeducedType();
  11190. DeducedDecl = D;
  11191. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  11192. auto *AT = dyn_cast<AutoType>(DT);
  11193. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  11194. diag::err_auto_different_deductions)
  11195. << (AT ? (unsigned)AT->getKeyword() : 3)
  11196. << Deduced << DeducedDecl->getDeclName()
  11197. << DT->getDeducedType() << D->getDeclName()
  11198. << DeducedDecl->getInit()->getSourceRange()
  11199. << D->getInit()->getSourceRange();
  11200. D->setInvalidDecl();
  11201. break;
  11202. }
  11203. }
  11204. }
  11205. ActOnDocumentableDecls(Group);
  11206. return DeclGroupPtrTy::make(
  11207. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  11208. }
  11209. void Sema::ActOnDocumentableDecl(Decl *D) {
  11210. ActOnDocumentableDecls(D);
  11211. }
  11212. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  11213. // Don't parse the comment if Doxygen diagnostics are ignored.
  11214. if (Group.empty() || !Group[0])
  11215. return;
  11216. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  11217. Group[0]->getLocation()) &&
  11218. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  11219. Group[0]->getLocation()))
  11220. return;
  11221. if (Group.size() >= 2) {
  11222. // This is a decl group. Normally it will contain only declarations
  11223. // produced from declarator list. But in case we have any definitions or
  11224. // additional declaration references:
  11225. // 'typedef struct S {} S;'
  11226. // 'typedef struct S *S;'
  11227. // 'struct S *pS;'
  11228. // FinalizeDeclaratorGroup adds these as separate declarations.
  11229. Decl *MaybeTagDecl = Group[0];
  11230. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  11231. Group = Group.slice(1);
  11232. }
  11233. }
  11234. // See if there are any new comments that are not attached to a decl.
  11235. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  11236. if (!Comments.empty() &&
  11237. !Comments.back()->isAttached()) {
  11238. // There is at least one comment that not attached to a decl.
  11239. // Maybe it should be attached to one of these decls?
  11240. //
  11241. // Note that this way we pick up not only comments that precede the
  11242. // declaration, but also comments that *follow* the declaration -- thanks to
  11243. // the lookahead in the lexer: we've consumed the semicolon and looked
  11244. // ahead through comments.
  11245. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  11246. Context.getCommentForDecl(Group[i], &PP);
  11247. }
  11248. }
  11249. /// Common checks for a parameter-declaration that should apply to both function
  11250. /// parameters and non-type template parameters.
  11251. void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
  11252. // Check that there are no default arguments inside the type of this
  11253. // parameter.
  11254. if (getLangOpts().CPlusPlus)
  11255. CheckExtraCXXDefaultArguments(D);
  11256. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  11257. if (D.getCXXScopeSpec().isSet()) {
  11258. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  11259. << D.getCXXScopeSpec().getRange();
  11260. }
  11261. // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
  11262. // simple identifier except [...irrelevant cases...].
  11263. switch (D.getName().getKind()) {
  11264. case UnqualifiedIdKind::IK_Identifier:
  11265. break;
  11266. case UnqualifiedIdKind::IK_OperatorFunctionId:
  11267. case UnqualifiedIdKind::IK_ConversionFunctionId:
  11268. case UnqualifiedIdKind::IK_LiteralOperatorId:
  11269. case UnqualifiedIdKind::IK_ConstructorName:
  11270. case UnqualifiedIdKind::IK_DestructorName:
  11271. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  11272. case UnqualifiedIdKind::IK_DeductionGuideName:
  11273. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  11274. << GetNameForDeclarator(D).getName();
  11275. break;
  11276. case UnqualifiedIdKind::IK_TemplateId:
  11277. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  11278. // GetNameForDeclarator would not produce a useful name in this case.
  11279. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
  11280. break;
  11281. }
  11282. }
  11283. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  11284. /// to introduce parameters into function prototype scope.
  11285. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  11286. const DeclSpec &DS = D.getDeclSpec();
  11287. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  11288. // C++03 [dcl.stc]p2 also permits 'auto'.
  11289. StorageClass SC = SC_None;
  11290. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  11291. SC = SC_Register;
  11292. // In C++11, the 'register' storage class specifier is deprecated.
  11293. // In C++17, it is not allowed, but we tolerate it as an extension.
  11294. if (getLangOpts().CPlusPlus11) {
  11295. Diag(DS.getStorageClassSpecLoc(),
  11296. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  11297. : diag::warn_deprecated_register)
  11298. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  11299. }
  11300. } else if (getLangOpts().CPlusPlus &&
  11301. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  11302. SC = SC_Auto;
  11303. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  11304. Diag(DS.getStorageClassSpecLoc(),
  11305. diag::err_invalid_storage_class_in_func_decl);
  11306. D.getMutableDeclSpec().ClearStorageClassSpecs();
  11307. }
  11308. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  11309. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  11310. << DeclSpec::getSpecifierName(TSCS);
  11311. if (DS.isInlineSpecified())
  11312. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  11313. << getLangOpts().CPlusPlus17;
  11314. if (DS.hasConstexprSpecifier())
  11315. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  11316. << 0 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
  11317. DiagnoseFunctionSpecifiers(DS);
  11318. CheckFunctionOrTemplateParamDeclarator(S, D);
  11319. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11320. QualType parmDeclType = TInfo->getType();
  11321. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  11322. IdentifierInfo *II = D.getIdentifier();
  11323. if (II) {
  11324. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  11325. ForVisibleRedeclaration);
  11326. LookupName(R, S);
  11327. if (R.isSingleResult()) {
  11328. NamedDecl *PrevDecl = R.getFoundDecl();
  11329. if (PrevDecl->isTemplateParameter()) {
  11330. // Maybe we will complain about the shadowed template parameter.
  11331. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11332. // Just pretend that we didn't see the previous declaration.
  11333. PrevDecl = nullptr;
  11334. } else if (S->isDeclScope(PrevDecl)) {
  11335. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  11336. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  11337. // Recover by removing the name
  11338. II = nullptr;
  11339. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  11340. D.setInvalidType(true);
  11341. }
  11342. }
  11343. }
  11344. // Temporarily put parameter variables in the translation unit, not
  11345. // the enclosing context. This prevents them from accidentally
  11346. // looking like class members in C++.
  11347. ParmVarDecl *New =
  11348. CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
  11349. D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
  11350. if (D.isInvalidType())
  11351. New->setInvalidDecl();
  11352. assert(S->isFunctionPrototypeScope());
  11353. assert(S->getFunctionPrototypeDepth() >= 1);
  11354. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  11355. S->getNextFunctionPrototypeIndex());
  11356. // Add the parameter declaration into this scope.
  11357. S->AddDecl(New);
  11358. if (II)
  11359. IdResolver.AddDecl(New);
  11360. ProcessDeclAttributes(S, New, D);
  11361. if (D.getDeclSpec().isModulePrivateSpecified())
  11362. Diag(New->getLocation(), diag::err_module_private_local)
  11363. << 1 << New->getDeclName()
  11364. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  11365. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  11366. if (New->hasAttr<BlocksAttr>()) {
  11367. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  11368. }
  11369. return New;
  11370. }
  11371. /// Synthesizes a variable for a parameter arising from a
  11372. /// typedef.
  11373. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  11374. SourceLocation Loc,
  11375. QualType T) {
  11376. /* FIXME: setting StartLoc == Loc.
  11377. Would it be worth to modify callers so as to provide proper source
  11378. location for the unnamed parameters, embedding the parameter's type? */
  11379. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  11380. T, Context.getTrivialTypeSourceInfo(T, Loc),
  11381. SC_None, nullptr);
  11382. Param->setImplicit();
  11383. return Param;
  11384. }
  11385. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  11386. // Don't diagnose unused-parameter errors in template instantiations; we
  11387. // will already have done so in the template itself.
  11388. if (inTemplateInstantiation())
  11389. return;
  11390. for (const ParmVarDecl *Parameter : Parameters) {
  11391. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  11392. !Parameter->hasAttr<UnusedAttr>()) {
  11393. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  11394. << Parameter->getDeclName();
  11395. }
  11396. }
  11397. }
  11398. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  11399. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  11400. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  11401. return;
  11402. // Warn if the return value is pass-by-value and larger than the specified
  11403. // threshold.
  11404. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  11405. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  11406. if (Size > LangOpts.NumLargeByValueCopy)
  11407. Diag(D->getLocation(), diag::warn_return_value_size)
  11408. << D->getDeclName() << Size;
  11409. }
  11410. // Warn if any parameter is pass-by-value and larger than the specified
  11411. // threshold.
  11412. for (const ParmVarDecl *Parameter : Parameters) {
  11413. QualType T = Parameter->getType();
  11414. if (T->isDependentType() || !T.isPODType(Context))
  11415. continue;
  11416. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  11417. if (Size > LangOpts.NumLargeByValueCopy)
  11418. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  11419. << Parameter->getDeclName() << Size;
  11420. }
  11421. }
  11422. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  11423. SourceLocation NameLoc, IdentifierInfo *Name,
  11424. QualType T, TypeSourceInfo *TSInfo,
  11425. StorageClass SC) {
  11426. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  11427. if (getLangOpts().ObjCAutoRefCount &&
  11428. T.getObjCLifetime() == Qualifiers::OCL_None &&
  11429. T->isObjCLifetimeType()) {
  11430. Qualifiers::ObjCLifetime lifetime;
  11431. // Special cases for arrays:
  11432. // - if it's const, use __unsafe_unretained
  11433. // - otherwise, it's an error
  11434. if (T->isArrayType()) {
  11435. if (!T.isConstQualified()) {
  11436. if (DelayedDiagnostics.shouldDelayDiagnostics())
  11437. DelayedDiagnostics.add(
  11438. sema::DelayedDiagnostic::makeForbiddenType(
  11439. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  11440. else
  11441. Diag(NameLoc, diag::err_arc_array_param_no_ownership)
  11442. << TSInfo->getTypeLoc().getSourceRange();
  11443. }
  11444. lifetime = Qualifiers::OCL_ExplicitNone;
  11445. } else {
  11446. lifetime = T->getObjCARCImplicitLifetime();
  11447. }
  11448. T = Context.getLifetimeQualifiedType(T, lifetime);
  11449. }
  11450. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  11451. Context.getAdjustedParameterType(T),
  11452. TSInfo, SC, nullptr);
  11453. if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
  11454. New->getType().hasNonTrivialToPrimitiveCopyCUnion())
  11455. checkNonTrivialCUnion(New->getType(), New->getLocation(),
  11456. NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
  11457. // Parameters can not be abstract class types.
  11458. // For record types, this is done by the AbstractClassUsageDiagnoser once
  11459. // the class has been completely parsed.
  11460. if (!CurContext->isRecord() &&
  11461. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  11462. AbstractParamType))
  11463. New->setInvalidDecl();
  11464. // Parameter declarators cannot be interface types. All ObjC objects are
  11465. // passed by reference.
  11466. if (T->isObjCObjectType()) {
  11467. SourceLocation TypeEndLoc =
  11468. getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
  11469. Diag(NameLoc,
  11470. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  11471. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  11472. T = Context.getObjCObjectPointerType(T);
  11473. New->setType(T);
  11474. }
  11475. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  11476. // duration shall not be qualified by an address-space qualifier."
  11477. // Since all parameters have automatic store duration, they can not have
  11478. // an address space.
  11479. if (T.getAddressSpace() != LangAS::Default &&
  11480. // OpenCL allows function arguments declared to be an array of a type
  11481. // to be qualified with an address space.
  11482. !(getLangOpts().OpenCL &&
  11483. (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
  11484. Diag(NameLoc, diag::err_arg_with_address_space);
  11485. New->setInvalidDecl();
  11486. }
  11487. return New;
  11488. }
  11489. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  11490. SourceLocation LocAfterDecls) {
  11491. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  11492. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  11493. // for a K&R function.
  11494. if (!FTI.hasPrototype) {
  11495. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  11496. --i;
  11497. if (FTI.Params[i].Param == nullptr) {
  11498. SmallString<256> Code;
  11499. llvm::raw_svector_ostream(Code)
  11500. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  11501. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  11502. << FTI.Params[i].Ident
  11503. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  11504. // Implicitly declare the argument as type 'int' for lack of a better
  11505. // type.
  11506. AttributeFactory attrs;
  11507. DeclSpec DS(attrs);
  11508. const char* PrevSpec; // unused
  11509. unsigned DiagID; // unused
  11510. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  11511. DiagID, Context.getPrintingPolicy());
  11512. // Use the identifier location for the type source range.
  11513. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  11514. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  11515. Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
  11516. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  11517. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  11518. }
  11519. }
  11520. }
  11521. }
  11522. Decl *
  11523. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  11524. MultiTemplateParamsArg TemplateParameterLists,
  11525. SkipBodyInfo *SkipBody) {
  11526. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  11527. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  11528. Scope *ParentScope = FnBodyScope->getParent();
  11529. D.setFunctionDefinitionKind(FDK_Definition);
  11530. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  11531. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  11532. }
  11533. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  11534. Consumer.HandleInlineFunctionDefinition(D);
  11535. }
  11536. static bool
  11537. ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  11538. const FunctionDecl *&PossiblePrototype) {
  11539. // Don't warn about invalid declarations.
  11540. if (FD->isInvalidDecl())
  11541. return false;
  11542. // Or declarations that aren't global.
  11543. if (!FD->isGlobal())
  11544. return false;
  11545. // Don't warn about C++ member functions.
  11546. if (isa<CXXMethodDecl>(FD))
  11547. return false;
  11548. // Don't warn about 'main'.
  11549. if (FD->isMain())
  11550. return false;
  11551. // Don't warn about inline functions.
  11552. if (FD->isInlined())
  11553. return false;
  11554. // Don't warn about function templates.
  11555. if (FD->getDescribedFunctionTemplate())
  11556. return false;
  11557. // Don't warn about function template specializations.
  11558. if (FD->isFunctionTemplateSpecialization())
  11559. return false;
  11560. // Don't warn for OpenCL kernels.
  11561. if (FD->hasAttr<OpenCLKernelAttr>())
  11562. return false;
  11563. // Don't warn on explicitly deleted functions.
  11564. if (FD->isDeleted())
  11565. return false;
  11566. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  11567. Prev; Prev = Prev->getPreviousDecl()) {
  11568. // Ignore any declarations that occur in function or method
  11569. // scope, because they aren't visible from the header.
  11570. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  11571. continue;
  11572. PossiblePrototype = Prev;
  11573. return Prev->getType()->isFunctionNoProtoType();
  11574. }
  11575. return true;
  11576. }
  11577. void
  11578. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  11579. const FunctionDecl *EffectiveDefinition,
  11580. SkipBodyInfo *SkipBody) {
  11581. const FunctionDecl *Definition = EffectiveDefinition;
  11582. if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
  11583. // If this is a friend function defined in a class template, it does not
  11584. // have a body until it is used, nevertheless it is a definition, see
  11585. // [temp.inst]p2:
  11586. //
  11587. // ... for the purpose of determining whether an instantiated redeclaration
  11588. // is valid according to [basic.def.odr] and [class.mem], a declaration that
  11589. // corresponds to a definition in the template is considered to be a
  11590. // definition.
  11591. //
  11592. // The following code must produce redefinition error:
  11593. //
  11594. // template<typename T> struct C20 { friend void func_20() {} };
  11595. // C20<int> c20i;
  11596. // void func_20() {}
  11597. //
  11598. for (auto I : FD->redecls()) {
  11599. if (I != FD && !I->isInvalidDecl() &&
  11600. I->getFriendObjectKind() != Decl::FOK_None) {
  11601. if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
  11602. if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
  11603. // A merged copy of the same function, instantiated as a member of
  11604. // the same class, is OK.
  11605. if (declaresSameEntity(OrigFD, Original) &&
  11606. declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
  11607. cast<Decl>(FD->getLexicalDeclContext())))
  11608. continue;
  11609. }
  11610. if (Original->isThisDeclarationADefinition()) {
  11611. Definition = I;
  11612. break;
  11613. }
  11614. }
  11615. }
  11616. }
  11617. }
  11618. if (!Definition)
  11619. // Similar to friend functions a friend function template may be a
  11620. // definition and do not have a body if it is instantiated in a class
  11621. // template.
  11622. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
  11623. for (auto I : FTD->redecls()) {
  11624. auto D = cast<FunctionTemplateDecl>(I);
  11625. if (D != FTD) {
  11626. assert(!D->isThisDeclarationADefinition() &&
  11627. "More than one definition in redeclaration chain");
  11628. if (D->getFriendObjectKind() != Decl::FOK_None)
  11629. if (FunctionTemplateDecl *FT =
  11630. D->getInstantiatedFromMemberTemplate()) {
  11631. if (FT->isThisDeclarationADefinition()) {
  11632. Definition = D->getTemplatedDecl();
  11633. break;
  11634. }
  11635. }
  11636. }
  11637. }
  11638. }
  11639. if (!Definition)
  11640. return;
  11641. if (canRedefineFunction(Definition, getLangOpts()))
  11642. return;
  11643. // Don't emit an error when this is redefinition of a typo-corrected
  11644. // definition.
  11645. if (TypoCorrectedFunctionDefinitions.count(Definition))
  11646. return;
  11647. // If we don't have a visible definition of the function, and it's inline or
  11648. // a template, skip the new definition.
  11649. if (SkipBody && !hasVisibleDefinition(Definition) &&
  11650. (Definition->getFormalLinkage() == InternalLinkage ||
  11651. Definition->isInlined() ||
  11652. Definition->getDescribedFunctionTemplate() ||
  11653. Definition->getNumTemplateParameterLists())) {
  11654. SkipBody->ShouldSkip = true;
  11655. SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
  11656. if (auto *TD = Definition->getDescribedFunctionTemplate())
  11657. makeMergedDefinitionVisible(TD);
  11658. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
  11659. return;
  11660. }
  11661. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  11662. Definition->getStorageClass() == SC_Extern)
  11663. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  11664. << FD->getDeclName() << getLangOpts().CPlusPlus;
  11665. else
  11666. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  11667. Diag(Definition->getLocation(), diag::note_previous_definition);
  11668. FD->setInvalidDecl();
  11669. }
  11670. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  11671. Sema &S) {
  11672. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  11673. LambdaScopeInfo *LSI = S.PushLambdaScope();
  11674. LSI->CallOperator = CallOperator;
  11675. LSI->Lambda = LambdaClass;
  11676. LSI->ReturnType = CallOperator->getReturnType();
  11677. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  11678. if (LCD == LCD_None)
  11679. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  11680. else if (LCD == LCD_ByCopy)
  11681. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  11682. else if (LCD == LCD_ByRef)
  11683. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  11684. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  11685. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  11686. LSI->Mutable = !CallOperator->isConst();
  11687. // Add the captures to the LSI so they can be noted as already
  11688. // captured within tryCaptureVar.
  11689. auto I = LambdaClass->field_begin();
  11690. for (const auto &C : LambdaClass->captures()) {
  11691. if (C.capturesVariable()) {
  11692. VarDecl *VD = C.getCapturedVar();
  11693. if (VD->isInitCapture())
  11694. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  11695. QualType CaptureType = VD->getType();
  11696. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  11697. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  11698. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  11699. /*EllipsisLoc*/C.isPackExpansion()
  11700. ? C.getEllipsisLoc() : SourceLocation(),
  11701. CaptureType, /*Invalid*/false);
  11702. } else if (C.capturesThis()) {
  11703. LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
  11704. C.getCaptureKind() == LCK_StarThis);
  11705. } else {
  11706. LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
  11707. I->getType());
  11708. }
  11709. ++I;
  11710. }
  11711. }
  11712. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  11713. SkipBodyInfo *SkipBody) {
  11714. if (!D) {
  11715. // Parsing the function declaration failed in some way. Push on a fake scope
  11716. // anyway so we can try to parse the function body.
  11717. PushFunctionScope();
  11718. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11719. return D;
  11720. }
  11721. FunctionDecl *FD = nullptr;
  11722. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  11723. FD = FunTmpl->getTemplatedDecl();
  11724. else
  11725. FD = cast<FunctionDecl>(D);
  11726. // Do not push if it is a lambda because one is already pushed when building
  11727. // the lambda in ActOnStartOfLambdaDefinition().
  11728. if (!isLambdaCallOperator(FD))
  11729. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11730. // Check for defining attributes before the check for redefinition.
  11731. if (const auto *Attr = FD->getAttr<AliasAttr>()) {
  11732. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
  11733. FD->dropAttr<AliasAttr>();
  11734. FD->setInvalidDecl();
  11735. }
  11736. if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
  11737. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
  11738. FD->dropAttr<IFuncAttr>();
  11739. FD->setInvalidDecl();
  11740. }
  11741. // See if this is a redefinition. If 'will have body' is already set, then
  11742. // these checks were already performed when it was set.
  11743. if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
  11744. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  11745. // If we're skipping the body, we're done. Don't enter the scope.
  11746. if (SkipBody && SkipBody->ShouldSkip)
  11747. return D;
  11748. }
  11749. // Mark this function as "will have a body eventually". This lets users to
  11750. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  11751. // this function.
  11752. FD->setWillHaveBody();
  11753. // If we are instantiating a generic lambda call operator, push
  11754. // a LambdaScopeInfo onto the function stack. But use the information
  11755. // that's already been calculated (ActOnLambdaExpr) to prime the current
  11756. // LambdaScopeInfo.
  11757. // When the template operator is being specialized, the LambdaScopeInfo,
  11758. // has to be properly restored so that tryCaptureVariable doesn't try
  11759. // and capture any new variables. In addition when calculating potential
  11760. // captures during transformation of nested lambdas, it is necessary to
  11761. // have the LSI properly restored.
  11762. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  11763. assert(inTemplateInstantiation() &&
  11764. "There should be an active template instantiation on the stack "
  11765. "when instantiating a generic lambda!");
  11766. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  11767. } else {
  11768. // Enter a new function scope
  11769. PushFunctionScope();
  11770. }
  11771. // Builtin functions cannot be defined.
  11772. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11773. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  11774. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  11775. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  11776. FD->setInvalidDecl();
  11777. }
  11778. }
  11779. // The return type of a function definition must be complete
  11780. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  11781. QualType ResultType = FD->getReturnType();
  11782. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  11783. !FD->isInvalidDecl() &&
  11784. RequireCompleteType(FD->getLocation(), ResultType,
  11785. diag::err_func_def_incomplete_result))
  11786. FD->setInvalidDecl();
  11787. if (FnBodyScope)
  11788. PushDeclContext(FnBodyScope, FD);
  11789. // Check the validity of our function parameters
  11790. CheckParmsForFunctionDef(FD->parameters(),
  11791. /*CheckParameterNames=*/true);
  11792. // Add non-parameter declarations already in the function to the current
  11793. // scope.
  11794. if (FnBodyScope) {
  11795. for (Decl *NPD : FD->decls()) {
  11796. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  11797. if (!NonParmDecl)
  11798. continue;
  11799. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  11800. "parameters should not be in newly created FD yet");
  11801. // If the decl has a name, make it accessible in the current scope.
  11802. if (NonParmDecl->getDeclName())
  11803. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  11804. // Similarly, dive into enums and fish their constants out, making them
  11805. // accessible in this scope.
  11806. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  11807. for (auto *EI : ED->enumerators())
  11808. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  11809. }
  11810. }
  11811. }
  11812. // Introduce our parameters into the function scope
  11813. for (auto Param : FD->parameters()) {
  11814. Param->setOwningFunction(FD);
  11815. // If this has an identifier, add it to the scope stack.
  11816. if (Param->getIdentifier() && FnBodyScope) {
  11817. CheckShadow(FnBodyScope, Param);
  11818. PushOnScopeChains(Param, FnBodyScope);
  11819. }
  11820. }
  11821. // Ensure that the function's exception specification is instantiated.
  11822. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  11823. ResolveExceptionSpec(D->getLocation(), FPT);
  11824. // dllimport cannot be applied to non-inline function definitions.
  11825. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  11826. !FD->isTemplateInstantiation()) {
  11827. assert(!FD->hasAttr<DLLExportAttr>());
  11828. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  11829. FD->setInvalidDecl();
  11830. return D;
  11831. }
  11832. // We want to attach documentation to original Decl (which might be
  11833. // a function template).
  11834. ActOnDocumentableDecl(D);
  11835. if (getCurLexicalContext()->isObjCContainer() &&
  11836. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  11837. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  11838. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  11839. return D;
  11840. }
  11841. /// Given the set of return statements within a function body,
  11842. /// compute the variables that are subject to the named return value
  11843. /// optimization.
  11844. ///
  11845. /// Each of the variables that is subject to the named return value
  11846. /// optimization will be marked as NRVO variables in the AST, and any
  11847. /// return statement that has a marked NRVO variable as its NRVO candidate can
  11848. /// use the named return value optimization.
  11849. ///
  11850. /// This function applies a very simplistic algorithm for NRVO: if every return
  11851. /// statement in the scope of a variable has the same NRVO candidate, that
  11852. /// candidate is an NRVO variable.
  11853. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  11854. ReturnStmt **Returns = Scope->Returns.data();
  11855. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  11856. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  11857. if (!NRVOCandidate->isNRVOVariable())
  11858. Returns[I]->setNRVOCandidate(nullptr);
  11859. }
  11860. }
  11861. }
  11862. bool Sema::canDelayFunctionBody(const Declarator &D) {
  11863. // We can't delay parsing the body of a constexpr function template (yet).
  11864. if (D.getDeclSpec().hasConstexprSpecifier())
  11865. return false;
  11866. // We can't delay parsing the body of a function template with a deduced
  11867. // return type (yet).
  11868. if (D.getDeclSpec().hasAutoTypeSpec()) {
  11869. // If the placeholder introduces a non-deduced trailing return type,
  11870. // we can still delay parsing it.
  11871. if (D.getNumTypeObjects()) {
  11872. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  11873. if (Outer.Kind == DeclaratorChunk::Function &&
  11874. Outer.Fun.hasTrailingReturnType()) {
  11875. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  11876. return Ty.isNull() || !Ty->isUndeducedType();
  11877. }
  11878. }
  11879. return false;
  11880. }
  11881. return true;
  11882. }
  11883. bool Sema::canSkipFunctionBody(Decl *D) {
  11884. // We cannot skip the body of a function (or function template) which is
  11885. // constexpr, since we may need to evaluate its body in order to parse the
  11886. // rest of the file.
  11887. // We cannot skip the body of a function with an undeduced return type,
  11888. // because any callers of that function need to know the type.
  11889. if (const FunctionDecl *FD = D->getAsFunction()) {
  11890. if (FD->isConstexpr())
  11891. return false;
  11892. // We can't simply call Type::isUndeducedType here, because inside template
  11893. // auto can be deduced to a dependent type, which is not considered
  11894. // "undeduced".
  11895. if (FD->getReturnType()->getContainedDeducedType())
  11896. return false;
  11897. }
  11898. return Consumer.shouldSkipFunctionBody(D);
  11899. }
  11900. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  11901. if (!Decl)
  11902. return nullptr;
  11903. if (FunctionDecl *FD = Decl->getAsFunction())
  11904. FD->setHasSkippedBody();
  11905. else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
  11906. MD->setHasSkippedBody();
  11907. return Decl;
  11908. }
  11909. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  11910. return ActOnFinishFunctionBody(D, BodyArg, false);
  11911. }
  11912. /// RAII object that pops an ExpressionEvaluationContext when exiting a function
  11913. /// body.
  11914. class ExitFunctionBodyRAII {
  11915. public:
  11916. ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
  11917. ~ExitFunctionBodyRAII() {
  11918. if (!IsLambda)
  11919. S.PopExpressionEvaluationContext();
  11920. }
  11921. private:
  11922. Sema &S;
  11923. bool IsLambda = false;
  11924. };
  11925. static void diagnoseImplicitlyRetainedSelf(Sema &S) {
  11926. llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
  11927. auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
  11928. if (EscapeInfo.count(BD))
  11929. return EscapeInfo[BD];
  11930. bool R = false;
  11931. const BlockDecl *CurBD = BD;
  11932. do {
  11933. R = !CurBD->doesNotEscape();
  11934. if (R)
  11935. break;
  11936. CurBD = CurBD->getParent()->getInnermostBlockDecl();
  11937. } while (CurBD);
  11938. return EscapeInfo[BD] = R;
  11939. };
  11940. // If the location where 'self' is implicitly retained is inside a escaping
  11941. // block, emit a diagnostic.
  11942. for (const std::pair<SourceLocation, const BlockDecl *> &P :
  11943. S.ImplicitlyRetainedSelfLocs)
  11944. if (IsOrNestedInEscapingBlock(P.second))
  11945. S.Diag(P.first, diag::warn_implicitly_retains_self)
  11946. << FixItHint::CreateInsertion(P.first, "self->");
  11947. }
  11948. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  11949. bool IsInstantiation) {
  11950. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  11951. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  11952. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  11953. if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
  11954. CheckCompletedCoroutineBody(FD, Body);
  11955. // Do not call PopExpressionEvaluationContext() if it is a lambda because one
  11956. // is already popped when finishing the lambda in BuildLambdaExpr(). This is
  11957. // meant to pop the context added in ActOnStartOfFunctionDef().
  11958. ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
  11959. if (FD) {
  11960. FD->setBody(Body);
  11961. FD->setWillHaveBody(false);
  11962. if (getLangOpts().CPlusPlus14) {
  11963. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  11964. FD->getReturnType()->isUndeducedType()) {
  11965. // If the function has a deduced result type but contains no 'return'
  11966. // statements, the result type as written must be exactly 'auto', and
  11967. // the deduced result type is 'void'.
  11968. if (!FD->getReturnType()->getAs<AutoType>()) {
  11969. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  11970. << FD->getReturnType();
  11971. FD->setInvalidDecl();
  11972. } else {
  11973. // Substitute 'void' for the 'auto' in the type.
  11974. TypeLoc ResultType = getReturnTypeLoc(FD);
  11975. Context.adjustDeducedFunctionResultType(
  11976. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  11977. }
  11978. }
  11979. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  11980. // In C++11, we don't use 'auto' deduction rules for lambda call
  11981. // operators because we don't support return type deduction.
  11982. auto *LSI = getCurLambda();
  11983. if (LSI->HasImplicitReturnType) {
  11984. deduceClosureReturnType(*LSI);
  11985. // C++11 [expr.prim.lambda]p4:
  11986. // [...] if there are no return statements in the compound-statement
  11987. // [the deduced type is] the type void
  11988. QualType RetType =
  11989. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  11990. // Update the return type to the deduced type.
  11991. const FunctionProtoType *Proto =
  11992. FD->getType()->getAs<FunctionProtoType>();
  11993. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  11994. Proto->getExtProtoInfo()));
  11995. }
  11996. }
  11997. // If the function implicitly returns zero (like 'main') or is naked,
  11998. // don't complain about missing return statements.
  11999. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  12000. WP.disableCheckFallThrough();
  12001. // MSVC permits the use of pure specifier (=0) on function definition,
  12002. // defined at class scope, warn about this non-standard construct.
  12003. if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
  12004. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  12005. if (!FD->isInvalidDecl()) {
  12006. // Don't diagnose unused parameters of defaulted or deleted functions.
  12007. if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
  12008. DiagnoseUnusedParameters(FD->parameters());
  12009. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  12010. FD->getReturnType(), FD);
  12011. // If this is a structor, we need a vtable.
  12012. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  12013. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  12014. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  12015. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  12016. // Try to apply the named return value optimization. We have to check
  12017. // if we can do this here because lambdas keep return statements around
  12018. // to deduce an implicit return type.
  12019. if (FD->getReturnType()->isRecordType() &&
  12020. (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
  12021. computeNRVO(Body, getCurFunction());
  12022. }
  12023. // GNU warning -Wmissing-prototypes:
  12024. // Warn if a global function is defined without a previous
  12025. // prototype declaration. This warning is issued even if the
  12026. // definition itself provides a prototype. The aim is to detect
  12027. // global functions that fail to be declared in header files.
  12028. const FunctionDecl *PossiblePrototype = nullptr;
  12029. if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
  12030. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  12031. if (PossiblePrototype) {
  12032. // We found a declaration that is not a prototype,
  12033. // but that could be a zero-parameter prototype
  12034. if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
  12035. TypeLoc TL = TI->getTypeLoc();
  12036. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  12037. Diag(PossiblePrototype->getLocation(),
  12038. diag::note_declaration_not_a_prototype)
  12039. << (FD->getNumParams() != 0)
  12040. << (FD->getNumParams() == 0
  12041. ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
  12042. : FixItHint{});
  12043. }
  12044. } else {
  12045. Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
  12046. << /* function */ 1
  12047. << (FD->getStorageClass() == SC_None
  12048. ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
  12049. "static ")
  12050. : FixItHint{});
  12051. }
  12052. // GNU warning -Wstrict-prototypes
  12053. // Warn if K&R function is defined without a previous declaration.
  12054. // This warning is issued only if the definition itself does not provide
  12055. // a prototype. Only K&R definitions do not provide a prototype.
  12056. // An empty list in a function declarator that is part of a definition
  12057. // of that function specifies that the function has no parameters
  12058. // (C99 6.7.5.3p14)
  12059. if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
  12060. !LangOpts.CPlusPlus) {
  12061. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  12062. TypeLoc TL = TI->getTypeLoc();
  12063. FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
  12064. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
  12065. }
  12066. }
  12067. // Warn on CPUDispatch with an actual body.
  12068. if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
  12069. if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
  12070. if (!CmpndBody->body_empty())
  12071. Diag(CmpndBody->body_front()->getBeginLoc(),
  12072. diag::warn_dispatch_body_ignored);
  12073. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  12074. const CXXMethodDecl *KeyFunction;
  12075. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  12076. MD->isVirtual() &&
  12077. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  12078. MD == KeyFunction->getCanonicalDecl()) {
  12079. // Update the key-function state if necessary for this ABI.
  12080. if (FD->isInlined() &&
  12081. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  12082. Context.setNonKeyFunction(MD);
  12083. // If the newly-chosen key function is already defined, then we
  12084. // need to mark the vtable as used retroactively.
  12085. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  12086. const FunctionDecl *Definition;
  12087. if (KeyFunction && KeyFunction->isDefined(Definition))
  12088. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  12089. } else {
  12090. // We just defined they key function; mark the vtable as used.
  12091. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  12092. }
  12093. }
  12094. }
  12095. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  12096. "Function parsing confused");
  12097. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  12098. assert(MD == getCurMethodDecl() && "Method parsing confused");
  12099. MD->setBody(Body);
  12100. if (!MD->isInvalidDecl()) {
  12101. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  12102. MD->getReturnType(), MD);
  12103. if (Body)
  12104. computeNRVO(Body, getCurFunction());
  12105. }
  12106. if (getCurFunction()->ObjCShouldCallSuper) {
  12107. Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
  12108. << MD->getSelector().getAsString();
  12109. getCurFunction()->ObjCShouldCallSuper = false;
  12110. }
  12111. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  12112. const ObjCMethodDecl *InitMethod = nullptr;
  12113. bool isDesignated =
  12114. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  12115. assert(isDesignated && InitMethod);
  12116. (void)isDesignated;
  12117. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  12118. auto IFace = MD->getClassInterface();
  12119. if (!IFace)
  12120. return false;
  12121. auto SuperD = IFace->getSuperClass();
  12122. if (!SuperD)
  12123. return false;
  12124. return SuperD->getIdentifier() ==
  12125. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  12126. };
  12127. // Don't issue this warning for unavailable inits or direct subclasses
  12128. // of NSObject.
  12129. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  12130. Diag(MD->getLocation(),
  12131. diag::warn_objc_designated_init_missing_super_call);
  12132. Diag(InitMethod->getLocation(),
  12133. diag::note_objc_designated_init_marked_here);
  12134. }
  12135. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  12136. }
  12137. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  12138. // Don't issue this warning for unavaialable inits.
  12139. if (!MD->isUnavailable())
  12140. Diag(MD->getLocation(),
  12141. diag::warn_objc_secondary_init_missing_init_call);
  12142. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  12143. }
  12144. diagnoseImplicitlyRetainedSelf(*this);
  12145. } else {
  12146. // Parsing the function declaration failed in some way. Pop the fake scope
  12147. // we pushed on.
  12148. PopFunctionScopeInfo(ActivePolicy, dcl);
  12149. return nullptr;
  12150. }
  12151. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  12152. DiagnoseUnguardedAvailabilityViolations(dcl);
  12153. assert(!getCurFunction()->ObjCShouldCallSuper &&
  12154. "This should only be set for ObjC methods, which should have been "
  12155. "handled in the block above.");
  12156. // Verify and clean out per-function state.
  12157. if (Body && (!FD || !FD->isDefaulted())) {
  12158. // C++ constructors that have function-try-blocks can't have return
  12159. // statements in the handlers of that block. (C++ [except.handle]p14)
  12160. // Verify this.
  12161. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  12162. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  12163. // Verify that gotos and switch cases don't jump into scopes illegally.
  12164. if (getCurFunction()->NeedsScopeChecking() &&
  12165. !PP.isCodeCompletionEnabled())
  12166. DiagnoseInvalidJumps(Body);
  12167. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  12168. if (!Destructor->getParent()->isDependentType())
  12169. CheckDestructor(Destructor);
  12170. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  12171. Destructor->getParent());
  12172. }
  12173. // If any errors have occurred, clear out any temporaries that may have
  12174. // been leftover. This ensures that these temporaries won't be picked up for
  12175. // deletion in some later function.
  12176. if (getDiagnostics().hasErrorOccurred() ||
  12177. getDiagnostics().getSuppressAllDiagnostics()) {
  12178. DiscardCleanupsInEvaluationContext();
  12179. }
  12180. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  12181. !isa<FunctionTemplateDecl>(dcl)) {
  12182. // Since the body is valid, issue any analysis-based warnings that are
  12183. // enabled.
  12184. ActivePolicy = &WP;
  12185. }
  12186. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  12187. (!CheckConstexprFunctionDecl(FD) ||
  12188. !CheckConstexprFunctionBody(FD, Body)))
  12189. FD->setInvalidDecl();
  12190. if (FD && FD->hasAttr<NakedAttr>()) {
  12191. for (const Stmt *S : Body->children()) {
  12192. // Allow local register variables without initializer as they don't
  12193. // require prologue.
  12194. bool RegisterVariables = false;
  12195. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  12196. for (const auto *Decl : DS->decls()) {
  12197. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  12198. RegisterVariables =
  12199. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  12200. if (!RegisterVariables)
  12201. break;
  12202. }
  12203. }
  12204. }
  12205. if (RegisterVariables)
  12206. continue;
  12207. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  12208. Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
  12209. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  12210. FD->setInvalidDecl();
  12211. break;
  12212. }
  12213. }
  12214. }
  12215. assert(ExprCleanupObjects.size() ==
  12216. ExprEvalContexts.back().NumCleanupObjects &&
  12217. "Leftover temporaries in function");
  12218. assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
  12219. assert(MaybeODRUseExprs.empty() &&
  12220. "Leftover expressions for odr-use checking");
  12221. }
  12222. if (!IsInstantiation)
  12223. PopDeclContext();
  12224. PopFunctionScopeInfo(ActivePolicy, dcl);
  12225. // If any errors have occurred, clear out any temporaries that may have
  12226. // been leftover. This ensures that these temporaries won't be picked up for
  12227. // deletion in some later function.
  12228. if (getDiagnostics().hasErrorOccurred()) {
  12229. DiscardCleanupsInEvaluationContext();
  12230. }
  12231. return dcl;
  12232. }
  12233. /// When we finish delayed parsing of an attribute, we must attach it to the
  12234. /// relevant Decl.
  12235. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  12236. ParsedAttributes &Attrs) {
  12237. // Always attach attributes to the underlying decl.
  12238. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  12239. D = TD->getTemplatedDecl();
  12240. ProcessDeclAttributeList(S, D, Attrs);
  12241. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  12242. if (Method->isStatic())
  12243. checkThisInStaticMemberFunctionAttributes(Method);
  12244. }
  12245. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  12246. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  12247. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  12248. IdentifierInfo &II, Scope *S) {
  12249. // Find the scope in which the identifier is injected and the corresponding
  12250. // DeclContext.
  12251. // FIXME: C89 does not say what happens if there is no enclosing block scope.
  12252. // In that case, we inject the declaration into the translation unit scope
  12253. // instead.
  12254. Scope *BlockScope = S;
  12255. while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
  12256. BlockScope = BlockScope->getParent();
  12257. Scope *ContextScope = BlockScope;
  12258. while (!ContextScope->getEntity())
  12259. ContextScope = ContextScope->getParent();
  12260. ContextRAII SavedContext(*this, ContextScope->getEntity());
  12261. // Before we produce a declaration for an implicitly defined
  12262. // function, see whether there was a locally-scoped declaration of
  12263. // this name as a function or variable. If so, use that
  12264. // (non-visible) declaration, and complain about it.
  12265. NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
  12266. if (ExternCPrev) {
  12267. // We still need to inject the function into the enclosing block scope so
  12268. // that later (non-call) uses can see it.
  12269. PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
  12270. // C89 footnote 38:
  12271. // If in fact it is not defined as having type "function returning int",
  12272. // the behavior is undefined.
  12273. if (!isa<FunctionDecl>(ExternCPrev) ||
  12274. !Context.typesAreCompatible(
  12275. cast<FunctionDecl>(ExternCPrev)->getType(),
  12276. Context.getFunctionNoProtoType(Context.IntTy))) {
  12277. Diag(Loc, diag::ext_use_out_of_scope_declaration)
  12278. << ExternCPrev << !getLangOpts().C99;
  12279. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  12280. return ExternCPrev;
  12281. }
  12282. }
  12283. // Extension in C99. Legal in C90, but warn about it.
  12284. unsigned diag_id;
  12285. if (II.getName().startswith("__builtin_"))
  12286. diag_id = diag::warn_builtin_unknown;
  12287. // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
  12288. else if (getLangOpts().OpenCL)
  12289. diag_id = diag::err_opencl_implicit_function_decl;
  12290. else if (getLangOpts().C99)
  12291. diag_id = diag::ext_implicit_function_decl;
  12292. else
  12293. diag_id = diag::warn_implicit_function_decl;
  12294. Diag(Loc, diag_id) << &II;
  12295. // If we found a prior declaration of this function, don't bother building
  12296. // another one. We've already pushed that one into scope, so there's nothing
  12297. // more to do.
  12298. if (ExternCPrev)
  12299. return ExternCPrev;
  12300. // Because typo correction is expensive, only do it if the implicit
  12301. // function declaration is going to be treated as an error.
  12302. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  12303. TypoCorrection Corrected;
  12304. DeclFilterCCC<FunctionDecl> CCC{};
  12305. if (S && (Corrected =
  12306. CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
  12307. S, nullptr, CCC, CTK_NonError)))
  12308. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  12309. /*ErrorRecovery*/false);
  12310. }
  12311. // Set a Declarator for the implicit definition: int foo();
  12312. const char *Dummy;
  12313. AttributeFactory attrFactory;
  12314. DeclSpec DS(attrFactory);
  12315. unsigned DiagID;
  12316. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  12317. Context.getPrintingPolicy());
  12318. (void)Error; // Silence warning.
  12319. assert(!Error && "Error setting up implicit decl!");
  12320. SourceLocation NoLoc;
  12321. Declarator D(DS, DeclaratorContext::BlockContext);
  12322. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  12323. /*IsAmbiguous=*/false,
  12324. /*LParenLoc=*/NoLoc,
  12325. /*Params=*/nullptr,
  12326. /*NumParams=*/0,
  12327. /*EllipsisLoc=*/NoLoc,
  12328. /*RParenLoc=*/NoLoc,
  12329. /*RefQualifierIsLvalueRef=*/true,
  12330. /*RefQualifierLoc=*/NoLoc,
  12331. /*MutableLoc=*/NoLoc, EST_None,
  12332. /*ESpecRange=*/SourceRange(),
  12333. /*Exceptions=*/nullptr,
  12334. /*ExceptionRanges=*/nullptr,
  12335. /*NumExceptions=*/0,
  12336. /*NoexceptExpr=*/nullptr,
  12337. /*ExceptionSpecTokens=*/nullptr,
  12338. /*DeclsInPrototype=*/None, Loc,
  12339. Loc, D),
  12340. std::move(DS.getAttributes()), SourceLocation());
  12341. D.SetIdentifier(&II, Loc);
  12342. // Insert this function into the enclosing block scope.
  12343. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
  12344. FD->setImplicit();
  12345. AddKnownFunctionAttributes(FD);
  12346. return FD;
  12347. }
  12348. /// Adds any function attributes that we know a priori based on
  12349. /// the declaration of this function.
  12350. ///
  12351. /// These attributes can apply both to implicitly-declared builtins
  12352. /// (like __builtin___printf_chk) or to library-declared functions
  12353. /// like NSLog or printf.
  12354. ///
  12355. /// We need to check for duplicate attributes both here and where user-written
  12356. /// attributes are applied to declarations.
  12357. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  12358. if (FD->isInvalidDecl())
  12359. return;
  12360. // If this is a built-in function, map its builtin attributes to
  12361. // actual attributes.
  12362. if (unsigned BuiltinID = FD->getBuiltinID()) {
  12363. // Handle printf-formatting attributes.
  12364. unsigned FormatIdx;
  12365. bool HasVAListArg;
  12366. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  12367. if (!FD->hasAttr<FormatAttr>()) {
  12368. const char *fmt = "printf";
  12369. unsigned int NumParams = FD->getNumParams();
  12370. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  12371. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  12372. fmt = "NSString";
  12373. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12374. &Context.Idents.get(fmt),
  12375. FormatIdx+1,
  12376. HasVAListArg ? 0 : FormatIdx+2,
  12377. FD->getLocation()));
  12378. }
  12379. }
  12380. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  12381. HasVAListArg)) {
  12382. if (!FD->hasAttr<FormatAttr>())
  12383. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12384. &Context.Idents.get("scanf"),
  12385. FormatIdx+1,
  12386. HasVAListArg ? 0 : FormatIdx+2,
  12387. FD->getLocation()));
  12388. }
  12389. // Handle automatically recognized callbacks.
  12390. SmallVector<int, 4> Encoding;
  12391. if (!FD->hasAttr<CallbackAttr>() &&
  12392. Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
  12393. FD->addAttr(CallbackAttr::CreateImplicit(
  12394. Context, Encoding.data(), Encoding.size(), FD->getLocation()));
  12395. // Mark const if we don't care about errno and that is the only thing
  12396. // preventing the function from being const. This allows IRgen to use LLVM
  12397. // intrinsics for such functions.
  12398. if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
  12399. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
  12400. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12401. // We make "fma" on some platforms const because we know it does not set
  12402. // errno in those environments even though it could set errno based on the
  12403. // C standard.
  12404. const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
  12405. if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
  12406. !FD->hasAttr<ConstAttr>()) {
  12407. switch (BuiltinID) {
  12408. case Builtin::BI__builtin_fma:
  12409. case Builtin::BI__builtin_fmaf:
  12410. case Builtin::BI__builtin_fmal:
  12411. case Builtin::BIfma:
  12412. case Builtin::BIfmaf:
  12413. case Builtin::BIfmal:
  12414. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12415. break;
  12416. default:
  12417. break;
  12418. }
  12419. }
  12420. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  12421. !FD->hasAttr<ReturnsTwiceAttr>())
  12422. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  12423. FD->getLocation()));
  12424. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  12425. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12426. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  12427. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  12428. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  12429. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12430. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  12431. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  12432. // Add the appropriate attribute, depending on the CUDA compilation mode
  12433. // and which target the builtin belongs to. For example, during host
  12434. // compilation, aux builtins are __device__, while the rest are __host__.
  12435. if (getLangOpts().CUDAIsDevice !=
  12436. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  12437. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  12438. else
  12439. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  12440. }
  12441. }
  12442. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  12443. // throw, add an implicit nothrow attribute to any extern "C" function we come
  12444. // across.
  12445. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  12446. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  12447. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  12448. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  12449. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12450. }
  12451. IdentifierInfo *Name = FD->getIdentifier();
  12452. if (!Name)
  12453. return;
  12454. if ((!getLangOpts().CPlusPlus &&
  12455. FD->getDeclContext()->isTranslationUnit()) ||
  12456. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  12457. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  12458. LinkageSpecDecl::lang_c)) {
  12459. // Okay: this could be a libc/libm/Objective-C function we know
  12460. // about.
  12461. } else
  12462. return;
  12463. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  12464. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  12465. // target-specific builtins, perhaps?
  12466. if (!FD->hasAttr<FormatAttr>())
  12467. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12468. &Context.Idents.get("printf"), 2,
  12469. Name->isStr("vasprintf") ? 0 : 3,
  12470. FD->getLocation()));
  12471. }
  12472. if (Name->isStr("__CFStringMakeConstantString")) {
  12473. // We already have a __builtin___CFStringMakeConstantString,
  12474. // but builds that use -fno-constant-cfstrings don't go through that.
  12475. if (!FD->hasAttr<FormatArgAttr>())
  12476. FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
  12477. FD->getLocation()));
  12478. }
  12479. }
  12480. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  12481. TypeSourceInfo *TInfo) {
  12482. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  12483. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  12484. if (!TInfo) {
  12485. assert(D.isInvalidType() && "no declarator info for valid type");
  12486. TInfo = Context.getTrivialTypeSourceInfo(T);
  12487. }
  12488. // Scope manipulation handled by caller.
  12489. TypedefDecl *NewTD =
  12490. TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
  12491. D.getIdentifierLoc(), D.getIdentifier(), TInfo);
  12492. // Bail out immediately if we have an invalid declaration.
  12493. if (D.isInvalidType()) {
  12494. NewTD->setInvalidDecl();
  12495. return NewTD;
  12496. }
  12497. if (D.getDeclSpec().isModulePrivateSpecified()) {
  12498. if (CurContext->isFunctionOrMethod())
  12499. Diag(NewTD->getLocation(), diag::err_module_private_local)
  12500. << 2 << NewTD->getDeclName()
  12501. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  12502. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  12503. else
  12504. NewTD->setModulePrivate();
  12505. }
  12506. // C++ [dcl.typedef]p8:
  12507. // If the typedef declaration defines an unnamed class (or
  12508. // enum), the first typedef-name declared by the declaration
  12509. // to be that class type (or enum type) is used to denote the
  12510. // class type (or enum type) for linkage purposes only.
  12511. // We need to check whether the type was declared in the declaration.
  12512. switch (D.getDeclSpec().getTypeSpecType()) {
  12513. case TST_enum:
  12514. case TST_struct:
  12515. case TST_interface:
  12516. case TST_union:
  12517. case TST_class: {
  12518. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  12519. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  12520. break;
  12521. }
  12522. default:
  12523. break;
  12524. }
  12525. return NewTD;
  12526. }
  12527. /// Check that this is a valid underlying type for an enum declaration.
  12528. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  12529. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  12530. QualType T = TI->getType();
  12531. if (T->isDependentType())
  12532. return false;
  12533. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  12534. if (BT->isInteger())
  12535. return false;
  12536. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  12537. return true;
  12538. }
  12539. /// Check whether this is a valid redeclaration of a previous enumeration.
  12540. /// \return true if the redeclaration was invalid.
  12541. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  12542. QualType EnumUnderlyingTy, bool IsFixed,
  12543. const EnumDecl *Prev) {
  12544. if (IsScoped != Prev->isScoped()) {
  12545. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  12546. << Prev->isScoped();
  12547. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12548. return true;
  12549. }
  12550. if (IsFixed && Prev->isFixed()) {
  12551. if (!EnumUnderlyingTy->isDependentType() &&
  12552. !Prev->getIntegerType()->isDependentType() &&
  12553. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  12554. Prev->getIntegerType())) {
  12555. // TODO: Highlight the underlying type of the redeclaration.
  12556. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  12557. << EnumUnderlyingTy << Prev->getIntegerType();
  12558. Diag(Prev->getLocation(), diag::note_previous_declaration)
  12559. << Prev->getIntegerTypeRange();
  12560. return true;
  12561. }
  12562. } else if (IsFixed != Prev->isFixed()) {
  12563. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  12564. << Prev->isFixed();
  12565. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12566. return true;
  12567. }
  12568. return false;
  12569. }
  12570. /// Get diagnostic %select index for tag kind for
  12571. /// redeclaration diagnostic message.
  12572. /// WARNING: Indexes apply to particular diagnostics only!
  12573. ///
  12574. /// \returns diagnostic %select index.
  12575. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  12576. switch (Tag) {
  12577. case TTK_Struct: return 0;
  12578. case TTK_Interface: return 1;
  12579. case TTK_Class: return 2;
  12580. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  12581. }
  12582. }
  12583. /// Determine if tag kind is a class-key compatible with
  12584. /// class for redeclaration (class, struct, or __interface).
  12585. ///
  12586. /// \returns true iff the tag kind is compatible.
  12587. static bool isClassCompatTagKind(TagTypeKind Tag)
  12588. {
  12589. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  12590. }
  12591. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  12592. TagTypeKind TTK) {
  12593. if (isa<TypedefDecl>(PrevDecl))
  12594. return NTK_Typedef;
  12595. else if (isa<TypeAliasDecl>(PrevDecl))
  12596. return NTK_TypeAlias;
  12597. else if (isa<ClassTemplateDecl>(PrevDecl))
  12598. return NTK_Template;
  12599. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  12600. return NTK_TypeAliasTemplate;
  12601. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  12602. return NTK_TemplateTemplateArgument;
  12603. switch (TTK) {
  12604. case TTK_Struct:
  12605. case TTK_Interface:
  12606. case TTK_Class:
  12607. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  12608. case TTK_Union:
  12609. return NTK_NonUnion;
  12610. case TTK_Enum:
  12611. return NTK_NonEnum;
  12612. }
  12613. llvm_unreachable("invalid TTK");
  12614. }
  12615. /// Determine whether a tag with a given kind is acceptable
  12616. /// as a redeclaration of the given tag declaration.
  12617. ///
  12618. /// \returns true if the new tag kind is acceptable, false otherwise.
  12619. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  12620. TagTypeKind NewTag, bool isDefinition,
  12621. SourceLocation NewTagLoc,
  12622. const IdentifierInfo *Name) {
  12623. // C++ [dcl.type.elab]p3:
  12624. // The class-key or enum keyword present in the
  12625. // elaborated-type-specifier shall agree in kind with the
  12626. // declaration to which the name in the elaborated-type-specifier
  12627. // refers. This rule also applies to the form of
  12628. // elaborated-type-specifier that declares a class-name or
  12629. // friend class since it can be construed as referring to the
  12630. // definition of the class. Thus, in any
  12631. // elaborated-type-specifier, the enum keyword shall be used to
  12632. // refer to an enumeration (7.2), the union class-key shall be
  12633. // used to refer to a union (clause 9), and either the class or
  12634. // struct class-key shall be used to refer to a class (clause 9)
  12635. // declared using the class or struct class-key.
  12636. TagTypeKind OldTag = Previous->getTagKind();
  12637. if (OldTag != NewTag &&
  12638. !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
  12639. return false;
  12640. // Tags are compatible, but we might still want to warn on mismatched tags.
  12641. // Non-class tags can't be mismatched at this point.
  12642. if (!isClassCompatTagKind(NewTag))
  12643. return true;
  12644. // Declarations for which -Wmismatched-tags is disabled are entirely ignored
  12645. // by our warning analysis. We don't want to warn about mismatches with (eg)
  12646. // declarations in system headers that are designed to be specialized, but if
  12647. // a user asks us to warn, we should warn if their code contains mismatched
  12648. // declarations.
  12649. auto IsIgnoredLoc = [&](SourceLocation Loc) {
  12650. return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
  12651. Loc);
  12652. };
  12653. if (IsIgnoredLoc(NewTagLoc))
  12654. return true;
  12655. auto IsIgnored = [&](const TagDecl *Tag) {
  12656. return IsIgnoredLoc(Tag->getLocation());
  12657. };
  12658. while (IsIgnored(Previous)) {
  12659. Previous = Previous->getPreviousDecl();
  12660. if (!Previous)
  12661. return true;
  12662. OldTag = Previous->getTagKind();
  12663. }
  12664. bool isTemplate = false;
  12665. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  12666. isTemplate = Record->getDescribedClassTemplate();
  12667. if (inTemplateInstantiation()) {
  12668. if (OldTag != NewTag) {
  12669. // In a template instantiation, do not offer fix-its for tag mismatches
  12670. // since they usually mess up the template instead of fixing the problem.
  12671. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12672. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12673. << getRedeclDiagFromTagKind(OldTag);
  12674. // FIXME: Note previous location?
  12675. }
  12676. return true;
  12677. }
  12678. if (isDefinition) {
  12679. // On definitions, check all previous tags and issue a fix-it for each
  12680. // one that doesn't match the current tag.
  12681. if (Previous->getDefinition()) {
  12682. // Don't suggest fix-its for redefinitions.
  12683. return true;
  12684. }
  12685. bool previousMismatch = false;
  12686. for (const TagDecl *I : Previous->redecls()) {
  12687. if (I->getTagKind() != NewTag) {
  12688. // Ignore previous declarations for which the warning was disabled.
  12689. if (IsIgnored(I))
  12690. continue;
  12691. if (!previousMismatch) {
  12692. previousMismatch = true;
  12693. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  12694. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12695. << getRedeclDiagFromTagKind(I->getTagKind());
  12696. }
  12697. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  12698. << getRedeclDiagFromTagKind(NewTag)
  12699. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  12700. TypeWithKeyword::getTagTypeKindName(NewTag));
  12701. }
  12702. }
  12703. return true;
  12704. }
  12705. // Identify the prevailing tag kind: this is the kind of the definition (if
  12706. // there is a non-ignored definition), or otherwise the kind of the prior
  12707. // (non-ignored) declaration.
  12708. const TagDecl *PrevDef = Previous->getDefinition();
  12709. if (PrevDef && IsIgnored(PrevDef))
  12710. PrevDef = nullptr;
  12711. const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
  12712. if (Redecl->getTagKind() != NewTag) {
  12713. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12714. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12715. << getRedeclDiagFromTagKind(OldTag);
  12716. Diag(Redecl->getLocation(), diag::note_previous_use);
  12717. // If there is a previous definition, suggest a fix-it.
  12718. if (PrevDef) {
  12719. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  12720. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  12721. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  12722. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  12723. }
  12724. }
  12725. return true;
  12726. }
  12727. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  12728. /// from an outer enclosing namespace or file scope inside a friend declaration.
  12729. /// This should provide the commented out code in the following snippet:
  12730. /// namespace N {
  12731. /// struct X;
  12732. /// namespace M {
  12733. /// struct Y { friend struct /*N::*/ X; };
  12734. /// }
  12735. /// }
  12736. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  12737. SourceLocation NameLoc) {
  12738. // While the decl is in a namespace, do repeated lookup of that name and see
  12739. // if we get the same namespace back. If we do not, continue until
  12740. // translation unit scope, at which point we have a fully qualified NNS.
  12741. SmallVector<IdentifierInfo *, 4> Namespaces;
  12742. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  12743. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  12744. // This tag should be declared in a namespace, which can only be enclosed by
  12745. // other namespaces. Bail if there's an anonymous namespace in the chain.
  12746. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  12747. if (!Namespace || Namespace->isAnonymousNamespace())
  12748. return FixItHint();
  12749. IdentifierInfo *II = Namespace->getIdentifier();
  12750. Namespaces.push_back(II);
  12751. NamedDecl *Lookup = SemaRef.LookupSingleName(
  12752. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  12753. if (Lookup == Namespace)
  12754. break;
  12755. }
  12756. // Once we have all the namespaces, reverse them to go outermost first, and
  12757. // build an NNS.
  12758. SmallString<64> Insertion;
  12759. llvm::raw_svector_ostream OS(Insertion);
  12760. if (DC->isTranslationUnit())
  12761. OS << "::";
  12762. std::reverse(Namespaces.begin(), Namespaces.end());
  12763. for (auto *II : Namespaces)
  12764. OS << II->getName() << "::";
  12765. return FixItHint::CreateInsertion(NameLoc, Insertion);
  12766. }
  12767. /// Determine whether a tag originally declared in context \p OldDC can
  12768. /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
  12769. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  12770. /// using-declaration).
  12771. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  12772. DeclContext *NewDC) {
  12773. OldDC = OldDC->getRedeclContext();
  12774. NewDC = NewDC->getRedeclContext();
  12775. if (OldDC->Equals(NewDC))
  12776. return true;
  12777. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  12778. // encloses the other).
  12779. if (S.getLangOpts().MSVCCompat &&
  12780. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  12781. return true;
  12782. return false;
  12783. }
  12784. /// This is invoked when we see 'struct foo' or 'struct {'. In the
  12785. /// former case, Name will be non-null. In the later case, Name will be null.
  12786. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  12787. /// reference/declaration/definition of a tag.
  12788. ///
  12789. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  12790. /// trailing-type-specifier) other than one in an alias-declaration.
  12791. ///
  12792. /// \param SkipBody If non-null, will be set to indicate if the caller should
  12793. /// skip the definition of this tag and treat it as if it were a declaration.
  12794. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  12795. SourceLocation KWLoc, CXXScopeSpec &SS,
  12796. IdentifierInfo *Name, SourceLocation NameLoc,
  12797. const ParsedAttributesView &Attrs, AccessSpecifier AS,
  12798. SourceLocation ModulePrivateLoc,
  12799. MultiTemplateParamsArg TemplateParameterLists,
  12800. bool &OwnedDecl, bool &IsDependent,
  12801. SourceLocation ScopedEnumKWLoc,
  12802. bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
  12803. bool IsTypeSpecifier, bool IsTemplateParamOrArg,
  12804. SkipBodyInfo *SkipBody) {
  12805. // If this is not a definition, it must have a name.
  12806. IdentifierInfo *OrigName = Name;
  12807. assert((Name != nullptr || TUK == TUK_Definition) &&
  12808. "Nameless record must be a definition!");
  12809. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  12810. OwnedDecl = false;
  12811. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  12812. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  12813. // FIXME: Check member specializations more carefully.
  12814. bool isMemberSpecialization = false;
  12815. bool Invalid = false;
  12816. // We only need to do this matching if we have template parameters
  12817. // or a scope specifier, which also conveniently avoids this work
  12818. // for non-C++ cases.
  12819. if (TemplateParameterLists.size() > 0 ||
  12820. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  12821. if (TemplateParameterList *TemplateParams =
  12822. MatchTemplateParametersToScopeSpecifier(
  12823. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  12824. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  12825. if (Kind == TTK_Enum) {
  12826. Diag(KWLoc, diag::err_enum_template);
  12827. return nullptr;
  12828. }
  12829. if (TemplateParams->size() > 0) {
  12830. // This is a declaration or definition of a class template (which may
  12831. // be a member of another template).
  12832. if (Invalid)
  12833. return nullptr;
  12834. OwnedDecl = false;
  12835. DeclResult Result = CheckClassTemplate(
  12836. S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
  12837. AS, ModulePrivateLoc,
  12838. /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
  12839. TemplateParameterLists.data(), SkipBody);
  12840. return Result.get();
  12841. } else {
  12842. // The "template<>" header is extraneous.
  12843. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12844. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12845. isMemberSpecialization = true;
  12846. }
  12847. }
  12848. }
  12849. // Figure out the underlying type if this a enum declaration. We need to do
  12850. // this early, because it's needed to detect if this is an incompatible
  12851. // redeclaration.
  12852. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  12853. bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
  12854. if (Kind == TTK_Enum) {
  12855. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
  12856. // No underlying type explicitly specified, or we failed to parse the
  12857. // type, default to int.
  12858. EnumUnderlying = Context.IntTy.getTypePtr();
  12859. } else if (UnderlyingType.get()) {
  12860. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  12861. // integral type; any cv-qualification is ignored.
  12862. TypeSourceInfo *TI = nullptr;
  12863. GetTypeFromParser(UnderlyingType.get(), &TI);
  12864. EnumUnderlying = TI;
  12865. if (CheckEnumUnderlyingType(TI))
  12866. // Recover by falling back to int.
  12867. EnumUnderlying = Context.IntTy.getTypePtr();
  12868. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  12869. UPPC_FixedUnderlyingType))
  12870. EnumUnderlying = Context.IntTy.getTypePtr();
  12871. } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  12872. // For MSVC ABI compatibility, unfixed enums must use an underlying type
  12873. // of 'int'. However, if this is an unfixed forward declaration, don't set
  12874. // the underlying type unless the user enables -fms-compatibility. This
  12875. // makes unfixed forward declared enums incomplete and is more conforming.
  12876. if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
  12877. EnumUnderlying = Context.IntTy.getTypePtr();
  12878. }
  12879. }
  12880. DeclContext *SearchDC = CurContext;
  12881. DeclContext *DC = CurContext;
  12882. bool isStdBadAlloc = false;
  12883. bool isStdAlignValT = false;
  12884. RedeclarationKind Redecl = forRedeclarationInCurContext();
  12885. if (TUK == TUK_Friend || TUK == TUK_Reference)
  12886. Redecl = NotForRedeclaration;
  12887. /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
  12888. /// implemented asks for structural equivalence checking, the returned decl
  12889. /// here is passed back to the parser, allowing the tag body to be parsed.
  12890. auto createTagFromNewDecl = [&]() -> TagDecl * {
  12891. assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
  12892. // If there is an identifier, use the location of the identifier as the
  12893. // location of the decl, otherwise use the location of the struct/union
  12894. // keyword.
  12895. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  12896. TagDecl *New = nullptr;
  12897. if (Kind == TTK_Enum) {
  12898. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
  12899. ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
  12900. // If this is an undefined enum, bail.
  12901. if (TUK != TUK_Definition && !Invalid)
  12902. return nullptr;
  12903. if (EnumUnderlying) {
  12904. EnumDecl *ED = cast<EnumDecl>(New);
  12905. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
  12906. ED->setIntegerTypeSourceInfo(TI);
  12907. else
  12908. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  12909. ED->setPromotionType(ED->getIntegerType());
  12910. }
  12911. } else { // struct/union
  12912. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12913. nullptr);
  12914. }
  12915. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  12916. // Add alignment attributes if necessary; these attributes are checked
  12917. // when the ASTContext lays out the structure.
  12918. //
  12919. // It is important for implementing the correct semantics that this
  12920. // happen here (in ActOnTag). The #pragma pack stack is
  12921. // maintained as a result of parser callbacks which can occur at
  12922. // many points during the parsing of a struct declaration (because
  12923. // the #pragma tokens are effectively skipped over during the
  12924. // parsing of the struct).
  12925. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  12926. AddAlignmentAttributesForRecord(RD);
  12927. AddMsStructLayoutForRecord(RD);
  12928. }
  12929. }
  12930. New->setLexicalDeclContext(CurContext);
  12931. return New;
  12932. };
  12933. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  12934. if (Name && SS.isNotEmpty()) {
  12935. // We have a nested-name tag ('struct foo::bar').
  12936. // Check for invalid 'foo::'.
  12937. if (SS.isInvalid()) {
  12938. Name = nullptr;
  12939. goto CreateNewDecl;
  12940. }
  12941. // If this is a friend or a reference to a class in a dependent
  12942. // context, don't try to make a decl for it.
  12943. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  12944. DC = computeDeclContext(SS, false);
  12945. if (!DC) {
  12946. IsDependent = true;
  12947. return nullptr;
  12948. }
  12949. } else {
  12950. DC = computeDeclContext(SS, true);
  12951. if (!DC) {
  12952. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  12953. << SS.getRange();
  12954. return nullptr;
  12955. }
  12956. }
  12957. if (RequireCompleteDeclContext(SS, DC))
  12958. return nullptr;
  12959. SearchDC = DC;
  12960. // Look-up name inside 'foo::'.
  12961. LookupQualifiedName(Previous, DC);
  12962. if (Previous.isAmbiguous())
  12963. return nullptr;
  12964. if (Previous.empty()) {
  12965. // Name lookup did not find anything. However, if the
  12966. // nested-name-specifier refers to the current instantiation,
  12967. // and that current instantiation has any dependent base
  12968. // classes, we might find something at instantiation time: treat
  12969. // this as a dependent elaborated-type-specifier.
  12970. // But this only makes any sense for reference-like lookups.
  12971. if (Previous.wasNotFoundInCurrentInstantiation() &&
  12972. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  12973. IsDependent = true;
  12974. return nullptr;
  12975. }
  12976. // A tag 'foo::bar' must already exist.
  12977. Diag(NameLoc, diag::err_not_tag_in_scope)
  12978. << Kind << Name << DC << SS.getRange();
  12979. Name = nullptr;
  12980. Invalid = true;
  12981. goto CreateNewDecl;
  12982. }
  12983. } else if (Name) {
  12984. // C++14 [class.mem]p14:
  12985. // If T is the name of a class, then each of the following shall have a
  12986. // name different from T:
  12987. // -- every member of class T that is itself a type
  12988. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  12989. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  12990. return nullptr;
  12991. // If this is a named struct, check to see if there was a previous forward
  12992. // declaration or definition.
  12993. // FIXME: We're looking into outer scopes here, even when we
  12994. // shouldn't be. Doing so can result in ambiguities that we
  12995. // shouldn't be diagnosing.
  12996. LookupName(Previous, S);
  12997. // When declaring or defining a tag, ignore ambiguities introduced
  12998. // by types using'ed into this scope.
  12999. if (Previous.isAmbiguous() &&
  13000. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  13001. LookupResult::Filter F = Previous.makeFilter();
  13002. while (F.hasNext()) {
  13003. NamedDecl *ND = F.next();
  13004. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  13005. SearchDC->getRedeclContext()))
  13006. F.erase();
  13007. }
  13008. F.done();
  13009. }
  13010. // C++11 [namespace.memdef]p3:
  13011. // If the name in a friend declaration is neither qualified nor
  13012. // a template-id and the declaration is a function or an
  13013. // elaborated-type-specifier, the lookup to determine whether
  13014. // the entity has been previously declared shall not consider
  13015. // any scopes outside the innermost enclosing namespace.
  13016. //
  13017. // MSVC doesn't implement the above rule for types, so a friend tag
  13018. // declaration may be a redeclaration of a type declared in an enclosing
  13019. // scope. They do implement this rule for friend functions.
  13020. //
  13021. // Does it matter that this should be by scope instead of by
  13022. // semantic context?
  13023. if (!Previous.empty() && TUK == TUK_Friend) {
  13024. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  13025. LookupResult::Filter F = Previous.makeFilter();
  13026. bool FriendSawTagOutsideEnclosingNamespace = false;
  13027. while (F.hasNext()) {
  13028. NamedDecl *ND = F.next();
  13029. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  13030. if (DC->isFileContext() &&
  13031. !EnclosingNS->Encloses(ND->getDeclContext())) {
  13032. if (getLangOpts().MSVCCompat)
  13033. FriendSawTagOutsideEnclosingNamespace = true;
  13034. else
  13035. F.erase();
  13036. }
  13037. }
  13038. F.done();
  13039. // Diagnose this MSVC extension in the easy case where lookup would have
  13040. // unambiguously found something outside the enclosing namespace.
  13041. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  13042. NamedDecl *ND = Previous.getFoundDecl();
  13043. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  13044. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  13045. }
  13046. }
  13047. // Note: there used to be some attempt at recovery here.
  13048. if (Previous.isAmbiguous())
  13049. return nullptr;
  13050. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  13051. // FIXME: This makes sure that we ignore the contexts associated
  13052. // with C structs, unions, and enums when looking for a matching
  13053. // tag declaration or definition. See the similar lookup tweak
  13054. // in Sema::LookupName; is there a better way to deal with this?
  13055. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  13056. SearchDC = SearchDC->getParent();
  13057. }
  13058. }
  13059. if (Previous.isSingleResult() &&
  13060. Previous.getFoundDecl()->isTemplateParameter()) {
  13061. // Maybe we will complain about the shadowed template parameter.
  13062. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  13063. // Just pretend that we didn't see the previous declaration.
  13064. Previous.clear();
  13065. }
  13066. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  13067. DC->Equals(getStdNamespace())) {
  13068. if (Name->isStr("bad_alloc")) {
  13069. // This is a declaration of or a reference to "std::bad_alloc".
  13070. isStdBadAlloc = true;
  13071. // If std::bad_alloc has been implicitly declared (but made invisible to
  13072. // name lookup), fill in this implicit declaration as the previous
  13073. // declaration, so that the declarations get chained appropriately.
  13074. if (Previous.empty() && StdBadAlloc)
  13075. Previous.addDecl(getStdBadAlloc());
  13076. } else if (Name->isStr("align_val_t")) {
  13077. isStdAlignValT = true;
  13078. if (Previous.empty() && StdAlignValT)
  13079. Previous.addDecl(getStdAlignValT());
  13080. }
  13081. }
  13082. // If we didn't find a previous declaration, and this is a reference
  13083. // (or friend reference), move to the correct scope. In C++, we
  13084. // also need to do a redeclaration lookup there, just in case
  13085. // there's a shadow friend decl.
  13086. if (Name && Previous.empty() &&
  13087. (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
  13088. if (Invalid) goto CreateNewDecl;
  13089. assert(SS.isEmpty());
  13090. if (TUK == TUK_Reference || IsTemplateParamOrArg) {
  13091. // C++ [basic.scope.pdecl]p5:
  13092. // -- for an elaborated-type-specifier of the form
  13093. //
  13094. // class-key identifier
  13095. //
  13096. // if the elaborated-type-specifier is used in the
  13097. // decl-specifier-seq or parameter-declaration-clause of a
  13098. // function defined in namespace scope, the identifier is
  13099. // declared as a class-name in the namespace that contains
  13100. // the declaration; otherwise, except as a friend
  13101. // declaration, the identifier is declared in the smallest
  13102. // non-class, non-function-prototype scope that contains the
  13103. // declaration.
  13104. //
  13105. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  13106. // C structs and unions.
  13107. //
  13108. // It is an error in C++ to declare (rather than define) an enum
  13109. // type, including via an elaborated type specifier. We'll
  13110. // diagnose that later; for now, declare the enum in the same
  13111. // scope as we would have picked for any other tag type.
  13112. //
  13113. // GNU C also supports this behavior as part of its incomplete
  13114. // enum types extension, while GNU C++ does not.
  13115. //
  13116. // Find the context where we'll be declaring the tag.
  13117. // FIXME: We would like to maintain the current DeclContext as the
  13118. // lexical context,
  13119. SearchDC = getTagInjectionContext(SearchDC);
  13120. // Find the scope where we'll be declaring the tag.
  13121. S = getTagInjectionScope(S, getLangOpts());
  13122. } else {
  13123. assert(TUK == TUK_Friend);
  13124. // C++ [namespace.memdef]p3:
  13125. // If a friend declaration in a non-local class first declares a
  13126. // class or function, the friend class or function is a member of
  13127. // the innermost enclosing namespace.
  13128. SearchDC = SearchDC->getEnclosingNamespaceContext();
  13129. }
  13130. // In C++, we need to do a redeclaration lookup to properly
  13131. // diagnose some problems.
  13132. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  13133. // hidden declaration so that we don't get ambiguity errors when using a
  13134. // type declared by an elaborated-type-specifier. In C that is not correct
  13135. // and we should instead merge compatible types found by lookup.
  13136. if (getLangOpts().CPlusPlus) {
  13137. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  13138. LookupQualifiedName(Previous, SearchDC);
  13139. } else {
  13140. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  13141. LookupName(Previous, S);
  13142. }
  13143. }
  13144. // If we have a known previous declaration to use, then use it.
  13145. if (Previous.empty() && SkipBody && SkipBody->Previous)
  13146. Previous.addDecl(SkipBody->Previous);
  13147. if (!Previous.empty()) {
  13148. NamedDecl *PrevDecl = Previous.getFoundDecl();
  13149. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  13150. // It's okay to have a tag decl in the same scope as a typedef
  13151. // which hides a tag decl in the same scope. Finding this
  13152. // insanity with a redeclaration lookup can only actually happen
  13153. // in C++.
  13154. //
  13155. // This is also okay for elaborated-type-specifiers, which is
  13156. // technically forbidden by the current standard but which is
  13157. // okay according to the likely resolution of an open issue;
  13158. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  13159. if (getLangOpts().CPlusPlus) {
  13160. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  13161. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  13162. TagDecl *Tag = TT->getDecl();
  13163. if (Tag->getDeclName() == Name &&
  13164. Tag->getDeclContext()->getRedeclContext()
  13165. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  13166. PrevDecl = Tag;
  13167. Previous.clear();
  13168. Previous.addDecl(Tag);
  13169. Previous.resolveKind();
  13170. }
  13171. }
  13172. }
  13173. }
  13174. // If this is a redeclaration of a using shadow declaration, it must
  13175. // declare a tag in the same context. In MSVC mode, we allow a
  13176. // redefinition if either context is within the other.
  13177. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  13178. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  13179. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  13180. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  13181. !(OldTag && isAcceptableTagRedeclContext(
  13182. *this, OldTag->getDeclContext(), SearchDC))) {
  13183. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  13184. Diag(Shadow->getTargetDecl()->getLocation(),
  13185. diag::note_using_decl_target);
  13186. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  13187. << 0;
  13188. // Recover by ignoring the old declaration.
  13189. Previous.clear();
  13190. goto CreateNewDecl;
  13191. }
  13192. }
  13193. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  13194. // If this is a use of a previous tag, or if the tag is already declared
  13195. // in the same scope (so that the definition/declaration completes or
  13196. // rementions the tag), reuse the decl.
  13197. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  13198. isDeclInScope(DirectPrevDecl, SearchDC, S,
  13199. SS.isNotEmpty() || isMemberSpecialization)) {
  13200. // Make sure that this wasn't declared as an enum and now used as a
  13201. // struct or something similar.
  13202. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  13203. TUK == TUK_Definition, KWLoc,
  13204. Name)) {
  13205. bool SafeToContinue
  13206. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  13207. Kind != TTK_Enum);
  13208. if (SafeToContinue)
  13209. Diag(KWLoc, diag::err_use_with_wrong_tag)
  13210. << Name
  13211. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  13212. PrevTagDecl->getKindName());
  13213. else
  13214. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  13215. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  13216. if (SafeToContinue)
  13217. Kind = PrevTagDecl->getTagKind();
  13218. else {
  13219. // Recover by making this an anonymous redefinition.
  13220. Name = nullptr;
  13221. Previous.clear();
  13222. Invalid = true;
  13223. }
  13224. }
  13225. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  13226. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  13227. // If this is an elaborated-type-specifier for a scoped enumeration,
  13228. // the 'class' keyword is not necessary and not permitted.
  13229. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13230. if (ScopedEnum)
  13231. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  13232. << PrevEnum->isScoped()
  13233. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  13234. return PrevTagDecl;
  13235. }
  13236. QualType EnumUnderlyingTy;
  13237. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  13238. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  13239. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  13240. EnumUnderlyingTy = QualType(T, 0);
  13241. // All conflicts with previous declarations are recovered by
  13242. // returning the previous declaration, unless this is a definition,
  13243. // in which case we want the caller to bail out.
  13244. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  13245. ScopedEnum, EnumUnderlyingTy,
  13246. IsFixed, PrevEnum))
  13247. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  13248. }
  13249. // C++11 [class.mem]p1:
  13250. // A member shall not be declared twice in the member-specification,
  13251. // except that a nested class or member class template can be declared
  13252. // and then later defined.
  13253. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  13254. S->isDeclScope(PrevDecl)) {
  13255. Diag(NameLoc, diag::ext_member_redeclared);
  13256. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  13257. }
  13258. if (!Invalid) {
  13259. // If this is a use, just return the declaration we found, unless
  13260. // we have attributes.
  13261. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13262. if (!Attrs.empty()) {
  13263. // FIXME: Diagnose these attributes. For now, we create a new
  13264. // declaration to hold them.
  13265. } else if (TUK == TUK_Reference &&
  13266. (PrevTagDecl->getFriendObjectKind() ==
  13267. Decl::FOK_Undeclared ||
  13268. PrevDecl->getOwningModule() != getCurrentModule()) &&
  13269. SS.isEmpty()) {
  13270. // This declaration is a reference to an existing entity, but
  13271. // has different visibility from that entity: it either makes
  13272. // a friend visible or it makes a type visible in a new module.
  13273. // In either case, create a new declaration. We only do this if
  13274. // the declaration would have meant the same thing if no prior
  13275. // declaration were found, that is, if it was found in the same
  13276. // scope where we would have injected a declaration.
  13277. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  13278. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  13279. return PrevTagDecl;
  13280. // This is in the injected scope, create a new declaration in
  13281. // that scope.
  13282. S = getTagInjectionScope(S, getLangOpts());
  13283. } else {
  13284. return PrevTagDecl;
  13285. }
  13286. }
  13287. // Diagnose attempts to redefine a tag.
  13288. if (TUK == TUK_Definition) {
  13289. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  13290. // If we're defining a specialization and the previous definition
  13291. // is from an implicit instantiation, don't emit an error
  13292. // here; we'll catch this in the general case below.
  13293. bool IsExplicitSpecializationAfterInstantiation = false;
  13294. if (isMemberSpecialization) {
  13295. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  13296. IsExplicitSpecializationAfterInstantiation =
  13297. RD->getTemplateSpecializationKind() !=
  13298. TSK_ExplicitSpecialization;
  13299. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  13300. IsExplicitSpecializationAfterInstantiation =
  13301. ED->getTemplateSpecializationKind() !=
  13302. TSK_ExplicitSpecialization;
  13303. }
  13304. // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
  13305. // not keep more that one definition around (merge them). However,
  13306. // ensure the decl passes the structural compatibility check in
  13307. // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
  13308. NamedDecl *Hidden = nullptr;
  13309. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  13310. // There is a definition of this tag, but it is not visible. We
  13311. // explicitly make use of C++'s one definition rule here, and
  13312. // assume that this definition is identical to the hidden one
  13313. // we already have. Make the existing definition visible and
  13314. // use it in place of this one.
  13315. if (!getLangOpts().CPlusPlus) {
  13316. // Postpone making the old definition visible until after we
  13317. // complete parsing the new one and do the structural
  13318. // comparison.
  13319. SkipBody->CheckSameAsPrevious = true;
  13320. SkipBody->New = createTagFromNewDecl();
  13321. SkipBody->Previous = Def;
  13322. return Def;
  13323. } else {
  13324. SkipBody->ShouldSkip = true;
  13325. SkipBody->Previous = Def;
  13326. makeMergedDefinitionVisible(Hidden);
  13327. // Carry on and handle it like a normal definition. We'll
  13328. // skip starting the definitiion later.
  13329. }
  13330. } else if (!IsExplicitSpecializationAfterInstantiation) {
  13331. // A redeclaration in function prototype scope in C isn't
  13332. // visible elsewhere, so merely issue a warning.
  13333. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  13334. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  13335. else
  13336. Diag(NameLoc, diag::err_redefinition) << Name;
  13337. notePreviousDefinition(Def,
  13338. NameLoc.isValid() ? NameLoc : KWLoc);
  13339. // If this is a redefinition, recover by making this
  13340. // struct be anonymous, which will make any later
  13341. // references get the previous definition.
  13342. Name = nullptr;
  13343. Previous.clear();
  13344. Invalid = true;
  13345. }
  13346. } else {
  13347. // If the type is currently being defined, complain
  13348. // about a nested redefinition.
  13349. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  13350. if (TD->isBeingDefined()) {
  13351. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  13352. Diag(PrevTagDecl->getLocation(),
  13353. diag::note_previous_definition);
  13354. Name = nullptr;
  13355. Previous.clear();
  13356. Invalid = true;
  13357. }
  13358. }
  13359. // Okay, this is definition of a previously declared or referenced
  13360. // tag. We're going to create a new Decl for it.
  13361. }
  13362. // Okay, we're going to make a redeclaration. If this is some kind
  13363. // of reference, make sure we build the redeclaration in the same DC
  13364. // as the original, and ignore the current access specifier.
  13365. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  13366. SearchDC = PrevTagDecl->getDeclContext();
  13367. AS = AS_none;
  13368. }
  13369. }
  13370. // If we get here we have (another) forward declaration or we
  13371. // have a definition. Just create a new decl.
  13372. } else {
  13373. // If we get here, this is a definition of a new tag type in a nested
  13374. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  13375. // new decl/type. We set PrevDecl to NULL so that the entities
  13376. // have distinct types.
  13377. Previous.clear();
  13378. }
  13379. // If we get here, we're going to create a new Decl. If PrevDecl
  13380. // is non-NULL, it's a definition of the tag declared by
  13381. // PrevDecl. If it's NULL, we have a new definition.
  13382. // Otherwise, PrevDecl is not a tag, but was found with tag
  13383. // lookup. This is only actually possible in C++, where a few
  13384. // things like templates still live in the tag namespace.
  13385. } else {
  13386. // Use a better diagnostic if an elaborated-type-specifier
  13387. // found the wrong kind of type on the first
  13388. // (non-redeclaration) lookup.
  13389. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  13390. !Previous.isForRedeclaration()) {
  13391. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13392. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  13393. << Kind;
  13394. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  13395. Invalid = true;
  13396. // Otherwise, only diagnose if the declaration is in scope.
  13397. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  13398. SS.isNotEmpty() || isMemberSpecialization)) {
  13399. // do nothing
  13400. // Diagnose implicit declarations introduced by elaborated types.
  13401. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13402. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13403. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  13404. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13405. Invalid = true;
  13406. // Otherwise it's a declaration. Call out a particularly common
  13407. // case here.
  13408. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  13409. unsigned Kind = 0;
  13410. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  13411. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  13412. << Name << Kind << TND->getUnderlyingType();
  13413. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13414. Invalid = true;
  13415. // Otherwise, diagnose.
  13416. } else {
  13417. // The tag name clashes with something else in the target scope,
  13418. // issue an error and recover by making this tag be anonymous.
  13419. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  13420. notePreviousDefinition(PrevDecl, NameLoc);
  13421. Name = nullptr;
  13422. Invalid = true;
  13423. }
  13424. // The existing declaration isn't relevant to us; we're in a
  13425. // new scope, so clear out the previous declaration.
  13426. Previous.clear();
  13427. }
  13428. }
  13429. CreateNewDecl:
  13430. TagDecl *PrevDecl = nullptr;
  13431. if (Previous.isSingleResult())
  13432. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  13433. // If there is an identifier, use the location of the identifier as the
  13434. // location of the decl, otherwise use the location of the struct/union
  13435. // keyword.
  13436. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  13437. // Otherwise, create a new declaration. If there is a previous
  13438. // declaration of the same entity, the two will be linked via
  13439. // PrevDecl.
  13440. TagDecl *New;
  13441. if (Kind == TTK_Enum) {
  13442. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13443. // enum X { A, B, C } D; D should chain to X.
  13444. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  13445. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  13446. ScopedEnumUsesClassTag, IsFixed);
  13447. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  13448. StdAlignValT = cast<EnumDecl>(New);
  13449. // If this is an undefined enum, warn.
  13450. if (TUK != TUK_Definition && !Invalid) {
  13451. TagDecl *Def;
  13452. if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
  13453. // C++0x: 7.2p2: opaque-enum-declaration.
  13454. // Conflicts are diagnosed above. Do nothing.
  13455. }
  13456. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  13457. Diag(Loc, diag::ext_forward_ref_enum_def)
  13458. << New;
  13459. Diag(Def->getLocation(), diag::note_previous_definition);
  13460. } else {
  13461. unsigned DiagID = diag::ext_forward_ref_enum;
  13462. if (getLangOpts().MSVCCompat)
  13463. DiagID = diag::ext_ms_forward_ref_enum;
  13464. else if (getLangOpts().CPlusPlus)
  13465. DiagID = diag::err_forward_ref_enum;
  13466. Diag(Loc, DiagID);
  13467. }
  13468. }
  13469. if (EnumUnderlying) {
  13470. EnumDecl *ED = cast<EnumDecl>(New);
  13471. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  13472. ED->setIntegerTypeSourceInfo(TI);
  13473. else
  13474. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  13475. ED->setPromotionType(ED->getIntegerType());
  13476. assert(ED->isComplete() && "enum with type should be complete");
  13477. }
  13478. } else {
  13479. // struct/union/class
  13480. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13481. // struct X { int A; } D; D should chain to X.
  13482. if (getLangOpts().CPlusPlus) {
  13483. // FIXME: Look for a way to use RecordDecl for simple structs.
  13484. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13485. cast_or_null<CXXRecordDecl>(PrevDecl));
  13486. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  13487. StdBadAlloc = cast<CXXRecordDecl>(New);
  13488. } else
  13489. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13490. cast_or_null<RecordDecl>(PrevDecl));
  13491. }
  13492. // C++11 [dcl.type]p3:
  13493. // A type-specifier-seq shall not define a class or enumeration [...].
  13494. if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
  13495. TUK == TUK_Definition) {
  13496. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  13497. << Context.getTagDeclType(New);
  13498. Invalid = true;
  13499. }
  13500. if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
  13501. DC->getDeclKind() == Decl::Enum) {
  13502. Diag(New->getLocation(), diag::err_type_defined_in_enum)
  13503. << Context.getTagDeclType(New);
  13504. Invalid = true;
  13505. }
  13506. // Maybe add qualifier info.
  13507. if (SS.isNotEmpty()) {
  13508. if (SS.isSet()) {
  13509. // If this is either a declaration or a definition, check the
  13510. // nested-name-specifier against the current context.
  13511. if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
  13512. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
  13513. isMemberSpecialization))
  13514. Invalid = true;
  13515. New->setQualifierInfo(SS.getWithLocInContext(Context));
  13516. if (TemplateParameterLists.size() > 0) {
  13517. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  13518. }
  13519. }
  13520. else
  13521. Invalid = true;
  13522. }
  13523. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  13524. // Add alignment attributes if necessary; these attributes are checked when
  13525. // the ASTContext lays out the structure.
  13526. //
  13527. // It is important for implementing the correct semantics that this
  13528. // happen here (in ActOnTag). The #pragma pack stack is
  13529. // maintained as a result of parser callbacks which can occur at
  13530. // many points during the parsing of a struct declaration (because
  13531. // the #pragma tokens are effectively skipped over during the
  13532. // parsing of the struct).
  13533. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  13534. AddAlignmentAttributesForRecord(RD);
  13535. AddMsStructLayoutForRecord(RD);
  13536. }
  13537. }
  13538. if (ModulePrivateLoc.isValid()) {
  13539. if (isMemberSpecialization)
  13540. Diag(New->getLocation(), diag::err_module_private_specialization)
  13541. << 2
  13542. << FixItHint::CreateRemoval(ModulePrivateLoc);
  13543. // __module_private__ does not apply to local classes. However, we only
  13544. // diagnose this as an error when the declaration specifiers are
  13545. // freestanding. Here, we just ignore the __module_private__.
  13546. else if (!SearchDC->isFunctionOrMethod())
  13547. New->setModulePrivate();
  13548. }
  13549. // If this is a specialization of a member class (of a class template),
  13550. // check the specialization.
  13551. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  13552. Invalid = true;
  13553. // If we're declaring or defining a tag in function prototype scope in C,
  13554. // note that this type can only be used within the function and add it to
  13555. // the list of decls to inject into the function definition scope.
  13556. if ((Name || Kind == TTK_Enum) &&
  13557. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  13558. if (getLangOpts().CPlusPlus) {
  13559. // C++ [dcl.fct]p6:
  13560. // Types shall not be defined in return or parameter types.
  13561. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  13562. Diag(Loc, diag::err_type_defined_in_param_type)
  13563. << Name;
  13564. Invalid = true;
  13565. }
  13566. } else if (!PrevDecl) {
  13567. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  13568. }
  13569. }
  13570. if (Invalid)
  13571. New->setInvalidDecl();
  13572. // Set the lexical context. If the tag has a C++ scope specifier, the
  13573. // lexical context will be different from the semantic context.
  13574. New->setLexicalDeclContext(CurContext);
  13575. // Mark this as a friend decl if applicable.
  13576. // In Microsoft mode, a friend declaration also acts as a forward
  13577. // declaration so we always pass true to setObjectOfFriendDecl to make
  13578. // the tag name visible.
  13579. if (TUK == TUK_Friend)
  13580. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  13581. // Set the access specifier.
  13582. if (!Invalid && SearchDC->isRecord())
  13583. SetMemberAccessSpecifier(New, PrevDecl, AS);
  13584. if (PrevDecl)
  13585. CheckRedeclarationModuleOwnership(New, PrevDecl);
  13586. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  13587. New->startDefinition();
  13588. ProcessDeclAttributeList(S, New, Attrs);
  13589. AddPragmaAttributes(S, New);
  13590. // If this has an identifier, add it to the scope stack.
  13591. if (TUK == TUK_Friend) {
  13592. // We might be replacing an existing declaration in the lookup tables;
  13593. // if so, borrow its access specifier.
  13594. if (PrevDecl)
  13595. New->setAccess(PrevDecl->getAccess());
  13596. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  13597. DC->makeDeclVisibleInContext(New);
  13598. if (Name) // can be null along some error paths
  13599. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  13600. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  13601. } else if (Name) {
  13602. S = getNonFieldDeclScope(S);
  13603. PushOnScopeChains(New, S, true);
  13604. } else {
  13605. CurContext->addDecl(New);
  13606. }
  13607. // If this is the C FILE type, notify the AST context.
  13608. if (IdentifierInfo *II = New->getIdentifier())
  13609. if (!New->isInvalidDecl() &&
  13610. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  13611. II->isStr("FILE"))
  13612. Context.setFILEDecl(New);
  13613. if (PrevDecl)
  13614. mergeDeclAttributes(New, PrevDecl);
  13615. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13616. // record.
  13617. AddPushedVisibilityAttribute(New);
  13618. if (isMemberSpecialization && !New->isInvalidDecl())
  13619. CompleteMemberSpecialization(New, Previous);
  13620. OwnedDecl = true;
  13621. // In C++, don't return an invalid declaration. We can't recover well from
  13622. // the cases where we make the type anonymous.
  13623. if (Invalid && getLangOpts().CPlusPlus) {
  13624. if (New->isBeingDefined())
  13625. if (auto RD = dyn_cast<RecordDecl>(New))
  13626. RD->completeDefinition();
  13627. return nullptr;
  13628. } else if (SkipBody && SkipBody->ShouldSkip) {
  13629. return SkipBody->Previous;
  13630. } else {
  13631. return New;
  13632. }
  13633. }
  13634. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  13635. AdjustDeclIfTemplate(TagD);
  13636. TagDecl *Tag = cast<TagDecl>(TagD);
  13637. // Enter the tag context.
  13638. PushDeclContext(S, Tag);
  13639. ActOnDocumentableDecl(TagD);
  13640. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13641. // record.
  13642. AddPushedVisibilityAttribute(Tag);
  13643. }
  13644. bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
  13645. SkipBodyInfo &SkipBody) {
  13646. if (!hasStructuralCompatLayout(Prev, SkipBody.New))
  13647. return false;
  13648. // Make the previous decl visible.
  13649. makeMergedDefinitionVisible(SkipBody.Previous);
  13650. return true;
  13651. }
  13652. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  13653. assert(isa<ObjCContainerDecl>(IDecl) &&
  13654. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  13655. DeclContext *OCD = cast<DeclContext>(IDecl);
  13656. assert(getContainingDC(OCD) == CurContext &&
  13657. "The next DeclContext should be lexically contained in the current one.");
  13658. CurContext = OCD;
  13659. return IDecl;
  13660. }
  13661. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  13662. SourceLocation FinalLoc,
  13663. bool IsFinalSpelledSealed,
  13664. SourceLocation LBraceLoc) {
  13665. AdjustDeclIfTemplate(TagD);
  13666. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  13667. FieldCollector->StartClass();
  13668. if (!Record->getIdentifier())
  13669. return;
  13670. if (FinalLoc.isValid())
  13671. Record->addAttr(new (Context)
  13672. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  13673. // C++ [class]p2:
  13674. // [...] The class-name is also inserted into the scope of the
  13675. // class itself; this is known as the injected-class-name. For
  13676. // purposes of access checking, the injected-class-name is treated
  13677. // as if it were a public member name.
  13678. CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
  13679. Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
  13680. Record->getLocation(), Record->getIdentifier(),
  13681. /*PrevDecl=*/nullptr,
  13682. /*DelayTypeCreation=*/true);
  13683. Context.getTypeDeclType(InjectedClassName, Record);
  13684. InjectedClassName->setImplicit();
  13685. InjectedClassName->setAccess(AS_public);
  13686. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  13687. InjectedClassName->setDescribedClassTemplate(Template);
  13688. PushOnScopeChains(InjectedClassName, S);
  13689. assert(InjectedClassName->isInjectedClassName() &&
  13690. "Broken injected-class-name");
  13691. }
  13692. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  13693. SourceRange BraceRange) {
  13694. AdjustDeclIfTemplate(TagD);
  13695. TagDecl *Tag = cast<TagDecl>(TagD);
  13696. Tag->setBraceRange(BraceRange);
  13697. // Make sure we "complete" the definition even it is invalid.
  13698. if (Tag->isBeingDefined()) {
  13699. assert(Tag->isInvalidDecl() && "We should already have completed it");
  13700. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13701. RD->completeDefinition();
  13702. }
  13703. if (isa<CXXRecordDecl>(Tag)) {
  13704. FieldCollector->FinishClass();
  13705. }
  13706. // Exit this scope of this tag's definition.
  13707. PopDeclContext();
  13708. if (getCurLexicalContext()->isObjCContainer() &&
  13709. Tag->getDeclContext()->isFileContext())
  13710. Tag->setTopLevelDeclInObjCContainer();
  13711. // Notify the consumer that we've defined a tag.
  13712. if (!Tag->isInvalidDecl())
  13713. Consumer.HandleTagDeclDefinition(Tag);
  13714. }
  13715. void Sema::ActOnObjCContainerFinishDefinition() {
  13716. // Exit this scope of this interface definition.
  13717. PopDeclContext();
  13718. }
  13719. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  13720. assert(DC == CurContext && "Mismatch of container contexts");
  13721. OriginalLexicalContext = DC;
  13722. ActOnObjCContainerFinishDefinition();
  13723. }
  13724. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  13725. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  13726. OriginalLexicalContext = nullptr;
  13727. }
  13728. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  13729. AdjustDeclIfTemplate(TagD);
  13730. TagDecl *Tag = cast<TagDecl>(TagD);
  13731. Tag->setInvalidDecl();
  13732. // Make sure we "complete" the definition even it is invalid.
  13733. if (Tag->isBeingDefined()) {
  13734. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13735. RD->completeDefinition();
  13736. }
  13737. // We're undoing ActOnTagStartDefinition here, not
  13738. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  13739. // the FieldCollector.
  13740. PopDeclContext();
  13741. }
  13742. // Note that FieldName may be null for anonymous bitfields.
  13743. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  13744. IdentifierInfo *FieldName,
  13745. QualType FieldTy, bool IsMsStruct,
  13746. Expr *BitWidth, bool *ZeroWidth) {
  13747. // Default to true; that shouldn't confuse checks for emptiness
  13748. if (ZeroWidth)
  13749. *ZeroWidth = true;
  13750. // C99 6.7.2.1p4 - verify the field type.
  13751. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  13752. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  13753. // Handle incomplete types with specific error.
  13754. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  13755. return ExprError();
  13756. if (FieldName)
  13757. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  13758. << FieldName << FieldTy << BitWidth->getSourceRange();
  13759. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  13760. << FieldTy << BitWidth->getSourceRange();
  13761. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  13762. UPPC_BitFieldWidth))
  13763. return ExprError();
  13764. // If the bit-width is type- or value-dependent, don't try to check
  13765. // it now.
  13766. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  13767. return BitWidth;
  13768. llvm::APSInt Value;
  13769. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  13770. if (ICE.isInvalid())
  13771. return ICE;
  13772. BitWidth = ICE.get();
  13773. if (Value != 0 && ZeroWidth)
  13774. *ZeroWidth = false;
  13775. // Zero-width bitfield is ok for anonymous field.
  13776. if (Value == 0 && FieldName)
  13777. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  13778. if (Value.isSigned() && Value.isNegative()) {
  13779. if (FieldName)
  13780. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  13781. << FieldName << Value.toString(10);
  13782. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  13783. << Value.toString(10);
  13784. }
  13785. if (!FieldTy->isDependentType()) {
  13786. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  13787. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  13788. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  13789. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  13790. // ABI.
  13791. bool CStdConstraintViolation =
  13792. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  13793. bool MSBitfieldViolation =
  13794. Value.ugt(TypeStorageSize) &&
  13795. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  13796. if (CStdConstraintViolation || MSBitfieldViolation) {
  13797. unsigned DiagWidth =
  13798. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  13799. if (FieldName)
  13800. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  13801. << FieldName << (unsigned)Value.getZExtValue()
  13802. << !CStdConstraintViolation << DiagWidth;
  13803. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  13804. << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
  13805. << DiagWidth;
  13806. }
  13807. // Warn on types where the user might conceivably expect to get all
  13808. // specified bits as value bits: that's all integral types other than
  13809. // 'bool'.
  13810. if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
  13811. if (FieldName)
  13812. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  13813. << FieldName << (unsigned)Value.getZExtValue()
  13814. << (unsigned)TypeWidth;
  13815. else
  13816. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  13817. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  13818. }
  13819. }
  13820. return BitWidth;
  13821. }
  13822. /// ActOnField - Each field of a C struct/union is passed into this in order
  13823. /// to create a FieldDecl object for it.
  13824. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  13825. Declarator &D, Expr *BitfieldWidth) {
  13826. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  13827. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  13828. /*InitStyle=*/ICIS_NoInit, AS_public);
  13829. return Res;
  13830. }
  13831. /// HandleField - Analyze a field of a C struct or a C++ data member.
  13832. ///
  13833. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  13834. SourceLocation DeclStart,
  13835. Declarator &D, Expr *BitWidth,
  13836. InClassInitStyle InitStyle,
  13837. AccessSpecifier AS) {
  13838. if (D.isDecompositionDeclarator()) {
  13839. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  13840. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  13841. << Decomp.getSourceRange();
  13842. return nullptr;
  13843. }
  13844. IdentifierInfo *II = D.getIdentifier();
  13845. SourceLocation Loc = DeclStart;
  13846. if (II) Loc = D.getIdentifierLoc();
  13847. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13848. QualType T = TInfo->getType();
  13849. if (getLangOpts().CPlusPlus) {
  13850. CheckExtraCXXDefaultArguments(D);
  13851. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  13852. UPPC_DataMemberType)) {
  13853. D.setInvalidType();
  13854. T = Context.IntTy;
  13855. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  13856. }
  13857. }
  13858. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  13859. if (D.getDeclSpec().isInlineSpecified())
  13860. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  13861. << getLangOpts().CPlusPlus17;
  13862. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  13863. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  13864. diag::err_invalid_thread)
  13865. << DeclSpec::getSpecifierName(TSCS);
  13866. // Check to see if this name was declared as a member previously
  13867. NamedDecl *PrevDecl = nullptr;
  13868. LookupResult Previous(*this, II, Loc, LookupMemberName,
  13869. ForVisibleRedeclaration);
  13870. LookupName(Previous, S);
  13871. switch (Previous.getResultKind()) {
  13872. case LookupResult::Found:
  13873. case LookupResult::FoundUnresolvedValue:
  13874. PrevDecl = Previous.getAsSingle<NamedDecl>();
  13875. break;
  13876. case LookupResult::FoundOverloaded:
  13877. PrevDecl = Previous.getRepresentativeDecl();
  13878. break;
  13879. case LookupResult::NotFound:
  13880. case LookupResult::NotFoundInCurrentInstantiation:
  13881. case LookupResult::Ambiguous:
  13882. break;
  13883. }
  13884. Previous.suppressDiagnostics();
  13885. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13886. // Maybe we will complain about the shadowed template parameter.
  13887. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  13888. // Just pretend that we didn't see the previous declaration.
  13889. PrevDecl = nullptr;
  13890. }
  13891. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  13892. PrevDecl = nullptr;
  13893. bool Mutable
  13894. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  13895. SourceLocation TSSL = D.getBeginLoc();
  13896. FieldDecl *NewFD
  13897. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  13898. TSSL, AS, PrevDecl, &D);
  13899. if (NewFD->isInvalidDecl())
  13900. Record->setInvalidDecl();
  13901. if (D.getDeclSpec().isModulePrivateSpecified())
  13902. NewFD->setModulePrivate();
  13903. if (NewFD->isInvalidDecl() && PrevDecl) {
  13904. // Don't introduce NewFD into scope; there's already something
  13905. // with the same name in the same scope.
  13906. } else if (II) {
  13907. PushOnScopeChains(NewFD, S);
  13908. } else
  13909. Record->addDecl(NewFD);
  13910. return NewFD;
  13911. }
  13912. /// Build a new FieldDecl and check its well-formedness.
  13913. ///
  13914. /// This routine builds a new FieldDecl given the fields name, type,
  13915. /// record, etc. \p PrevDecl should refer to any previous declaration
  13916. /// with the same name and in the same scope as the field to be
  13917. /// created.
  13918. ///
  13919. /// \returns a new FieldDecl.
  13920. ///
  13921. /// \todo The Declarator argument is a hack. It will be removed once
  13922. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  13923. TypeSourceInfo *TInfo,
  13924. RecordDecl *Record, SourceLocation Loc,
  13925. bool Mutable, Expr *BitWidth,
  13926. InClassInitStyle InitStyle,
  13927. SourceLocation TSSL,
  13928. AccessSpecifier AS, NamedDecl *PrevDecl,
  13929. Declarator *D) {
  13930. IdentifierInfo *II = Name.getAsIdentifierInfo();
  13931. bool InvalidDecl = false;
  13932. if (D) InvalidDecl = D->isInvalidType();
  13933. // If we receive a broken type, recover by assuming 'int' and
  13934. // marking this declaration as invalid.
  13935. if (T.isNull()) {
  13936. InvalidDecl = true;
  13937. T = Context.IntTy;
  13938. }
  13939. QualType EltTy = Context.getBaseElementType(T);
  13940. if (!EltTy->isDependentType()) {
  13941. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  13942. // Fields of incomplete type force their record to be invalid.
  13943. Record->setInvalidDecl();
  13944. InvalidDecl = true;
  13945. } else {
  13946. NamedDecl *Def;
  13947. EltTy->isIncompleteType(&Def);
  13948. if (Def && Def->isInvalidDecl()) {
  13949. Record->setInvalidDecl();
  13950. InvalidDecl = true;
  13951. }
  13952. }
  13953. }
  13954. // TR 18037 does not allow fields to be declared with address space
  13955. if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
  13956. T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
  13957. Diag(Loc, diag::err_field_with_address_space);
  13958. Record->setInvalidDecl();
  13959. InvalidDecl = true;
  13960. }
  13961. if (LangOpts.OpenCL) {
  13962. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  13963. // used as structure or union field: image, sampler, event or block types.
  13964. if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
  13965. T->isBlockPointerType()) {
  13966. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  13967. Record->setInvalidDecl();
  13968. InvalidDecl = true;
  13969. }
  13970. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  13971. if (BitWidth) {
  13972. Diag(Loc, diag::err_opencl_bitfields);
  13973. InvalidDecl = true;
  13974. }
  13975. }
  13976. // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
  13977. if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
  13978. T.hasQualifiers()) {
  13979. InvalidDecl = true;
  13980. Diag(Loc, diag::err_anon_bitfield_qualifiers);
  13981. }
  13982. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  13983. // than a variably modified type.
  13984. if (!InvalidDecl && T->isVariablyModifiedType()) {
  13985. bool SizeIsNegative;
  13986. llvm::APSInt Oversized;
  13987. TypeSourceInfo *FixedTInfo =
  13988. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  13989. SizeIsNegative,
  13990. Oversized);
  13991. if (FixedTInfo) {
  13992. Diag(Loc, diag::warn_illegal_constant_array_size);
  13993. TInfo = FixedTInfo;
  13994. T = FixedTInfo->getType();
  13995. } else {
  13996. if (SizeIsNegative)
  13997. Diag(Loc, diag::err_typecheck_negative_array_size);
  13998. else if (Oversized.getBoolValue())
  13999. Diag(Loc, diag::err_array_too_large)
  14000. << Oversized.toString(10);
  14001. else
  14002. Diag(Loc, diag::err_typecheck_field_variable_size);
  14003. InvalidDecl = true;
  14004. }
  14005. }
  14006. // Fields can not have abstract class types
  14007. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  14008. diag::err_abstract_type_in_decl,
  14009. AbstractFieldType))
  14010. InvalidDecl = true;
  14011. bool ZeroWidth = false;
  14012. if (InvalidDecl)
  14013. BitWidth = nullptr;
  14014. // If this is declared as a bit-field, check the bit-field.
  14015. if (BitWidth) {
  14016. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  14017. &ZeroWidth).get();
  14018. if (!BitWidth) {
  14019. InvalidDecl = true;
  14020. BitWidth = nullptr;
  14021. ZeroWidth = false;
  14022. }
  14023. }
  14024. // Check that 'mutable' is consistent with the type of the declaration.
  14025. if (!InvalidDecl && Mutable) {
  14026. unsigned DiagID = 0;
  14027. if (T->isReferenceType())
  14028. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  14029. : diag::err_mutable_reference;
  14030. else if (T.isConstQualified())
  14031. DiagID = diag::err_mutable_const;
  14032. if (DiagID) {
  14033. SourceLocation ErrLoc = Loc;
  14034. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  14035. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  14036. Diag(ErrLoc, DiagID);
  14037. if (DiagID != diag::ext_mutable_reference) {
  14038. Mutable = false;
  14039. InvalidDecl = true;
  14040. }
  14041. }
  14042. }
  14043. // C++11 [class.union]p8 (DR1460):
  14044. // At most one variant member of a union may have a
  14045. // brace-or-equal-initializer.
  14046. if (InitStyle != ICIS_NoInit)
  14047. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  14048. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  14049. BitWidth, Mutable, InitStyle);
  14050. if (InvalidDecl)
  14051. NewFD->setInvalidDecl();
  14052. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  14053. Diag(Loc, diag::err_duplicate_member) << II;
  14054. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  14055. NewFD->setInvalidDecl();
  14056. }
  14057. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  14058. if (Record->isUnion()) {
  14059. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  14060. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  14061. if (RDecl->getDefinition()) {
  14062. // C++ [class.union]p1: An object of a class with a non-trivial
  14063. // constructor, a non-trivial copy constructor, a non-trivial
  14064. // destructor, or a non-trivial copy assignment operator
  14065. // cannot be a member of a union, nor can an array of such
  14066. // objects.
  14067. if (CheckNontrivialField(NewFD))
  14068. NewFD->setInvalidDecl();
  14069. }
  14070. }
  14071. // C++ [class.union]p1: If a union contains a member of reference type,
  14072. // the program is ill-formed, except when compiling with MSVC extensions
  14073. // enabled.
  14074. if (EltTy->isReferenceType()) {
  14075. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  14076. diag::ext_union_member_of_reference_type :
  14077. diag::err_union_member_of_reference_type)
  14078. << NewFD->getDeclName() << EltTy;
  14079. if (!getLangOpts().MicrosoftExt)
  14080. NewFD->setInvalidDecl();
  14081. }
  14082. }
  14083. }
  14084. // FIXME: We need to pass in the attributes given an AST
  14085. // representation, not a parser representation.
  14086. if (D) {
  14087. // FIXME: The current scope is almost... but not entirely... correct here.
  14088. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  14089. if (NewFD->hasAttrs())
  14090. CheckAlignasUnderalignment(NewFD);
  14091. }
  14092. // In auto-retain/release, infer strong retension for fields of
  14093. // retainable type.
  14094. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  14095. NewFD->setInvalidDecl();
  14096. if (T.isObjCGCWeak())
  14097. Diag(Loc, diag::warn_attribute_weak_on_field);
  14098. NewFD->setAccess(AS);
  14099. return NewFD;
  14100. }
  14101. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  14102. assert(FD);
  14103. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  14104. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  14105. return false;
  14106. QualType EltTy = Context.getBaseElementType(FD->getType());
  14107. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  14108. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  14109. if (RDecl->getDefinition()) {
  14110. // We check for copy constructors before constructors
  14111. // because otherwise we'll never get complaints about
  14112. // copy constructors.
  14113. CXXSpecialMember member = CXXInvalid;
  14114. // We're required to check for any non-trivial constructors. Since the
  14115. // implicit default constructor is suppressed if there are any
  14116. // user-declared constructors, we just need to check that there is a
  14117. // trivial default constructor and a trivial copy constructor. (We don't
  14118. // worry about move constructors here, since this is a C++98 check.)
  14119. if (RDecl->hasNonTrivialCopyConstructor())
  14120. member = CXXCopyConstructor;
  14121. else if (!RDecl->hasTrivialDefaultConstructor())
  14122. member = CXXDefaultConstructor;
  14123. else if (RDecl->hasNonTrivialCopyAssignment())
  14124. member = CXXCopyAssignment;
  14125. else if (RDecl->hasNonTrivialDestructor())
  14126. member = CXXDestructor;
  14127. if (member != CXXInvalid) {
  14128. if (!getLangOpts().CPlusPlus11 &&
  14129. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  14130. // Objective-C++ ARC: it is an error to have a non-trivial field of
  14131. // a union. However, system headers in Objective-C programs
  14132. // occasionally have Objective-C lifetime objects within unions,
  14133. // and rather than cause the program to fail, we make those
  14134. // members unavailable.
  14135. SourceLocation Loc = FD->getLocation();
  14136. if (getSourceManager().isInSystemHeader(Loc)) {
  14137. if (!FD->hasAttr<UnavailableAttr>())
  14138. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  14139. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  14140. return false;
  14141. }
  14142. }
  14143. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  14144. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  14145. diag::err_illegal_union_or_anon_struct_member)
  14146. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  14147. DiagnoseNontrivial(RDecl, member);
  14148. return !getLangOpts().CPlusPlus11;
  14149. }
  14150. }
  14151. }
  14152. return false;
  14153. }
  14154. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  14155. /// AST enum value.
  14156. static ObjCIvarDecl::AccessControl
  14157. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  14158. switch (ivarVisibility) {
  14159. default: llvm_unreachable("Unknown visitibility kind");
  14160. case tok::objc_private: return ObjCIvarDecl::Private;
  14161. case tok::objc_public: return ObjCIvarDecl::Public;
  14162. case tok::objc_protected: return ObjCIvarDecl::Protected;
  14163. case tok::objc_package: return ObjCIvarDecl::Package;
  14164. }
  14165. }
  14166. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  14167. /// in order to create an IvarDecl object for it.
  14168. Decl *Sema::ActOnIvar(Scope *S,
  14169. SourceLocation DeclStart,
  14170. Declarator &D, Expr *BitfieldWidth,
  14171. tok::ObjCKeywordKind Visibility) {
  14172. IdentifierInfo *II = D.getIdentifier();
  14173. Expr *BitWidth = (Expr*)BitfieldWidth;
  14174. SourceLocation Loc = DeclStart;
  14175. if (II) Loc = D.getIdentifierLoc();
  14176. // FIXME: Unnamed fields can be handled in various different ways, for
  14177. // example, unnamed unions inject all members into the struct namespace!
  14178. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14179. QualType T = TInfo->getType();
  14180. if (BitWidth) {
  14181. // 6.7.2.1p3, 6.7.2.1p4
  14182. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  14183. if (!BitWidth)
  14184. D.setInvalidType();
  14185. } else {
  14186. // Not a bitfield.
  14187. // validate II.
  14188. }
  14189. if (T->isReferenceType()) {
  14190. Diag(Loc, diag::err_ivar_reference_type);
  14191. D.setInvalidType();
  14192. }
  14193. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  14194. // than a variably modified type.
  14195. else if (T->isVariablyModifiedType()) {
  14196. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  14197. D.setInvalidType();
  14198. }
  14199. // Get the visibility (access control) for this ivar.
  14200. ObjCIvarDecl::AccessControl ac =
  14201. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  14202. : ObjCIvarDecl::None;
  14203. // Must set ivar's DeclContext to its enclosing interface.
  14204. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  14205. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  14206. return nullptr;
  14207. ObjCContainerDecl *EnclosingContext;
  14208. if (ObjCImplementationDecl *IMPDecl =
  14209. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  14210. if (LangOpts.ObjCRuntime.isFragile()) {
  14211. // Case of ivar declared in an implementation. Context is that of its class.
  14212. EnclosingContext = IMPDecl->getClassInterface();
  14213. assert(EnclosingContext && "Implementation has no class interface!");
  14214. }
  14215. else
  14216. EnclosingContext = EnclosingDecl;
  14217. } else {
  14218. if (ObjCCategoryDecl *CDecl =
  14219. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  14220. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  14221. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  14222. return nullptr;
  14223. }
  14224. }
  14225. EnclosingContext = EnclosingDecl;
  14226. }
  14227. // Construct the decl.
  14228. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  14229. DeclStart, Loc, II, T,
  14230. TInfo, ac, (Expr *)BitfieldWidth);
  14231. if (II) {
  14232. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  14233. ForVisibleRedeclaration);
  14234. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  14235. && !isa<TagDecl>(PrevDecl)) {
  14236. Diag(Loc, diag::err_duplicate_member) << II;
  14237. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  14238. NewID->setInvalidDecl();
  14239. }
  14240. }
  14241. // Process attributes attached to the ivar.
  14242. ProcessDeclAttributes(S, NewID, D);
  14243. if (D.isInvalidType())
  14244. NewID->setInvalidDecl();
  14245. // In ARC, infer 'retaining' for ivars of retainable type.
  14246. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  14247. NewID->setInvalidDecl();
  14248. if (D.getDeclSpec().isModulePrivateSpecified())
  14249. NewID->setModulePrivate();
  14250. if (II) {
  14251. // FIXME: When interfaces are DeclContexts, we'll need to add
  14252. // these to the interface.
  14253. S->AddDecl(NewID);
  14254. IdResolver.AddDecl(NewID);
  14255. }
  14256. if (LangOpts.ObjCRuntime.isNonFragile() &&
  14257. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  14258. Diag(Loc, diag::warn_ivars_in_interface);
  14259. return NewID;
  14260. }
  14261. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  14262. /// class and class extensions. For every class \@interface and class
  14263. /// extension \@interface, if the last ivar is a bitfield of any type,
  14264. /// then add an implicit `char :0` ivar to the end of that interface.
  14265. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  14266. SmallVectorImpl<Decl *> &AllIvarDecls) {
  14267. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  14268. return;
  14269. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  14270. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  14271. if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
  14272. return;
  14273. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  14274. if (!ID) {
  14275. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  14276. if (!CD->IsClassExtension())
  14277. return;
  14278. }
  14279. // No need to add this to end of @implementation.
  14280. else
  14281. return;
  14282. }
  14283. // All conditions are met. Add a new bitfield to the tail end of ivars.
  14284. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  14285. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  14286. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  14287. DeclLoc, DeclLoc, nullptr,
  14288. Context.CharTy,
  14289. Context.getTrivialTypeSourceInfo(Context.CharTy,
  14290. DeclLoc),
  14291. ObjCIvarDecl::Private, BW,
  14292. true);
  14293. AllIvarDecls.push_back(Ivar);
  14294. }
  14295. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  14296. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  14297. SourceLocation RBrac,
  14298. const ParsedAttributesView &Attrs) {
  14299. assert(EnclosingDecl && "missing record or interface decl");
  14300. // If this is an Objective-C @implementation or category and we have
  14301. // new fields here we should reset the layout of the interface since
  14302. // it will now change.
  14303. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  14304. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  14305. switch (DC->getKind()) {
  14306. default: break;
  14307. case Decl::ObjCCategory:
  14308. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  14309. break;
  14310. case Decl::ObjCImplementation:
  14311. Context.
  14312. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  14313. break;
  14314. }
  14315. }
  14316. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  14317. CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
  14318. // Start counting up the number of named members; make sure to include
  14319. // members of anonymous structs and unions in the total.
  14320. unsigned NumNamedMembers = 0;
  14321. if (Record) {
  14322. for (const auto *I : Record->decls()) {
  14323. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  14324. if (IFD->getDeclName())
  14325. ++NumNamedMembers;
  14326. }
  14327. }
  14328. // Verify that all the fields are okay.
  14329. SmallVector<FieldDecl*, 32> RecFields;
  14330. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  14331. i != end; ++i) {
  14332. FieldDecl *FD = cast<FieldDecl>(*i);
  14333. // Get the type for the field.
  14334. const Type *FDTy = FD->getType().getTypePtr();
  14335. if (!FD->isAnonymousStructOrUnion()) {
  14336. // Remember all fields written by the user.
  14337. RecFields.push_back(FD);
  14338. }
  14339. // If the field is already invalid for some reason, don't emit more
  14340. // diagnostics about it.
  14341. if (FD->isInvalidDecl()) {
  14342. EnclosingDecl->setInvalidDecl();
  14343. continue;
  14344. }
  14345. // C99 6.7.2.1p2:
  14346. // A structure or union shall not contain a member with
  14347. // incomplete or function type (hence, a structure shall not
  14348. // contain an instance of itself, but may contain a pointer to
  14349. // an instance of itself), except that the last member of a
  14350. // structure with more than one named member may have incomplete
  14351. // array type; such a structure (and any union containing,
  14352. // possibly recursively, a member that is such a structure)
  14353. // shall not be a member of a structure or an element of an
  14354. // array.
  14355. bool IsLastField = (i + 1 == Fields.end());
  14356. if (FDTy->isFunctionType()) {
  14357. // Field declared as a function.
  14358. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  14359. << FD->getDeclName();
  14360. FD->setInvalidDecl();
  14361. EnclosingDecl->setInvalidDecl();
  14362. continue;
  14363. } else if (FDTy->isIncompleteArrayType() &&
  14364. (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
  14365. if (Record) {
  14366. // Flexible array member.
  14367. // Microsoft and g++ is more permissive regarding flexible array.
  14368. // It will accept flexible array in union and also
  14369. // as the sole element of a struct/class.
  14370. unsigned DiagID = 0;
  14371. if (!Record->isUnion() && !IsLastField) {
  14372. Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
  14373. << FD->getDeclName() << FD->getType() << Record->getTagKind();
  14374. Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
  14375. FD->setInvalidDecl();
  14376. EnclosingDecl->setInvalidDecl();
  14377. continue;
  14378. } else if (Record->isUnion())
  14379. DiagID = getLangOpts().MicrosoftExt
  14380. ? diag::ext_flexible_array_union_ms
  14381. : getLangOpts().CPlusPlus
  14382. ? diag::ext_flexible_array_union_gnu
  14383. : diag::err_flexible_array_union;
  14384. else if (NumNamedMembers < 1)
  14385. DiagID = getLangOpts().MicrosoftExt
  14386. ? diag::ext_flexible_array_empty_aggregate_ms
  14387. : getLangOpts().CPlusPlus
  14388. ? diag::ext_flexible_array_empty_aggregate_gnu
  14389. : diag::err_flexible_array_empty_aggregate;
  14390. if (DiagID)
  14391. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  14392. << Record->getTagKind();
  14393. // While the layout of types that contain virtual bases is not specified
  14394. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  14395. // virtual bases after the derived members. This would make a flexible
  14396. // array member declared at the end of an object not adjacent to the end
  14397. // of the type.
  14398. if (CXXRecord && CXXRecord->getNumVBases() != 0)
  14399. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  14400. << FD->getDeclName() << Record->getTagKind();
  14401. if (!getLangOpts().C99)
  14402. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  14403. << FD->getDeclName() << Record->getTagKind();
  14404. // If the element type has a non-trivial destructor, we would not
  14405. // implicitly destroy the elements, so disallow it for now.
  14406. //
  14407. // FIXME: GCC allows this. We should probably either implicitly delete
  14408. // the destructor of the containing class, or just allow this.
  14409. QualType BaseElem = Context.getBaseElementType(FD->getType());
  14410. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  14411. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  14412. << FD->getDeclName() << FD->getType();
  14413. FD->setInvalidDecl();
  14414. EnclosingDecl->setInvalidDecl();
  14415. continue;
  14416. }
  14417. // Okay, we have a legal flexible array member at the end of the struct.
  14418. Record->setHasFlexibleArrayMember(true);
  14419. } else {
  14420. // In ObjCContainerDecl ivars with incomplete array type are accepted,
  14421. // unless they are followed by another ivar. That check is done
  14422. // elsewhere, after synthesized ivars are known.
  14423. }
  14424. } else if (!FDTy->isDependentType() &&
  14425. RequireCompleteType(FD->getLocation(), FD->getType(),
  14426. diag::err_field_incomplete)) {
  14427. // Incomplete type
  14428. FD->setInvalidDecl();
  14429. EnclosingDecl->setInvalidDecl();
  14430. continue;
  14431. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  14432. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  14433. // A type which contains a flexible array member is considered to be a
  14434. // flexible array member.
  14435. Record->setHasFlexibleArrayMember(true);
  14436. if (!Record->isUnion()) {
  14437. // If this is a struct/class and this is not the last element, reject
  14438. // it. Note that GCC supports variable sized arrays in the middle of
  14439. // structures.
  14440. if (!IsLastField)
  14441. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  14442. << FD->getDeclName() << FD->getType();
  14443. else {
  14444. // We support flexible arrays at the end of structs in
  14445. // other structs as an extension.
  14446. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  14447. << FD->getDeclName();
  14448. }
  14449. }
  14450. }
  14451. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  14452. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  14453. diag::err_abstract_type_in_decl,
  14454. AbstractIvarType)) {
  14455. // Ivars can not have abstract class types
  14456. FD->setInvalidDecl();
  14457. }
  14458. if (Record && FDTTy->getDecl()->hasObjectMember())
  14459. Record->setHasObjectMember(true);
  14460. if (Record && FDTTy->getDecl()->hasVolatileMember())
  14461. Record->setHasVolatileMember(true);
  14462. } else if (FDTy->isObjCObjectType()) {
  14463. /// A field cannot be an Objective-c object
  14464. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  14465. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  14466. QualType T = Context.getObjCObjectPointerType(FD->getType());
  14467. FD->setType(T);
  14468. } else if (getLangOpts().ObjC &&
  14469. getLangOpts().getGC() != LangOptions::NonGC &&
  14470. Record && !Record->hasObjectMember()) {
  14471. if (FD->getType()->isObjCObjectPointerType() ||
  14472. FD->getType().isObjCGCStrong())
  14473. Record->setHasObjectMember(true);
  14474. else if (Context.getAsArrayType(FD->getType())) {
  14475. QualType BaseType = Context.getBaseElementType(FD->getType());
  14476. if (BaseType->isRecordType() &&
  14477. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  14478. Record->setHasObjectMember(true);
  14479. else if (BaseType->isObjCObjectPointerType() ||
  14480. BaseType.isObjCGCStrong())
  14481. Record->setHasObjectMember(true);
  14482. }
  14483. }
  14484. if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
  14485. QualType FT = FD->getType();
  14486. if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
  14487. Record->setNonTrivialToPrimitiveDefaultInitialize(true);
  14488. if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  14489. Record->isUnion())
  14490. Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
  14491. }
  14492. QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
  14493. if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
  14494. Record->setNonTrivialToPrimitiveCopy(true);
  14495. if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
  14496. Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
  14497. }
  14498. if (FT.isDestructedType()) {
  14499. Record->setNonTrivialToPrimitiveDestroy(true);
  14500. Record->setParamDestroyedInCallee(true);
  14501. if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
  14502. Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
  14503. }
  14504. if (const auto *RT = FT->getAs<RecordType>()) {
  14505. if (RT->getDecl()->getArgPassingRestrictions() ==
  14506. RecordDecl::APK_CanNeverPassInRegs)
  14507. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14508. } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
  14509. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14510. }
  14511. if (Record && FD->getType().isVolatileQualified())
  14512. Record->setHasVolatileMember(true);
  14513. // Keep track of the number of named members.
  14514. if (FD->getIdentifier())
  14515. ++NumNamedMembers;
  14516. }
  14517. // Okay, we successfully defined 'Record'.
  14518. if (Record) {
  14519. bool Completed = false;
  14520. if (CXXRecord) {
  14521. if (!CXXRecord->isInvalidDecl()) {
  14522. // Set access bits correctly on the directly-declared conversions.
  14523. for (CXXRecordDecl::conversion_iterator
  14524. I = CXXRecord->conversion_begin(),
  14525. E = CXXRecord->conversion_end(); I != E; ++I)
  14526. I.setAccess((*I)->getAccess());
  14527. }
  14528. if (!CXXRecord->isDependentType()) {
  14529. // Add any implicitly-declared members to this class.
  14530. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  14531. if (!CXXRecord->isInvalidDecl()) {
  14532. // If we have virtual base classes, we may end up finding multiple
  14533. // final overriders for a given virtual function. Check for this
  14534. // problem now.
  14535. if (CXXRecord->getNumVBases()) {
  14536. CXXFinalOverriderMap FinalOverriders;
  14537. CXXRecord->getFinalOverriders(FinalOverriders);
  14538. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  14539. MEnd = FinalOverriders.end();
  14540. M != MEnd; ++M) {
  14541. for (OverridingMethods::iterator SO = M->second.begin(),
  14542. SOEnd = M->second.end();
  14543. SO != SOEnd; ++SO) {
  14544. assert(SO->second.size() > 0 &&
  14545. "Virtual function without overriding functions?");
  14546. if (SO->second.size() == 1)
  14547. continue;
  14548. // C++ [class.virtual]p2:
  14549. // In a derived class, if a virtual member function of a base
  14550. // class subobject has more than one final overrider the
  14551. // program is ill-formed.
  14552. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  14553. << (const NamedDecl *)M->first << Record;
  14554. Diag(M->first->getLocation(),
  14555. diag::note_overridden_virtual_function);
  14556. for (OverridingMethods::overriding_iterator
  14557. OM = SO->second.begin(),
  14558. OMEnd = SO->second.end();
  14559. OM != OMEnd; ++OM)
  14560. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  14561. << (const NamedDecl *)M->first << OM->Method->getParent();
  14562. Record->setInvalidDecl();
  14563. }
  14564. }
  14565. CXXRecord->completeDefinition(&FinalOverriders);
  14566. Completed = true;
  14567. }
  14568. }
  14569. }
  14570. }
  14571. if (!Completed)
  14572. Record->completeDefinition();
  14573. // Handle attributes before checking the layout.
  14574. ProcessDeclAttributeList(S, Record, Attrs);
  14575. // We may have deferred checking for a deleted destructor. Check now.
  14576. if (CXXRecord) {
  14577. auto *Dtor = CXXRecord->getDestructor();
  14578. if (Dtor && Dtor->isImplicit() &&
  14579. ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
  14580. CXXRecord->setImplicitDestructorIsDeleted();
  14581. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  14582. }
  14583. }
  14584. if (Record->hasAttrs()) {
  14585. CheckAlignasUnderalignment(Record);
  14586. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  14587. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  14588. IA->getRange(), IA->getBestCase(),
  14589. IA->getSemanticSpelling());
  14590. }
  14591. // Check if the structure/union declaration is a type that can have zero
  14592. // size in C. For C this is a language extension, for C++ it may cause
  14593. // compatibility problems.
  14594. bool CheckForZeroSize;
  14595. if (!getLangOpts().CPlusPlus) {
  14596. CheckForZeroSize = true;
  14597. } else {
  14598. // For C++ filter out types that cannot be referenced in C code.
  14599. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  14600. CheckForZeroSize =
  14601. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  14602. !CXXRecord->isDependentType() &&
  14603. CXXRecord->isCLike();
  14604. }
  14605. if (CheckForZeroSize) {
  14606. bool ZeroSize = true;
  14607. bool IsEmpty = true;
  14608. unsigned NonBitFields = 0;
  14609. for (RecordDecl::field_iterator I = Record->field_begin(),
  14610. E = Record->field_end();
  14611. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  14612. IsEmpty = false;
  14613. if (I->isUnnamedBitfield()) {
  14614. if (!I->isZeroLengthBitField(Context))
  14615. ZeroSize = false;
  14616. } else {
  14617. ++NonBitFields;
  14618. QualType FieldType = I->getType();
  14619. if (FieldType->isIncompleteType() ||
  14620. !Context.getTypeSizeInChars(FieldType).isZero())
  14621. ZeroSize = false;
  14622. }
  14623. }
  14624. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  14625. // allowed in C++, but warn if its declaration is inside
  14626. // extern "C" block.
  14627. if (ZeroSize) {
  14628. Diag(RecLoc, getLangOpts().CPlusPlus ?
  14629. diag::warn_zero_size_struct_union_in_extern_c :
  14630. diag::warn_zero_size_struct_union_compat)
  14631. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  14632. }
  14633. // Structs without named members are extension in C (C99 6.7.2.1p7),
  14634. // but are accepted by GCC.
  14635. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  14636. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  14637. diag::ext_no_named_members_in_struct_union)
  14638. << Record->isUnion();
  14639. }
  14640. }
  14641. } else {
  14642. ObjCIvarDecl **ClsFields =
  14643. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  14644. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  14645. ID->setEndOfDefinitionLoc(RBrac);
  14646. // Add ivar's to class's DeclContext.
  14647. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14648. ClsFields[i]->setLexicalDeclContext(ID);
  14649. ID->addDecl(ClsFields[i]);
  14650. }
  14651. // Must enforce the rule that ivars in the base classes may not be
  14652. // duplicates.
  14653. if (ID->getSuperClass())
  14654. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  14655. } else if (ObjCImplementationDecl *IMPDecl =
  14656. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  14657. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  14658. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  14659. // Ivar declared in @implementation never belongs to the implementation.
  14660. // Only it is in implementation's lexical context.
  14661. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  14662. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  14663. IMPDecl->setIvarLBraceLoc(LBrac);
  14664. IMPDecl->setIvarRBraceLoc(RBrac);
  14665. } else if (ObjCCategoryDecl *CDecl =
  14666. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  14667. // case of ivars in class extension; all other cases have been
  14668. // reported as errors elsewhere.
  14669. // FIXME. Class extension does not have a LocEnd field.
  14670. // CDecl->setLocEnd(RBrac);
  14671. // Add ivar's to class extension's DeclContext.
  14672. // Diagnose redeclaration of private ivars.
  14673. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  14674. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14675. if (IDecl) {
  14676. if (const ObjCIvarDecl *ClsIvar =
  14677. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14678. Diag(ClsFields[i]->getLocation(),
  14679. diag::err_duplicate_ivar_declaration);
  14680. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  14681. continue;
  14682. }
  14683. for (const auto *Ext : IDecl->known_extensions()) {
  14684. if (const ObjCIvarDecl *ClsExtIvar
  14685. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14686. Diag(ClsFields[i]->getLocation(),
  14687. diag::err_duplicate_ivar_declaration);
  14688. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  14689. continue;
  14690. }
  14691. }
  14692. }
  14693. ClsFields[i]->setLexicalDeclContext(CDecl);
  14694. CDecl->addDecl(ClsFields[i]);
  14695. }
  14696. CDecl->setIvarLBraceLoc(LBrac);
  14697. CDecl->setIvarRBraceLoc(RBrac);
  14698. }
  14699. }
  14700. }
  14701. /// Determine whether the given integral value is representable within
  14702. /// the given type T.
  14703. static bool isRepresentableIntegerValue(ASTContext &Context,
  14704. llvm::APSInt &Value,
  14705. QualType T) {
  14706. assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
  14707. "Integral type required!");
  14708. unsigned BitWidth = Context.getIntWidth(T);
  14709. if (Value.isUnsigned() || Value.isNonNegative()) {
  14710. if (T->isSignedIntegerOrEnumerationType())
  14711. --BitWidth;
  14712. return Value.getActiveBits() <= BitWidth;
  14713. }
  14714. return Value.getMinSignedBits() <= BitWidth;
  14715. }
  14716. // Given an integral type, return the next larger integral type
  14717. // (or a NULL type of no such type exists).
  14718. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  14719. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  14720. // enum checking below.
  14721. assert((T->isIntegralType(Context) ||
  14722. T->isEnumeralType()) && "Integral type required!");
  14723. const unsigned NumTypes = 4;
  14724. QualType SignedIntegralTypes[NumTypes] = {
  14725. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  14726. };
  14727. QualType UnsignedIntegralTypes[NumTypes] = {
  14728. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  14729. Context.UnsignedLongLongTy
  14730. };
  14731. unsigned BitWidth = Context.getTypeSize(T);
  14732. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  14733. : UnsignedIntegralTypes;
  14734. for (unsigned I = 0; I != NumTypes; ++I)
  14735. if (Context.getTypeSize(Types[I]) > BitWidth)
  14736. return Types[I];
  14737. return QualType();
  14738. }
  14739. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  14740. EnumConstantDecl *LastEnumConst,
  14741. SourceLocation IdLoc,
  14742. IdentifierInfo *Id,
  14743. Expr *Val) {
  14744. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  14745. llvm::APSInt EnumVal(IntWidth);
  14746. QualType EltTy;
  14747. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  14748. Val = nullptr;
  14749. if (Val)
  14750. Val = DefaultLvalueConversion(Val).get();
  14751. if (Val) {
  14752. if (Enum->isDependentType() || Val->isTypeDependent())
  14753. EltTy = Context.DependentTy;
  14754. else {
  14755. if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
  14756. !getLangOpts().MSVCCompat) {
  14757. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  14758. // constant-expression in the enumerator-definition shall be a converted
  14759. // constant expression of the underlying type.
  14760. EltTy = Enum->getIntegerType();
  14761. ExprResult Converted =
  14762. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  14763. CCEK_Enumerator);
  14764. if (Converted.isInvalid())
  14765. Val = nullptr;
  14766. else
  14767. Val = Converted.get();
  14768. } else if (!Val->isValueDependent() &&
  14769. !(Val = VerifyIntegerConstantExpression(Val,
  14770. &EnumVal).get())) {
  14771. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  14772. } else {
  14773. if (Enum->isComplete()) {
  14774. EltTy = Enum->getIntegerType();
  14775. // In Obj-C and Microsoft mode, require the enumeration value to be
  14776. // representable in the underlying type of the enumeration. In C++11,
  14777. // we perform a non-narrowing conversion as part of converted constant
  14778. // expression checking.
  14779. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14780. if (getLangOpts().MSVCCompat) {
  14781. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  14782. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  14783. } else
  14784. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  14785. } else
  14786. Val = ImpCastExprToType(Val, EltTy,
  14787. EltTy->isBooleanType() ?
  14788. CK_IntegralToBoolean : CK_IntegralCast)
  14789. .get();
  14790. } else if (getLangOpts().CPlusPlus) {
  14791. // C++11 [dcl.enum]p5:
  14792. // If the underlying type is not fixed, the type of each enumerator
  14793. // is the type of its initializing value:
  14794. // - If an initializer is specified for an enumerator, the
  14795. // initializing value has the same type as the expression.
  14796. EltTy = Val->getType();
  14797. } else {
  14798. // C99 6.7.2.2p2:
  14799. // The expression that defines the value of an enumeration constant
  14800. // shall be an integer constant expression that has a value
  14801. // representable as an int.
  14802. // Complain if the value is not representable in an int.
  14803. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  14804. Diag(IdLoc, diag::ext_enum_value_not_int)
  14805. << EnumVal.toString(10) << Val->getSourceRange()
  14806. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  14807. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  14808. // Force the type of the expression to 'int'.
  14809. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  14810. }
  14811. EltTy = Val->getType();
  14812. }
  14813. }
  14814. }
  14815. }
  14816. if (!Val) {
  14817. if (Enum->isDependentType())
  14818. EltTy = Context.DependentTy;
  14819. else if (!LastEnumConst) {
  14820. // C++0x [dcl.enum]p5:
  14821. // If the underlying type is not fixed, the type of each enumerator
  14822. // is the type of its initializing value:
  14823. // - If no initializer is specified for the first enumerator, the
  14824. // initializing value has an unspecified integral type.
  14825. //
  14826. // GCC uses 'int' for its unspecified integral type, as does
  14827. // C99 6.7.2.2p3.
  14828. if (Enum->isFixed()) {
  14829. EltTy = Enum->getIntegerType();
  14830. }
  14831. else {
  14832. EltTy = Context.IntTy;
  14833. }
  14834. } else {
  14835. // Assign the last value + 1.
  14836. EnumVal = LastEnumConst->getInitVal();
  14837. ++EnumVal;
  14838. EltTy = LastEnumConst->getType();
  14839. // Check for overflow on increment.
  14840. if (EnumVal < LastEnumConst->getInitVal()) {
  14841. // C++0x [dcl.enum]p5:
  14842. // If the underlying type is not fixed, the type of each enumerator
  14843. // is the type of its initializing value:
  14844. //
  14845. // - Otherwise the type of the initializing value is the same as
  14846. // the type of the initializing value of the preceding enumerator
  14847. // unless the incremented value is not representable in that type,
  14848. // in which case the type is an unspecified integral type
  14849. // sufficient to contain the incremented value. If no such type
  14850. // exists, the program is ill-formed.
  14851. QualType T = getNextLargerIntegralType(Context, EltTy);
  14852. if (T.isNull() || Enum->isFixed()) {
  14853. // There is no integral type larger enough to represent this
  14854. // value. Complain, then allow the value to wrap around.
  14855. EnumVal = LastEnumConst->getInitVal();
  14856. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  14857. ++EnumVal;
  14858. if (Enum->isFixed())
  14859. // When the underlying type is fixed, this is ill-formed.
  14860. Diag(IdLoc, diag::err_enumerator_wrapped)
  14861. << EnumVal.toString(10)
  14862. << EltTy;
  14863. else
  14864. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  14865. << EnumVal.toString(10);
  14866. } else {
  14867. EltTy = T;
  14868. }
  14869. // Retrieve the last enumerator's value, extent that type to the
  14870. // type that is supposed to be large enough to represent the incremented
  14871. // value, then increment.
  14872. EnumVal = LastEnumConst->getInitVal();
  14873. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  14874. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  14875. ++EnumVal;
  14876. // If we're not in C++, diagnose the overflow of enumerator values,
  14877. // which in C99 means that the enumerator value is not representable in
  14878. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  14879. // permits enumerator values that are representable in some larger
  14880. // integral type.
  14881. if (!getLangOpts().CPlusPlus && !T.isNull())
  14882. Diag(IdLoc, diag::warn_enum_value_overflow);
  14883. } else if (!getLangOpts().CPlusPlus &&
  14884. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14885. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  14886. Diag(IdLoc, diag::ext_enum_value_not_int)
  14887. << EnumVal.toString(10) << 1;
  14888. }
  14889. }
  14890. }
  14891. if (!EltTy->isDependentType()) {
  14892. // Make the enumerator value match the signedness and size of the
  14893. // enumerator's type.
  14894. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  14895. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  14896. }
  14897. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  14898. Val, EnumVal);
  14899. }
  14900. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  14901. SourceLocation IILoc) {
  14902. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  14903. !getLangOpts().CPlusPlus)
  14904. return SkipBodyInfo();
  14905. // We have an anonymous enum definition. Look up the first enumerator to
  14906. // determine if we should merge the definition with an existing one and
  14907. // skip the body.
  14908. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  14909. forRedeclarationInCurContext());
  14910. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  14911. if (!PrevECD)
  14912. return SkipBodyInfo();
  14913. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  14914. NamedDecl *Hidden;
  14915. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  14916. SkipBodyInfo Skip;
  14917. Skip.Previous = Hidden;
  14918. return Skip;
  14919. }
  14920. return SkipBodyInfo();
  14921. }
  14922. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  14923. SourceLocation IdLoc, IdentifierInfo *Id,
  14924. const ParsedAttributesView &Attrs,
  14925. SourceLocation EqualLoc, Expr *Val) {
  14926. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  14927. EnumConstantDecl *LastEnumConst =
  14928. cast_or_null<EnumConstantDecl>(lastEnumConst);
  14929. // The scope passed in may not be a decl scope. Zip up the scope tree until
  14930. // we find one that is.
  14931. S = getNonFieldDeclScope(S);
  14932. // Verify that there isn't already something declared with this name in this
  14933. // scope.
  14934. LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
  14935. LookupName(R, S);
  14936. NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
  14937. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  14938. // Maybe we will complain about the shadowed template parameter.
  14939. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  14940. // Just pretend that we didn't see the previous declaration.
  14941. PrevDecl = nullptr;
  14942. }
  14943. // C++ [class.mem]p15:
  14944. // If T is the name of a class, then each of the following shall have a name
  14945. // different from T:
  14946. // - every enumerator of every member of class T that is an unscoped
  14947. // enumerated type
  14948. if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
  14949. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  14950. DeclarationNameInfo(Id, IdLoc));
  14951. EnumConstantDecl *New =
  14952. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  14953. if (!New)
  14954. return nullptr;
  14955. if (PrevDecl) {
  14956. if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
  14957. // Check for other kinds of shadowing not already handled.
  14958. CheckShadow(New, PrevDecl, R);
  14959. }
  14960. // When in C++, we may get a TagDecl with the same name; in this case the
  14961. // enum constant will 'hide' the tag.
  14962. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  14963. "Received TagDecl when not in C++!");
  14964. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  14965. if (isa<EnumConstantDecl>(PrevDecl))
  14966. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  14967. else
  14968. Diag(IdLoc, diag::err_redefinition) << Id;
  14969. notePreviousDefinition(PrevDecl, IdLoc);
  14970. return nullptr;
  14971. }
  14972. }
  14973. // Process attributes.
  14974. ProcessDeclAttributeList(S, New, Attrs);
  14975. AddPragmaAttributes(S, New);
  14976. // Register this decl in the current scope stack.
  14977. New->setAccess(TheEnumDecl->getAccess());
  14978. PushOnScopeChains(New, S);
  14979. ActOnDocumentableDecl(New);
  14980. return New;
  14981. }
  14982. // Returns true when the enum initial expression does not trigger the
  14983. // duplicate enum warning. A few common cases are exempted as follows:
  14984. // Element2 = Element1
  14985. // Element2 = Element1 + 1
  14986. // Element2 = Element1 - 1
  14987. // Where Element2 and Element1 are from the same enum.
  14988. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  14989. Expr *InitExpr = ECD->getInitExpr();
  14990. if (!InitExpr)
  14991. return true;
  14992. InitExpr = InitExpr->IgnoreImpCasts();
  14993. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  14994. if (!BO->isAdditiveOp())
  14995. return true;
  14996. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  14997. if (!IL)
  14998. return true;
  14999. if (IL->getValue() != 1)
  15000. return true;
  15001. InitExpr = BO->getLHS();
  15002. }
  15003. // This checks if the elements are from the same enum.
  15004. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  15005. if (!DRE)
  15006. return true;
  15007. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  15008. if (!EnumConstant)
  15009. return true;
  15010. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  15011. Enum)
  15012. return true;
  15013. return false;
  15014. }
  15015. // Emits a warning when an element is implicitly set a value that
  15016. // a previous element has already been set to.
  15017. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  15018. EnumDecl *Enum, QualType EnumType) {
  15019. // Avoid anonymous enums
  15020. if (!Enum->getIdentifier())
  15021. return;
  15022. // Only check for small enums.
  15023. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  15024. return;
  15025. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  15026. return;
  15027. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  15028. typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
  15029. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  15030. typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
  15031. // Use int64_t as a key to avoid needing special handling for DenseMap keys.
  15032. auto EnumConstantToKey = [](const EnumConstantDecl *D) {
  15033. llvm::APSInt Val = D->getInitVal();
  15034. return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
  15035. };
  15036. DuplicatesVector DupVector;
  15037. ValueToVectorMap EnumMap;
  15038. // Populate the EnumMap with all values represented by enum constants without
  15039. // an initializer.
  15040. for (auto *Element : Elements) {
  15041. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
  15042. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  15043. // this constant. Skip this enum since it may be ill-formed.
  15044. if (!ECD) {
  15045. return;
  15046. }
  15047. // Constants with initalizers are handled in the next loop.
  15048. if (ECD->getInitExpr())
  15049. continue;
  15050. // Duplicate values are handled in the next loop.
  15051. EnumMap.insert({EnumConstantToKey(ECD), ECD});
  15052. }
  15053. if (EnumMap.size() == 0)
  15054. return;
  15055. // Create vectors for any values that has duplicates.
  15056. for (auto *Element : Elements) {
  15057. // The last loop returned if any constant was null.
  15058. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
  15059. if (!ValidDuplicateEnum(ECD, Enum))
  15060. continue;
  15061. auto Iter = EnumMap.find(EnumConstantToKey(ECD));
  15062. if (Iter == EnumMap.end())
  15063. continue;
  15064. DeclOrVector& Entry = Iter->second;
  15065. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  15066. // Ensure constants are different.
  15067. if (D == ECD)
  15068. continue;
  15069. // Create new vector and push values onto it.
  15070. auto Vec = llvm::make_unique<ECDVector>();
  15071. Vec->push_back(D);
  15072. Vec->push_back(ECD);
  15073. // Update entry to point to the duplicates vector.
  15074. Entry = Vec.get();
  15075. // Store the vector somewhere we can consult later for quick emission of
  15076. // diagnostics.
  15077. DupVector.emplace_back(std::move(Vec));
  15078. continue;
  15079. }
  15080. ECDVector *Vec = Entry.get<ECDVector*>();
  15081. // Make sure constants are not added more than once.
  15082. if (*Vec->begin() == ECD)
  15083. continue;
  15084. Vec->push_back(ECD);
  15085. }
  15086. // Emit diagnostics.
  15087. for (const auto &Vec : DupVector) {
  15088. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  15089. // Emit warning for one enum constant.
  15090. auto *FirstECD = Vec->front();
  15091. S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
  15092. << FirstECD << FirstECD->getInitVal().toString(10)
  15093. << FirstECD->getSourceRange();
  15094. // Emit one note for each of the remaining enum constants with
  15095. // the same value.
  15096. for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
  15097. S.Diag(ECD->getLocation(), diag::note_duplicate_element)
  15098. << ECD << ECD->getInitVal().toString(10)
  15099. << ECD->getSourceRange();
  15100. }
  15101. }
  15102. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  15103. bool AllowMask) const {
  15104. assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
  15105. assert(ED->isCompleteDefinition() && "expected enum definition");
  15106. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  15107. llvm::APInt &FlagBits = R.first->second;
  15108. if (R.second) {
  15109. for (auto *E : ED->enumerators()) {
  15110. const auto &EVal = E->getInitVal();
  15111. // Only single-bit enumerators introduce new flag values.
  15112. if (EVal.isPowerOf2())
  15113. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  15114. }
  15115. }
  15116. // A value is in a flag enum if either its bits are a subset of the enum's
  15117. // flag bits (the first condition) or we are allowing masks and the same is
  15118. // true of its complement (the second condition). When masks are allowed, we
  15119. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  15120. //
  15121. // While it's true that any value could be used as a mask, the assumption is
  15122. // that a mask will have all of the insignificant bits set. Anything else is
  15123. // likely a logic error.
  15124. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  15125. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  15126. }
  15127. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  15128. Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
  15129. const ParsedAttributesView &Attrs) {
  15130. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  15131. QualType EnumType = Context.getTypeDeclType(Enum);
  15132. ProcessDeclAttributeList(S, Enum, Attrs);
  15133. if (Enum->isDependentType()) {
  15134. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  15135. EnumConstantDecl *ECD =
  15136. cast_or_null<EnumConstantDecl>(Elements[i]);
  15137. if (!ECD) continue;
  15138. ECD->setType(EnumType);
  15139. }
  15140. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  15141. return;
  15142. }
  15143. // TODO: If the result value doesn't fit in an int, it must be a long or long
  15144. // long value. ISO C does not support this, but GCC does as an extension,
  15145. // emit a warning.
  15146. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  15147. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  15148. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  15149. // Verify that all the values are okay, compute the size of the values, and
  15150. // reverse the list.
  15151. unsigned NumNegativeBits = 0;
  15152. unsigned NumPositiveBits = 0;
  15153. // Keep track of whether all elements have type int.
  15154. bool AllElementsInt = true;
  15155. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  15156. EnumConstantDecl *ECD =
  15157. cast_or_null<EnumConstantDecl>(Elements[i]);
  15158. if (!ECD) continue; // Already issued a diagnostic.
  15159. const llvm::APSInt &InitVal = ECD->getInitVal();
  15160. // Keep track of the size of positive and negative values.
  15161. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  15162. NumPositiveBits = std::max(NumPositiveBits,
  15163. (unsigned)InitVal.getActiveBits());
  15164. else
  15165. NumNegativeBits = std::max(NumNegativeBits,
  15166. (unsigned)InitVal.getMinSignedBits());
  15167. // Keep track of whether every enum element has type int (very common).
  15168. if (AllElementsInt)
  15169. AllElementsInt = ECD->getType() == Context.IntTy;
  15170. }
  15171. // Figure out the type that should be used for this enum.
  15172. QualType BestType;
  15173. unsigned BestWidth;
  15174. // C++0x N3000 [conv.prom]p3:
  15175. // An rvalue of an unscoped enumeration type whose underlying
  15176. // type is not fixed can be converted to an rvalue of the first
  15177. // of the following types that can represent all the values of
  15178. // the enumeration: int, unsigned int, long int, unsigned long
  15179. // int, long long int, or unsigned long long int.
  15180. // C99 6.4.4.3p2:
  15181. // An identifier declared as an enumeration constant has type int.
  15182. // The C99 rule is modified by a gcc extension
  15183. QualType BestPromotionType;
  15184. bool Packed = Enum->hasAttr<PackedAttr>();
  15185. // -fshort-enums is the equivalent to specifying the packed attribute on all
  15186. // enum definitions.
  15187. if (LangOpts.ShortEnums)
  15188. Packed = true;
  15189. // If the enum already has a type because it is fixed or dictated by the
  15190. // target, promote that type instead of analyzing the enumerators.
  15191. if (Enum->isComplete()) {
  15192. BestType = Enum->getIntegerType();
  15193. if (BestType->isPromotableIntegerType())
  15194. BestPromotionType = Context.getPromotedIntegerType(BestType);
  15195. else
  15196. BestPromotionType = BestType;
  15197. BestWidth = Context.getIntWidth(BestType);
  15198. }
  15199. else if (NumNegativeBits) {
  15200. // If there is a negative value, figure out the smallest integer type (of
  15201. // int/long/longlong) that fits.
  15202. // If it's packed, check also if it fits a char or a short.
  15203. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  15204. BestType = Context.SignedCharTy;
  15205. BestWidth = CharWidth;
  15206. } else if (Packed && NumNegativeBits <= ShortWidth &&
  15207. NumPositiveBits < ShortWidth) {
  15208. BestType = Context.ShortTy;
  15209. BestWidth = ShortWidth;
  15210. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  15211. BestType = Context.IntTy;
  15212. BestWidth = IntWidth;
  15213. } else {
  15214. BestWidth = Context.getTargetInfo().getLongWidth();
  15215. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  15216. BestType = Context.LongTy;
  15217. } else {
  15218. BestWidth = Context.getTargetInfo().getLongLongWidth();
  15219. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  15220. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  15221. BestType = Context.LongLongTy;
  15222. }
  15223. }
  15224. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  15225. } else {
  15226. // If there is no negative value, figure out the smallest type that fits
  15227. // all of the enumerator values.
  15228. // If it's packed, check also if it fits a char or a short.
  15229. if (Packed && NumPositiveBits <= CharWidth) {
  15230. BestType = Context.UnsignedCharTy;
  15231. BestPromotionType = Context.IntTy;
  15232. BestWidth = CharWidth;
  15233. } else if (Packed && NumPositiveBits <= ShortWidth) {
  15234. BestType = Context.UnsignedShortTy;
  15235. BestPromotionType = Context.IntTy;
  15236. BestWidth = ShortWidth;
  15237. } else if (NumPositiveBits <= IntWidth) {
  15238. BestType = Context.UnsignedIntTy;
  15239. BestWidth = IntWidth;
  15240. BestPromotionType
  15241. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15242. ? Context.UnsignedIntTy : Context.IntTy;
  15243. } else if (NumPositiveBits <=
  15244. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  15245. BestType = Context.UnsignedLongTy;
  15246. BestPromotionType
  15247. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15248. ? Context.UnsignedLongTy : Context.LongTy;
  15249. } else {
  15250. BestWidth = Context.getTargetInfo().getLongLongWidth();
  15251. assert(NumPositiveBits <= BestWidth &&
  15252. "How could an initializer get larger than ULL?");
  15253. BestType = Context.UnsignedLongLongTy;
  15254. BestPromotionType
  15255. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15256. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  15257. }
  15258. }
  15259. // Loop over all of the enumerator constants, changing their types to match
  15260. // the type of the enum if needed.
  15261. for (auto *D : Elements) {
  15262. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  15263. if (!ECD) continue; // Already issued a diagnostic.
  15264. // Standard C says the enumerators have int type, but we allow, as an
  15265. // extension, the enumerators to be larger than int size. If each
  15266. // enumerator value fits in an int, type it as an int, otherwise type it the
  15267. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  15268. // that X has type 'int', not 'unsigned'.
  15269. // Determine whether the value fits into an int.
  15270. llvm::APSInt InitVal = ECD->getInitVal();
  15271. // If it fits into an integer type, force it. Otherwise force it to match
  15272. // the enum decl type.
  15273. QualType NewTy;
  15274. unsigned NewWidth;
  15275. bool NewSign;
  15276. if (!getLangOpts().CPlusPlus &&
  15277. !Enum->isFixed() &&
  15278. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  15279. NewTy = Context.IntTy;
  15280. NewWidth = IntWidth;
  15281. NewSign = true;
  15282. } else if (ECD->getType() == BestType) {
  15283. // Already the right type!
  15284. if (getLangOpts().CPlusPlus)
  15285. // C++ [dcl.enum]p4: Following the closing brace of an
  15286. // enum-specifier, each enumerator has the type of its
  15287. // enumeration.
  15288. ECD->setType(EnumType);
  15289. continue;
  15290. } else {
  15291. NewTy = BestType;
  15292. NewWidth = BestWidth;
  15293. NewSign = BestType->isSignedIntegerOrEnumerationType();
  15294. }
  15295. // Adjust the APSInt value.
  15296. InitVal = InitVal.extOrTrunc(NewWidth);
  15297. InitVal.setIsSigned(NewSign);
  15298. ECD->setInitVal(InitVal);
  15299. // Adjust the Expr initializer and type.
  15300. if (ECD->getInitExpr() &&
  15301. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  15302. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  15303. CK_IntegralCast,
  15304. ECD->getInitExpr(),
  15305. /*base paths*/ nullptr,
  15306. VK_RValue));
  15307. if (getLangOpts().CPlusPlus)
  15308. // C++ [dcl.enum]p4: Following the closing brace of an
  15309. // enum-specifier, each enumerator has the type of its
  15310. // enumeration.
  15311. ECD->setType(EnumType);
  15312. else
  15313. ECD->setType(NewTy);
  15314. }
  15315. Enum->completeDefinition(BestType, BestPromotionType,
  15316. NumPositiveBits, NumNegativeBits);
  15317. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  15318. if (Enum->isClosedFlag()) {
  15319. for (Decl *D : Elements) {
  15320. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  15321. if (!ECD) continue; // Already issued a diagnostic.
  15322. llvm::APSInt InitVal = ECD->getInitVal();
  15323. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  15324. !IsValueInFlagEnum(Enum, InitVal, true))
  15325. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  15326. << ECD << Enum;
  15327. }
  15328. }
  15329. // Now that the enum type is defined, ensure it's not been underaligned.
  15330. if (Enum->hasAttrs())
  15331. CheckAlignasUnderalignment(Enum);
  15332. }
  15333. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  15334. SourceLocation StartLoc,
  15335. SourceLocation EndLoc) {
  15336. StringLiteral *AsmString = cast<StringLiteral>(expr);
  15337. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  15338. AsmString, StartLoc,
  15339. EndLoc);
  15340. CurContext->addDecl(New);
  15341. return New;
  15342. }
  15343. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  15344. IdentifierInfo* AliasName,
  15345. SourceLocation PragmaLoc,
  15346. SourceLocation NameLoc,
  15347. SourceLocation AliasNameLoc) {
  15348. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  15349. LookupOrdinaryName);
  15350. AsmLabelAttr *Attr =
  15351. AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
  15352. // If a declaration that:
  15353. // 1) declares a function or a variable
  15354. // 2) has external linkage
  15355. // already exists, add a label attribute to it.
  15356. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15357. if (isDeclExternC(PrevDecl))
  15358. PrevDecl->addAttr(Attr);
  15359. else
  15360. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  15361. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  15362. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  15363. } else
  15364. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  15365. }
  15366. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  15367. SourceLocation PragmaLoc,
  15368. SourceLocation NameLoc) {
  15369. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  15370. if (PrevDecl) {
  15371. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  15372. } else {
  15373. (void)WeakUndeclaredIdentifiers.insert(
  15374. std::pair<IdentifierInfo*,WeakInfo>
  15375. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  15376. }
  15377. }
  15378. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  15379. IdentifierInfo* AliasName,
  15380. SourceLocation PragmaLoc,
  15381. SourceLocation NameLoc,
  15382. SourceLocation AliasNameLoc) {
  15383. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  15384. LookupOrdinaryName);
  15385. WeakInfo W = WeakInfo(Name, NameLoc);
  15386. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15387. if (!PrevDecl->hasAttr<AliasAttr>())
  15388. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  15389. DeclApplyPragmaWeak(TUScope, ND, W);
  15390. } else {
  15391. (void)WeakUndeclaredIdentifiers.insert(
  15392. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  15393. }
  15394. }
  15395. Decl *Sema::getObjCDeclContext() const {
  15396. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  15397. }