SemaDecl.cpp 664 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115
  1. //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for declarations.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TypeLocBuilder.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/CommentDiagnostic.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/EvaluatedExprVisitor.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/StmtCXX.h"
  25. #include "clang/Basic/Builtins.h"
  26. #include "clang/Basic/PartialDiagnostic.h"
  27. #include "clang/Basic/SourceManager.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  30. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  31. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  32. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  33. #include "clang/Sema/CXXFieldCollector.h"
  34. #include "clang/Sema/DeclSpec.h"
  35. #include "clang/Sema/DelayedDiagnostic.h"
  36. #include "clang/Sema/Initialization.h"
  37. #include "clang/Sema/Lookup.h"
  38. #include "clang/Sema/ParsedTemplate.h"
  39. #include "clang/Sema/Scope.h"
  40. #include "clang/Sema/ScopeInfo.h"
  41. #include "clang/Sema/SemaInternal.h"
  42. #include "clang/Sema/Template.h"
  43. #include "llvm/ADT/SmallString.h"
  44. #include "llvm/ADT/Triple.h"
  45. #include <algorithm>
  46. #include <cstring>
  47. #include <functional>
  48. using namespace clang;
  49. using namespace sema;
  50. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  51. if (OwnedType) {
  52. Decl *Group[2] = { OwnedType, Ptr };
  53. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  54. }
  55. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  56. }
  57. namespace {
  58. class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
  59. public:
  60. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
  61. bool AllowTemplates = false,
  62. bool AllowNonTemplates = true)
  63. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  64. AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
  65. WantExpressionKeywords = false;
  66. WantCXXNamedCasts = false;
  67. WantRemainingKeywords = false;
  68. }
  69. bool ValidateCandidate(const TypoCorrection &candidate) override {
  70. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  71. if (!AllowInvalidDecl && ND->isInvalidDecl())
  72. return false;
  73. if (getAsTypeTemplateDecl(ND))
  74. return AllowTemplates;
  75. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  76. if (!IsType)
  77. return false;
  78. if (AllowNonTemplates)
  79. return true;
  80. // An injected-class-name of a class template (specialization) is valid
  81. // as a template or as a non-template.
  82. if (AllowTemplates) {
  83. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  84. if (!RD || !RD->isInjectedClassName())
  85. return false;
  86. RD = cast<CXXRecordDecl>(RD->getDeclContext());
  87. return RD->getDescribedClassTemplate() ||
  88. isa<ClassTemplateSpecializationDecl>(RD);
  89. }
  90. return false;
  91. }
  92. return !WantClassName && candidate.isKeyword();
  93. }
  94. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  95. return llvm::make_unique<TypeNameValidatorCCC>(*this);
  96. }
  97. private:
  98. bool AllowInvalidDecl;
  99. bool WantClassName;
  100. bool AllowTemplates;
  101. bool AllowNonTemplates;
  102. };
  103. } // end anonymous namespace
  104. /// Determine whether the token kind starts a simple-type-specifier.
  105. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  106. switch (Kind) {
  107. // FIXME: Take into account the current language when deciding whether a
  108. // token kind is a valid type specifier
  109. case tok::kw_short:
  110. case tok::kw_long:
  111. case tok::kw___int64:
  112. case tok::kw___int128:
  113. case tok::kw_signed:
  114. case tok::kw_unsigned:
  115. case tok::kw_void:
  116. case tok::kw_char:
  117. case tok::kw_int:
  118. case tok::kw_half:
  119. case tok::kw_float:
  120. case tok::kw_double:
  121. case tok::kw__Float16:
  122. case tok::kw___float128:
  123. case tok::kw_wchar_t:
  124. case tok::kw_bool:
  125. case tok::kw___underlying_type:
  126. case tok::kw___auto_type:
  127. return true;
  128. case tok::annot_typename:
  129. case tok::kw_char16_t:
  130. case tok::kw_char32_t:
  131. case tok::kw_typeof:
  132. case tok::annot_decltype:
  133. case tok::kw_decltype:
  134. return getLangOpts().CPlusPlus;
  135. case tok::kw_char8_t:
  136. return getLangOpts().Char8;
  137. default:
  138. break;
  139. }
  140. return false;
  141. }
  142. namespace {
  143. enum class UnqualifiedTypeNameLookupResult {
  144. NotFound,
  145. FoundNonType,
  146. FoundType
  147. };
  148. } // end anonymous namespace
  149. /// Tries to perform unqualified lookup of the type decls in bases for
  150. /// dependent class.
  151. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  152. /// type decl, \a FoundType if only type decls are found.
  153. static UnqualifiedTypeNameLookupResult
  154. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  155. SourceLocation NameLoc,
  156. const CXXRecordDecl *RD) {
  157. if (!RD->hasDefinition())
  158. return UnqualifiedTypeNameLookupResult::NotFound;
  159. // Look for type decls in base classes.
  160. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  161. UnqualifiedTypeNameLookupResult::NotFound;
  162. for (const auto &Base : RD->bases()) {
  163. const CXXRecordDecl *BaseRD = nullptr;
  164. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  165. BaseRD = BaseTT->getAsCXXRecordDecl();
  166. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  167. // Look for type decls in dependent base classes that have known primary
  168. // templates.
  169. if (!TST || !TST->isDependentType())
  170. continue;
  171. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  172. if (!TD)
  173. continue;
  174. if (auto *BasePrimaryTemplate =
  175. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
  176. if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
  177. BaseRD = BasePrimaryTemplate;
  178. else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
  179. if (const ClassTemplatePartialSpecializationDecl *PS =
  180. CTD->findPartialSpecialization(Base.getType()))
  181. if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
  182. BaseRD = PS;
  183. }
  184. }
  185. }
  186. if (BaseRD) {
  187. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  188. if (!isa<TypeDecl>(ND))
  189. return UnqualifiedTypeNameLookupResult::FoundNonType;
  190. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  191. }
  192. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  193. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  194. case UnqualifiedTypeNameLookupResult::FoundNonType:
  195. return UnqualifiedTypeNameLookupResult::FoundNonType;
  196. case UnqualifiedTypeNameLookupResult::FoundType:
  197. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  198. break;
  199. case UnqualifiedTypeNameLookupResult::NotFound:
  200. break;
  201. }
  202. }
  203. }
  204. }
  205. return FoundTypeDecl;
  206. }
  207. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  208. const IdentifierInfo &II,
  209. SourceLocation NameLoc) {
  210. // Lookup in the parent class template context, if any.
  211. const CXXRecordDecl *RD = nullptr;
  212. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  213. UnqualifiedTypeNameLookupResult::NotFound;
  214. for (DeclContext *DC = S.CurContext;
  215. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  216. DC = DC->getParent()) {
  217. // Look for type decls in dependent base classes that have known primary
  218. // templates.
  219. RD = dyn_cast<CXXRecordDecl>(DC);
  220. if (RD && RD->getDescribedClassTemplate())
  221. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  222. }
  223. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  224. return nullptr;
  225. // We found some types in dependent base classes. Recover as if the user
  226. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  227. // lookup during template instantiation.
  228. S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
  229. ASTContext &Context = S.Context;
  230. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  231. cast<Type>(Context.getRecordType(RD)));
  232. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  233. CXXScopeSpec SS;
  234. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  235. TypeLocBuilder Builder;
  236. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  237. DepTL.setNameLoc(NameLoc);
  238. DepTL.setElaboratedKeywordLoc(SourceLocation());
  239. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  240. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  241. }
  242. /// If the identifier refers to a type name within this scope,
  243. /// return the declaration of that type.
  244. ///
  245. /// This routine performs ordinary name lookup of the identifier II
  246. /// within the given scope, with optional C++ scope specifier SS, to
  247. /// determine whether the name refers to a type. If so, returns an
  248. /// opaque pointer (actually a QualType) corresponding to that
  249. /// type. Otherwise, returns NULL.
  250. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  251. Scope *S, CXXScopeSpec *SS,
  252. bool isClassName, bool HasTrailingDot,
  253. ParsedType ObjectTypePtr,
  254. bool IsCtorOrDtorName,
  255. bool WantNontrivialTypeSourceInfo,
  256. bool IsClassTemplateDeductionContext,
  257. IdentifierInfo **CorrectedII) {
  258. // FIXME: Consider allowing this outside C++1z mode as an extension.
  259. bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
  260. getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
  261. !isClassName && !HasTrailingDot;
  262. // Determine where we will perform name lookup.
  263. DeclContext *LookupCtx = nullptr;
  264. if (ObjectTypePtr) {
  265. QualType ObjectType = ObjectTypePtr.get();
  266. if (ObjectType->isRecordType())
  267. LookupCtx = computeDeclContext(ObjectType);
  268. } else if (SS && SS->isNotEmpty()) {
  269. LookupCtx = computeDeclContext(*SS, false);
  270. if (!LookupCtx) {
  271. if (isDependentScopeSpecifier(*SS)) {
  272. // C++ [temp.res]p3:
  273. // A qualified-id that refers to a type and in which the
  274. // nested-name-specifier depends on a template-parameter (14.6.2)
  275. // shall be prefixed by the keyword typename to indicate that the
  276. // qualified-id denotes a type, forming an
  277. // elaborated-type-specifier (7.1.5.3).
  278. //
  279. // We therefore do not perform any name lookup if the result would
  280. // refer to a member of an unknown specialization.
  281. if (!isClassName && !IsCtorOrDtorName)
  282. return nullptr;
  283. // We know from the grammar that this name refers to a type,
  284. // so build a dependent node to describe the type.
  285. if (WantNontrivialTypeSourceInfo)
  286. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  287. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  288. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  289. II, NameLoc);
  290. return ParsedType::make(T);
  291. }
  292. return nullptr;
  293. }
  294. if (!LookupCtx->isDependentContext() &&
  295. RequireCompleteDeclContext(*SS, LookupCtx))
  296. return nullptr;
  297. }
  298. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  299. // lookup for class-names.
  300. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  301. LookupOrdinaryName;
  302. LookupResult Result(*this, &II, NameLoc, Kind);
  303. if (LookupCtx) {
  304. // Perform "qualified" name lookup into the declaration context we
  305. // computed, which is either the type of the base of a member access
  306. // expression or the declaration context associated with a prior
  307. // nested-name-specifier.
  308. LookupQualifiedName(Result, LookupCtx);
  309. if (ObjectTypePtr && Result.empty()) {
  310. // C++ [basic.lookup.classref]p3:
  311. // If the unqualified-id is ~type-name, the type-name is looked up
  312. // in the context of the entire postfix-expression. If the type T of
  313. // the object expression is of a class type C, the type-name is also
  314. // looked up in the scope of class C. At least one of the lookups shall
  315. // find a name that refers to (possibly cv-qualified) T.
  316. LookupName(Result, S);
  317. }
  318. } else {
  319. // Perform unqualified name lookup.
  320. LookupName(Result, S);
  321. // For unqualified lookup in a class template in MSVC mode, look into
  322. // dependent base classes where the primary class template is known.
  323. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  324. if (ParsedType TypeInBase =
  325. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  326. return TypeInBase;
  327. }
  328. }
  329. NamedDecl *IIDecl = nullptr;
  330. switch (Result.getResultKind()) {
  331. case LookupResult::NotFound:
  332. case LookupResult::NotFoundInCurrentInstantiation:
  333. if (CorrectedII) {
  334. TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
  335. AllowDeducedTemplate);
  336. TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
  337. S, SS, CCC, CTK_ErrorRecovery);
  338. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  339. TemplateTy Template;
  340. bool MemberOfUnknownSpecialization;
  341. UnqualifiedId TemplateName;
  342. TemplateName.setIdentifier(NewII, NameLoc);
  343. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  344. CXXScopeSpec NewSS, *NewSSPtr = SS;
  345. if (SS && NNS) {
  346. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  347. NewSSPtr = &NewSS;
  348. }
  349. if (Correction && (NNS || NewII != &II) &&
  350. // Ignore a correction to a template type as the to-be-corrected
  351. // identifier is not a template (typo correction for template names
  352. // is handled elsewhere).
  353. !(getLangOpts().CPlusPlus && NewSSPtr &&
  354. isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
  355. Template, MemberOfUnknownSpecialization))) {
  356. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  357. isClassName, HasTrailingDot, ObjectTypePtr,
  358. IsCtorOrDtorName,
  359. WantNontrivialTypeSourceInfo,
  360. IsClassTemplateDeductionContext);
  361. if (Ty) {
  362. diagnoseTypo(Correction,
  363. PDiag(diag::err_unknown_type_or_class_name_suggest)
  364. << Result.getLookupName() << isClassName);
  365. if (SS && NNS)
  366. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  367. *CorrectedII = NewII;
  368. return Ty;
  369. }
  370. }
  371. }
  372. // If typo correction failed or was not performed, fall through
  373. LLVM_FALLTHROUGH;
  374. case LookupResult::FoundOverloaded:
  375. case LookupResult::FoundUnresolvedValue:
  376. Result.suppressDiagnostics();
  377. return nullptr;
  378. case LookupResult::Ambiguous:
  379. // Recover from type-hiding ambiguities by hiding the type. We'll
  380. // do the lookup again when looking for an object, and we can
  381. // diagnose the error then. If we don't do this, then the error
  382. // about hiding the type will be immediately followed by an error
  383. // that only makes sense if the identifier was treated like a type.
  384. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  385. Result.suppressDiagnostics();
  386. return nullptr;
  387. }
  388. // Look to see if we have a type anywhere in the list of results.
  389. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  390. Res != ResEnd; ++Res) {
  391. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
  392. (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
  393. if (!IIDecl ||
  394. (*Res)->getLocation().getRawEncoding() <
  395. IIDecl->getLocation().getRawEncoding())
  396. IIDecl = *Res;
  397. }
  398. }
  399. if (!IIDecl) {
  400. // None of the entities we found is a type, so there is no way
  401. // to even assume that the result is a type. In this case, don't
  402. // complain about the ambiguity. The parser will either try to
  403. // perform this lookup again (e.g., as an object name), which
  404. // will produce the ambiguity, or will complain that it expected
  405. // a type name.
  406. Result.suppressDiagnostics();
  407. return nullptr;
  408. }
  409. // We found a type within the ambiguous lookup; diagnose the
  410. // ambiguity and then return that type. This might be the right
  411. // answer, or it might not be, but it suppresses any attempt to
  412. // perform the name lookup again.
  413. break;
  414. case LookupResult::Found:
  415. IIDecl = Result.getFoundDecl();
  416. break;
  417. }
  418. assert(IIDecl && "Didn't find decl");
  419. QualType T;
  420. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  421. // C++ [class.qual]p2: A lookup that would find the injected-class-name
  422. // instead names the constructors of the class, except when naming a class.
  423. // This is ill-formed when we're not actually forming a ctor or dtor name.
  424. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  425. auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
  426. if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
  427. FoundRD->isInjectedClassName() &&
  428. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  429. Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
  430. << &II << /*Type*/1;
  431. DiagnoseUseOfDecl(IIDecl, NameLoc);
  432. T = Context.getTypeDeclType(TD);
  433. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  434. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  435. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  436. if (!HasTrailingDot)
  437. T = Context.getObjCInterfaceType(IDecl);
  438. } else if (AllowDeducedTemplate) {
  439. if (auto *TD = getAsTypeTemplateDecl(IIDecl))
  440. T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  441. QualType(), false);
  442. }
  443. if (T.isNull()) {
  444. // If it's not plausibly a type, suppress diagnostics.
  445. Result.suppressDiagnostics();
  446. return nullptr;
  447. }
  448. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  449. // constructor or destructor name (in such a case, the scope specifier
  450. // will be attached to the enclosing Expr or Decl node).
  451. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
  452. !isa<ObjCInterfaceDecl>(IIDecl)) {
  453. if (WantNontrivialTypeSourceInfo) {
  454. // Construct a type with type-source information.
  455. TypeLocBuilder Builder;
  456. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  457. T = getElaboratedType(ETK_None, *SS, T);
  458. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  459. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  460. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  461. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  462. } else {
  463. T = getElaboratedType(ETK_None, *SS, T);
  464. }
  465. }
  466. return ParsedType::make(T);
  467. }
  468. // Builds a fake NNS for the given decl context.
  469. static NestedNameSpecifier *
  470. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  471. for (;; DC = DC->getLookupParent()) {
  472. DC = DC->getPrimaryContext();
  473. auto *ND = dyn_cast<NamespaceDecl>(DC);
  474. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  475. return NestedNameSpecifier::Create(Context, nullptr, ND);
  476. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  477. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  478. RD->getTypeForDecl());
  479. else if (isa<TranslationUnitDecl>(DC))
  480. return NestedNameSpecifier::GlobalSpecifier(Context);
  481. }
  482. llvm_unreachable("something isn't in TU scope?");
  483. }
  484. /// Find the parent class with dependent bases of the innermost enclosing method
  485. /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
  486. /// up allowing unqualified dependent type names at class-level, which MSVC
  487. /// correctly rejects.
  488. static const CXXRecordDecl *
  489. findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
  490. for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
  491. DC = DC->getPrimaryContext();
  492. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  493. if (MD->getParent()->hasAnyDependentBases())
  494. return MD->getParent();
  495. }
  496. return nullptr;
  497. }
  498. ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
  499. SourceLocation NameLoc,
  500. bool IsTemplateTypeArg) {
  501. assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
  502. NestedNameSpecifier *NNS = nullptr;
  503. if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
  504. // If we weren't able to parse a default template argument, delay lookup
  505. // until instantiation time by making a non-dependent DependentTypeName. We
  506. // pretend we saw a NestedNameSpecifier referring to the current scope, and
  507. // lookup is retried.
  508. // FIXME: This hurts our diagnostic quality, since we get errors like "no
  509. // type named 'Foo' in 'current_namespace'" when the user didn't write any
  510. // name specifiers.
  511. NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  512. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  513. } else if (const CXXRecordDecl *RD =
  514. findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
  515. // Build a DependentNameType that will perform lookup into RD at
  516. // instantiation time.
  517. NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  518. RD->getTypeForDecl());
  519. // Diagnose that this identifier was undeclared, and retry the lookup during
  520. // template instantiation.
  521. Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
  522. << RD;
  523. } else {
  524. // This is not a situation that we should recover from.
  525. return ParsedType();
  526. }
  527. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  528. // Build type location information. We synthesized the qualifier, so we have
  529. // to build a fake NestedNameSpecifierLoc.
  530. NestedNameSpecifierLocBuilder NNSLocBuilder;
  531. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  532. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  533. TypeLocBuilder Builder;
  534. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  535. DepTL.setNameLoc(NameLoc);
  536. DepTL.setElaboratedKeywordLoc(SourceLocation());
  537. DepTL.setQualifierLoc(QualifierLoc);
  538. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  539. }
  540. /// isTagName() - This method is called *for error recovery purposes only*
  541. /// to determine if the specified name is a valid tag name ("struct foo"). If
  542. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  543. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  544. /// cases in C where the user forgot to specify the tag.
  545. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  546. // Do a tag name lookup in this scope.
  547. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  548. LookupName(R, S, false);
  549. R.suppressDiagnostics();
  550. if (R.getResultKind() == LookupResult::Found)
  551. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  552. switch (TD->getTagKind()) {
  553. case TTK_Struct: return DeclSpec::TST_struct;
  554. case TTK_Interface: return DeclSpec::TST_interface;
  555. case TTK_Union: return DeclSpec::TST_union;
  556. case TTK_Class: return DeclSpec::TST_class;
  557. case TTK_Enum: return DeclSpec::TST_enum;
  558. }
  559. }
  560. return DeclSpec::TST_unspecified;
  561. }
  562. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  563. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  564. /// then downgrade the missing typename error to a warning.
  565. /// This is needed for MSVC compatibility; Example:
  566. /// @code
  567. /// template<class T> class A {
  568. /// public:
  569. /// typedef int TYPE;
  570. /// };
  571. /// template<class T> class B : public A<T> {
  572. /// public:
  573. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  574. /// };
  575. /// @endcode
  576. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  577. if (CurContext->isRecord()) {
  578. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  579. return true;
  580. const Type *Ty = SS->getScopeRep()->getAsType();
  581. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  582. for (const auto &Base : RD->bases())
  583. if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  584. return true;
  585. return S->isFunctionPrototypeScope();
  586. }
  587. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  588. }
  589. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  590. SourceLocation IILoc,
  591. Scope *S,
  592. CXXScopeSpec *SS,
  593. ParsedType &SuggestedType,
  594. bool IsTemplateName) {
  595. // Don't report typename errors for editor placeholders.
  596. if (II->isEditorPlaceholder())
  597. return;
  598. // We don't have anything to suggest (yet).
  599. SuggestedType = nullptr;
  600. // There may have been a typo in the name of the type. Look up typo
  601. // results, in case we have something that we can suggest.
  602. TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
  603. /*AllowTemplates=*/IsTemplateName,
  604. /*AllowNonTemplates=*/!IsTemplateName);
  605. if (TypoCorrection Corrected =
  606. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  607. CCC, CTK_ErrorRecovery)) {
  608. // FIXME: Support error recovery for the template-name case.
  609. bool CanRecover = !IsTemplateName;
  610. if (Corrected.isKeyword()) {
  611. // We corrected to a keyword.
  612. diagnoseTypo(Corrected,
  613. PDiag(IsTemplateName ? diag::err_no_template_suggest
  614. : diag::err_unknown_typename_suggest)
  615. << II);
  616. II = Corrected.getCorrectionAsIdentifierInfo();
  617. } else {
  618. // We found a similarly-named type or interface; suggest that.
  619. if (!SS || !SS->isSet()) {
  620. diagnoseTypo(Corrected,
  621. PDiag(IsTemplateName ? diag::err_no_template_suggest
  622. : diag::err_unknown_typename_suggest)
  623. << II, CanRecover);
  624. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  625. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  626. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  627. II->getName().equals(CorrectedStr);
  628. diagnoseTypo(Corrected,
  629. PDiag(IsTemplateName
  630. ? diag::err_no_member_template_suggest
  631. : diag::err_unknown_nested_typename_suggest)
  632. << II << DC << DroppedSpecifier << SS->getRange(),
  633. CanRecover);
  634. } else {
  635. llvm_unreachable("could not have corrected a typo here");
  636. }
  637. if (!CanRecover)
  638. return;
  639. CXXScopeSpec tmpSS;
  640. if (Corrected.getCorrectionSpecifier())
  641. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  642. SourceRange(IILoc));
  643. // FIXME: Support class template argument deduction here.
  644. SuggestedType =
  645. getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
  646. tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
  647. /*IsCtorOrDtorName=*/false,
  648. /*NonTrivialTypeSourceInfo=*/true);
  649. }
  650. return;
  651. }
  652. if (getLangOpts().CPlusPlus && !IsTemplateName) {
  653. // See if II is a class template that the user forgot to pass arguments to.
  654. UnqualifiedId Name;
  655. Name.setIdentifier(II, IILoc);
  656. CXXScopeSpec EmptySS;
  657. TemplateTy TemplateResult;
  658. bool MemberOfUnknownSpecialization;
  659. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  660. Name, nullptr, true, TemplateResult,
  661. MemberOfUnknownSpecialization) == TNK_Type_template) {
  662. diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
  663. return;
  664. }
  665. }
  666. // FIXME: Should we move the logic that tries to recover from a missing tag
  667. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  668. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  669. Diag(IILoc, IsTemplateName ? diag::err_no_template
  670. : diag::err_unknown_typename)
  671. << II;
  672. else if (DeclContext *DC = computeDeclContext(*SS, false))
  673. Diag(IILoc, IsTemplateName ? diag::err_no_member_template
  674. : diag::err_typename_nested_not_found)
  675. << II << DC << SS->getRange();
  676. else if (isDependentScopeSpecifier(*SS)) {
  677. unsigned DiagID = diag::err_typename_missing;
  678. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  679. DiagID = diag::ext_typename_missing;
  680. Diag(SS->getRange().getBegin(), DiagID)
  681. << SS->getScopeRep() << II->getName()
  682. << SourceRange(SS->getRange().getBegin(), IILoc)
  683. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  684. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  685. *SS, *II, IILoc).get();
  686. } else {
  687. assert(SS && SS->isInvalid() &&
  688. "Invalid scope specifier has already been diagnosed");
  689. }
  690. }
  691. /// Determine whether the given result set contains either a type name
  692. /// or
  693. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  694. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  695. NextToken.is(tok::less);
  696. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  697. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  698. return true;
  699. if (CheckTemplate && isa<TemplateDecl>(*I))
  700. return true;
  701. }
  702. return false;
  703. }
  704. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  705. Scope *S, CXXScopeSpec &SS,
  706. IdentifierInfo *&Name,
  707. SourceLocation NameLoc) {
  708. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  709. SemaRef.LookupParsedName(R, S, &SS);
  710. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  711. StringRef FixItTagName;
  712. switch (Tag->getTagKind()) {
  713. case TTK_Class:
  714. FixItTagName = "class ";
  715. break;
  716. case TTK_Enum:
  717. FixItTagName = "enum ";
  718. break;
  719. case TTK_Struct:
  720. FixItTagName = "struct ";
  721. break;
  722. case TTK_Interface:
  723. FixItTagName = "__interface ";
  724. break;
  725. case TTK_Union:
  726. FixItTagName = "union ";
  727. break;
  728. }
  729. StringRef TagName = FixItTagName.drop_back();
  730. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  731. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  732. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  733. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  734. I != IEnd; ++I)
  735. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  736. << Name << TagName;
  737. // Replace lookup results with just the tag decl.
  738. Result.clear(Sema::LookupTagName);
  739. SemaRef.LookupParsedName(Result, S, &SS);
  740. return true;
  741. }
  742. return false;
  743. }
  744. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  745. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  746. QualType T, SourceLocation NameLoc) {
  747. ASTContext &Context = S.Context;
  748. TypeLocBuilder Builder;
  749. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  750. T = S.getElaboratedType(ETK_None, SS, T);
  751. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  752. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  753. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  754. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  755. }
  756. Sema::NameClassification
  757. Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
  758. SourceLocation NameLoc, const Token &NextToken,
  759. bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) {
  760. DeclarationNameInfo NameInfo(Name, NameLoc);
  761. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  762. if (NextToken.is(tok::coloncolon)) {
  763. NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
  764. BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
  765. } else if (getLangOpts().CPlusPlus && SS.isSet() &&
  766. isCurrentClassName(*Name, S, &SS)) {
  767. // Per [class.qual]p2, this names the constructors of SS, not the
  768. // injected-class-name. We don't have a classification for that.
  769. // There's not much point caching this result, since the parser
  770. // will reject it later.
  771. return NameClassification::Unknown();
  772. }
  773. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  774. LookupParsedName(Result, S, &SS, !CurMethod);
  775. // For unqualified lookup in a class template in MSVC mode, look into
  776. // dependent base classes where the primary class template is known.
  777. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  778. if (ParsedType TypeInBase =
  779. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  780. return TypeInBase;
  781. }
  782. // Perform lookup for Objective-C instance variables (including automatically
  783. // synthesized instance variables), if we're in an Objective-C method.
  784. // FIXME: This lookup really, really needs to be folded in to the normal
  785. // unqualified lookup mechanism.
  786. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  787. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  788. if (E.get() || E.isInvalid())
  789. return E;
  790. }
  791. bool SecondTry = false;
  792. bool IsFilteredTemplateName = false;
  793. Corrected:
  794. switch (Result.getResultKind()) {
  795. case LookupResult::NotFound:
  796. // If an unqualified-id is followed by a '(', then we have a function
  797. // call.
  798. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  799. // In C++, this is an ADL-only call.
  800. // FIXME: Reference?
  801. if (getLangOpts().CPlusPlus)
  802. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  803. // C90 6.3.2.2:
  804. // If the expression that precedes the parenthesized argument list in a
  805. // function call consists solely of an identifier, and if no
  806. // declaration is visible for this identifier, the identifier is
  807. // implicitly declared exactly as if, in the innermost block containing
  808. // the function call, the declaration
  809. //
  810. // extern int identifier ();
  811. //
  812. // appeared.
  813. //
  814. // We also allow this in C99 as an extension.
  815. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  816. Result.addDecl(D);
  817. Result.resolveKind();
  818. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  819. }
  820. }
  821. if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
  822. // In C++20 onwards, this could be an ADL-only call to a function
  823. // template, and we're required to assume that this is a template name.
  824. //
  825. // FIXME: Find a way to still do typo correction in this case.
  826. TemplateName Template =
  827. Context.getAssumedTemplateName(NameInfo.getName());
  828. return NameClassification::UndeclaredTemplate(Template);
  829. }
  830. // In C, we first see whether there is a tag type by the same name, in
  831. // which case it's likely that the user just forgot to write "enum",
  832. // "struct", or "union".
  833. if (!getLangOpts().CPlusPlus && !SecondTry &&
  834. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  835. break;
  836. }
  837. // Perform typo correction to determine if there is another name that is
  838. // close to this name.
  839. if (!SecondTry && CCC) {
  840. SecondTry = true;
  841. if (TypoCorrection Corrected =
  842. CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
  843. &SS, *CCC, CTK_ErrorRecovery)) {
  844. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  845. unsigned QualifiedDiag = diag::err_no_member_suggest;
  846. NamedDecl *FirstDecl = Corrected.getFoundDecl();
  847. NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
  848. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  849. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  850. UnqualifiedDiag = diag::err_no_template_suggest;
  851. QualifiedDiag = diag::err_no_member_template_suggest;
  852. } else if (UnderlyingFirstDecl &&
  853. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  854. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  855. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  856. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  857. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  858. }
  859. if (SS.isEmpty()) {
  860. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  861. } else {// FIXME: is this even reachable? Test it.
  862. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  863. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  864. Name->getName().equals(CorrectedStr);
  865. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  866. << Name << computeDeclContext(SS, false)
  867. << DroppedSpecifier << SS.getRange());
  868. }
  869. // Update the name, so that the caller has the new name.
  870. Name = Corrected.getCorrectionAsIdentifierInfo();
  871. // Typo correction corrected to a keyword.
  872. if (Corrected.isKeyword())
  873. return Name;
  874. // Also update the LookupResult...
  875. // FIXME: This should probably go away at some point
  876. Result.clear();
  877. Result.setLookupName(Corrected.getCorrection());
  878. if (FirstDecl)
  879. Result.addDecl(FirstDecl);
  880. // If we found an Objective-C instance variable, let
  881. // LookupInObjCMethod build the appropriate expression to
  882. // reference the ivar.
  883. // FIXME: This is a gross hack.
  884. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  885. Result.clear();
  886. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  887. return E;
  888. }
  889. goto Corrected;
  890. }
  891. }
  892. // We failed to correct; just fall through and let the parser deal with it.
  893. Result.suppressDiagnostics();
  894. return NameClassification::Unknown();
  895. case LookupResult::NotFoundInCurrentInstantiation: {
  896. // We performed name lookup into the current instantiation, and there were
  897. // dependent bases, so we treat this result the same way as any other
  898. // dependent nested-name-specifier.
  899. // C++ [temp.res]p2:
  900. // A name used in a template declaration or definition and that is
  901. // dependent on a template-parameter is assumed not to name a type
  902. // unless the applicable name lookup finds a type name or the name is
  903. // qualified by the keyword typename.
  904. //
  905. // FIXME: If the next token is '<', we might want to ask the parser to
  906. // perform some heroics to see if we actually have a
  907. // template-argument-list, which would indicate a missing 'template'
  908. // keyword here.
  909. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  910. NameInfo, IsAddressOfOperand,
  911. /*TemplateArgs=*/nullptr);
  912. }
  913. case LookupResult::Found:
  914. case LookupResult::FoundOverloaded:
  915. case LookupResult::FoundUnresolvedValue:
  916. break;
  917. case LookupResult::Ambiguous:
  918. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  919. hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
  920. /*AllowDependent=*/false)) {
  921. // C++ [temp.local]p3:
  922. // A lookup that finds an injected-class-name (10.2) can result in an
  923. // ambiguity in certain cases (for example, if it is found in more than
  924. // one base class). If all of the injected-class-names that are found
  925. // refer to specializations of the same class template, and if the name
  926. // is followed by a template-argument-list, the reference refers to the
  927. // class template itself and not a specialization thereof, and is not
  928. // ambiguous.
  929. //
  930. // This filtering can make an ambiguous result into an unambiguous one,
  931. // so try again after filtering out template names.
  932. FilterAcceptableTemplateNames(Result);
  933. if (!Result.isAmbiguous()) {
  934. IsFilteredTemplateName = true;
  935. break;
  936. }
  937. }
  938. // Diagnose the ambiguity and return an error.
  939. return NameClassification::Error();
  940. }
  941. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  942. (IsFilteredTemplateName ||
  943. hasAnyAcceptableTemplateNames(
  944. Result, /*AllowFunctionTemplates=*/true,
  945. /*AllowDependent=*/false,
  946. /*AllowNonTemplateFunctions*/ !SS.isSet() &&
  947. getLangOpts().CPlusPlus2a))) {
  948. // C++ [temp.names]p3:
  949. // After name lookup (3.4) finds that a name is a template-name or that
  950. // an operator-function-id or a literal- operator-id refers to a set of
  951. // overloaded functions any member of which is a function template if
  952. // this is followed by a <, the < is always taken as the delimiter of a
  953. // template-argument-list and never as the less-than operator.
  954. // C++2a [temp.names]p2:
  955. // A name is also considered to refer to a template if it is an
  956. // unqualified-id followed by a < and name lookup finds either one
  957. // or more functions or finds nothing.
  958. if (!IsFilteredTemplateName)
  959. FilterAcceptableTemplateNames(Result);
  960. bool IsFunctionTemplate;
  961. bool IsVarTemplate;
  962. TemplateName Template;
  963. if (Result.end() - Result.begin() > 1) {
  964. IsFunctionTemplate = true;
  965. Template = Context.getOverloadedTemplateName(Result.begin(),
  966. Result.end());
  967. } else if (!Result.empty()) {
  968. auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
  969. *Result.begin(), /*AllowFunctionTemplates=*/true,
  970. /*AllowDependent=*/false));
  971. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  972. IsVarTemplate = isa<VarTemplateDecl>(TD);
  973. if (SS.isSet() && !SS.isInvalid())
  974. Template =
  975. Context.getQualifiedTemplateName(SS.getScopeRep(),
  976. /*TemplateKeyword=*/false, TD);
  977. else
  978. Template = TemplateName(TD);
  979. } else {
  980. // All results were non-template functions. This is a function template
  981. // name.
  982. IsFunctionTemplate = true;
  983. Template = Context.getAssumedTemplateName(NameInfo.getName());
  984. }
  985. if (IsFunctionTemplate) {
  986. // Function templates always go through overload resolution, at which
  987. // point we'll perform the various checks (e.g., accessibility) we need
  988. // to based on which function we selected.
  989. Result.suppressDiagnostics();
  990. return NameClassification::FunctionTemplate(Template);
  991. }
  992. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  993. : NameClassification::TypeTemplate(Template);
  994. }
  995. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  996. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  997. DiagnoseUseOfDecl(Type, NameLoc);
  998. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  999. QualType T = Context.getTypeDeclType(Type);
  1000. if (SS.isNotEmpty())
  1001. return buildNestedType(*this, SS, T, NameLoc);
  1002. return ParsedType::make(T);
  1003. }
  1004. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  1005. if (!Class) {
  1006. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  1007. if (ObjCCompatibleAliasDecl *Alias =
  1008. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  1009. Class = Alias->getClassInterface();
  1010. }
  1011. if (Class) {
  1012. DiagnoseUseOfDecl(Class, NameLoc);
  1013. if (NextToken.is(tok::period)) {
  1014. // Interface. <something> is parsed as a property reference expression.
  1015. // Just return "unknown" as a fall-through for now.
  1016. Result.suppressDiagnostics();
  1017. return NameClassification::Unknown();
  1018. }
  1019. QualType T = Context.getObjCInterfaceType(Class);
  1020. return ParsedType::make(T);
  1021. }
  1022. // We can have a type template here if we're classifying a template argument.
  1023. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
  1024. !isa<VarTemplateDecl>(FirstDecl))
  1025. return NameClassification::TypeTemplate(
  1026. TemplateName(cast<TemplateDecl>(FirstDecl)));
  1027. // Check for a tag type hidden by a non-type decl in a few cases where it
  1028. // seems likely a type is wanted instead of the non-type that was found.
  1029. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  1030. if ((NextToken.is(tok::identifier) ||
  1031. (NextIsOp &&
  1032. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  1033. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  1034. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  1035. DiagnoseUseOfDecl(Type, NameLoc);
  1036. QualType T = Context.getTypeDeclType(Type);
  1037. if (SS.isNotEmpty())
  1038. return buildNestedType(*this, SS, T, NameLoc);
  1039. return ParsedType::make(T);
  1040. }
  1041. if (FirstDecl->isCXXClassMember())
  1042. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  1043. nullptr, S);
  1044. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1045. return BuildDeclarationNameExpr(SS, Result, ADL);
  1046. }
  1047. Sema::TemplateNameKindForDiagnostics
  1048. Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
  1049. auto *TD = Name.getAsTemplateDecl();
  1050. if (!TD)
  1051. return TemplateNameKindForDiagnostics::DependentTemplate;
  1052. if (isa<ClassTemplateDecl>(TD))
  1053. return TemplateNameKindForDiagnostics::ClassTemplate;
  1054. if (isa<FunctionTemplateDecl>(TD))
  1055. return TemplateNameKindForDiagnostics::FunctionTemplate;
  1056. if (isa<VarTemplateDecl>(TD))
  1057. return TemplateNameKindForDiagnostics::VarTemplate;
  1058. if (isa<TypeAliasTemplateDecl>(TD))
  1059. return TemplateNameKindForDiagnostics::AliasTemplate;
  1060. if (isa<TemplateTemplateParmDecl>(TD))
  1061. return TemplateNameKindForDiagnostics::TemplateTemplateParam;
  1062. return TemplateNameKindForDiagnostics::DependentTemplate;
  1063. }
  1064. // Determines the context to return to after temporarily entering a
  1065. // context. This depends in an unnecessarily complicated way on the
  1066. // exact ordering of callbacks from the parser.
  1067. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  1068. // Functions defined inline within classes aren't parsed until we've
  1069. // finished parsing the top-level class, so the top-level class is
  1070. // the context we'll need to return to.
  1071. // A Lambda call operator whose parent is a class must not be treated
  1072. // as an inline member function. A Lambda can be used legally
  1073. // either as an in-class member initializer or a default argument. These
  1074. // are parsed once the class has been marked complete and so the containing
  1075. // context would be the nested class (when the lambda is defined in one);
  1076. // If the class is not complete, then the lambda is being used in an
  1077. // ill-formed fashion (such as to specify the width of a bit-field, or
  1078. // in an array-bound) - in which case we still want to return the
  1079. // lexically containing DC (which could be a nested class).
  1080. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  1081. DC = DC->getLexicalParent();
  1082. // A function not defined within a class will always return to its
  1083. // lexical context.
  1084. if (!isa<CXXRecordDecl>(DC))
  1085. return DC;
  1086. // A C++ inline method/friend is parsed *after* the topmost class
  1087. // it was declared in is fully parsed ("complete"); the topmost
  1088. // class is the context we need to return to.
  1089. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  1090. DC = RD;
  1091. // Return the declaration context of the topmost class the inline method is
  1092. // declared in.
  1093. return DC;
  1094. }
  1095. return DC->getLexicalParent();
  1096. }
  1097. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  1098. assert(getContainingDC(DC) == CurContext &&
  1099. "The next DeclContext should be lexically contained in the current one.");
  1100. CurContext = DC;
  1101. S->setEntity(DC);
  1102. }
  1103. void Sema::PopDeclContext() {
  1104. assert(CurContext && "DeclContext imbalance!");
  1105. CurContext = getContainingDC(CurContext);
  1106. assert(CurContext && "Popped translation unit!");
  1107. }
  1108. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  1109. Decl *D) {
  1110. // Unlike PushDeclContext, the context to which we return is not necessarily
  1111. // the containing DC of TD, because the new context will be some pre-existing
  1112. // TagDecl definition instead of a fresh one.
  1113. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  1114. CurContext = cast<TagDecl>(D)->getDefinition();
  1115. assert(CurContext && "skipping definition of undefined tag");
  1116. // Start lookups from the parent of the current context; we don't want to look
  1117. // into the pre-existing complete definition.
  1118. S->setEntity(CurContext->getLookupParent());
  1119. return Result;
  1120. }
  1121. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  1122. CurContext = static_cast<decltype(CurContext)>(Context);
  1123. }
  1124. /// EnterDeclaratorContext - Used when we must lookup names in the context
  1125. /// of a declarator's nested name specifier.
  1126. ///
  1127. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  1128. // C++0x [basic.lookup.unqual]p13:
  1129. // A name used in the definition of a static data member of class
  1130. // X (after the qualified-id of the static member) is looked up as
  1131. // if the name was used in a member function of X.
  1132. // C++0x [basic.lookup.unqual]p14:
  1133. // If a variable member of a namespace is defined outside of the
  1134. // scope of its namespace then any name used in the definition of
  1135. // the variable member (after the declarator-id) is looked up as
  1136. // if the definition of the variable member occurred in its
  1137. // namespace.
  1138. // Both of these imply that we should push a scope whose context
  1139. // is the semantic context of the declaration. We can't use
  1140. // PushDeclContext here because that context is not necessarily
  1141. // lexically contained in the current context. Fortunately,
  1142. // the containing scope should have the appropriate information.
  1143. assert(!S->getEntity() && "scope already has entity");
  1144. #ifndef NDEBUG
  1145. Scope *Ancestor = S->getParent();
  1146. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1147. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1148. #endif
  1149. CurContext = DC;
  1150. S->setEntity(DC);
  1151. }
  1152. void Sema::ExitDeclaratorContext(Scope *S) {
  1153. assert(S->getEntity() == CurContext && "Context imbalance!");
  1154. // Switch back to the lexical context. The safety of this is
  1155. // enforced by an assert in EnterDeclaratorContext.
  1156. Scope *Ancestor = S->getParent();
  1157. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1158. CurContext = Ancestor->getEntity();
  1159. // We don't need to do anything with the scope, which is going to
  1160. // disappear.
  1161. }
  1162. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1163. // We assume that the caller has already called
  1164. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1165. FunctionDecl *FD = D->getAsFunction();
  1166. if (!FD)
  1167. return;
  1168. // Same implementation as PushDeclContext, but enters the context
  1169. // from the lexical parent, rather than the top-level class.
  1170. assert(CurContext == FD->getLexicalParent() &&
  1171. "The next DeclContext should be lexically contained in the current one.");
  1172. CurContext = FD;
  1173. S->setEntity(CurContext);
  1174. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1175. ParmVarDecl *Param = FD->getParamDecl(P);
  1176. // If the parameter has an identifier, then add it to the scope
  1177. if (Param->getIdentifier()) {
  1178. S->AddDecl(Param);
  1179. IdResolver.AddDecl(Param);
  1180. }
  1181. }
  1182. }
  1183. void Sema::ActOnExitFunctionContext() {
  1184. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1185. // rather than the top-level class.
  1186. assert(CurContext && "DeclContext imbalance!");
  1187. CurContext = CurContext->getLexicalParent();
  1188. assert(CurContext && "Popped translation unit!");
  1189. }
  1190. /// Determine whether we allow overloading of the function
  1191. /// PrevDecl with another declaration.
  1192. ///
  1193. /// This routine determines whether overloading is possible, not
  1194. /// whether some new function is actually an overload. It will return
  1195. /// true in C++ (where we can always provide overloads) or, as an
  1196. /// extension, in C when the previous function is already an
  1197. /// overloaded function declaration or has the "overloadable"
  1198. /// attribute.
  1199. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1200. ASTContext &Context,
  1201. const FunctionDecl *New) {
  1202. if (Context.getLangOpts().CPlusPlus)
  1203. return true;
  1204. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1205. return true;
  1206. return Previous.getResultKind() == LookupResult::Found &&
  1207. (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
  1208. New->hasAttr<OverloadableAttr>());
  1209. }
  1210. /// Add this decl to the scope shadowed decl chains.
  1211. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1212. // Move up the scope chain until we find the nearest enclosing
  1213. // non-transparent context. The declaration will be introduced into this
  1214. // scope.
  1215. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1216. S = S->getParent();
  1217. // Add scoped declarations into their context, so that they can be
  1218. // found later. Declarations without a context won't be inserted
  1219. // into any context.
  1220. if (AddToContext)
  1221. CurContext->addDecl(D);
  1222. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1223. // are function-local declarations.
  1224. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1225. !D->getDeclContext()->getRedeclContext()->Equals(
  1226. D->getLexicalDeclContext()->getRedeclContext()) &&
  1227. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1228. return;
  1229. // Template instantiations should also not be pushed into scope.
  1230. if (isa<FunctionDecl>(D) &&
  1231. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1232. return;
  1233. // If this replaces anything in the current scope,
  1234. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1235. IEnd = IdResolver.end();
  1236. for (; I != IEnd; ++I) {
  1237. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1238. S->RemoveDecl(*I);
  1239. IdResolver.RemoveDecl(*I);
  1240. // Should only need to replace one decl.
  1241. break;
  1242. }
  1243. }
  1244. S->AddDecl(D);
  1245. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1246. // Implicitly-generated labels may end up getting generated in an order that
  1247. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1248. // the label at the appropriate place in the identifier chain.
  1249. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1250. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1251. if (IDC == CurContext) {
  1252. if (!S->isDeclScope(*I))
  1253. continue;
  1254. } else if (IDC->Encloses(CurContext))
  1255. break;
  1256. }
  1257. IdResolver.InsertDeclAfter(I, D);
  1258. } else {
  1259. IdResolver.AddDecl(D);
  1260. }
  1261. }
  1262. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1263. bool AllowInlineNamespace) {
  1264. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1265. }
  1266. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1267. DeclContext *TargetDC = DC->getPrimaryContext();
  1268. do {
  1269. if (DeclContext *ScopeDC = S->getEntity())
  1270. if (ScopeDC->getPrimaryContext() == TargetDC)
  1271. return S;
  1272. } while ((S = S->getParent()));
  1273. return nullptr;
  1274. }
  1275. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1276. DeclContext*,
  1277. ASTContext&);
  1278. /// Filters out lookup results that don't fall within the given scope
  1279. /// as determined by isDeclInScope.
  1280. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1281. bool ConsiderLinkage,
  1282. bool AllowInlineNamespace) {
  1283. LookupResult::Filter F = R.makeFilter();
  1284. while (F.hasNext()) {
  1285. NamedDecl *D = F.next();
  1286. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1287. continue;
  1288. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1289. continue;
  1290. F.erase();
  1291. }
  1292. F.done();
  1293. }
  1294. /// We've determined that \p New is a redeclaration of \p Old. Check that they
  1295. /// have compatible owning modules.
  1296. bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
  1297. // FIXME: The Modules TS is not clear about how friend declarations are
  1298. // to be treated. It's not meaningful to have different owning modules for
  1299. // linkage in redeclarations of the same entity, so for now allow the
  1300. // redeclaration and change the owning modules to match.
  1301. if (New->getFriendObjectKind() &&
  1302. Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
  1303. New->setLocalOwningModule(Old->getOwningModule());
  1304. makeMergedDefinitionVisible(New);
  1305. return false;
  1306. }
  1307. Module *NewM = New->getOwningModule();
  1308. Module *OldM = Old->getOwningModule();
  1309. if (NewM && NewM->Kind == Module::PrivateModuleFragment)
  1310. NewM = NewM->Parent;
  1311. if (OldM && OldM->Kind == Module::PrivateModuleFragment)
  1312. OldM = OldM->Parent;
  1313. if (NewM == OldM)
  1314. return false;
  1315. bool NewIsModuleInterface = NewM && NewM->isModulePurview();
  1316. bool OldIsModuleInterface = OldM && OldM->isModulePurview();
  1317. if (NewIsModuleInterface || OldIsModuleInterface) {
  1318. // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
  1319. // if a declaration of D [...] appears in the purview of a module, all
  1320. // other such declarations shall appear in the purview of the same module
  1321. Diag(New->getLocation(), diag::err_mismatched_owning_module)
  1322. << New
  1323. << NewIsModuleInterface
  1324. << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
  1325. << OldIsModuleInterface
  1326. << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
  1327. Diag(Old->getLocation(), diag::note_previous_declaration);
  1328. New->setInvalidDecl();
  1329. return true;
  1330. }
  1331. return false;
  1332. }
  1333. static bool isUsingDecl(NamedDecl *D) {
  1334. return isa<UsingShadowDecl>(D) ||
  1335. isa<UnresolvedUsingTypenameDecl>(D) ||
  1336. isa<UnresolvedUsingValueDecl>(D);
  1337. }
  1338. /// Removes using shadow declarations from the lookup results.
  1339. static void RemoveUsingDecls(LookupResult &R) {
  1340. LookupResult::Filter F = R.makeFilter();
  1341. while (F.hasNext())
  1342. if (isUsingDecl(F.next()))
  1343. F.erase();
  1344. F.done();
  1345. }
  1346. /// Check for this common pattern:
  1347. /// @code
  1348. /// class S {
  1349. /// S(const S&); // DO NOT IMPLEMENT
  1350. /// void operator=(const S&); // DO NOT IMPLEMENT
  1351. /// };
  1352. /// @endcode
  1353. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1354. // FIXME: Should check for private access too but access is set after we get
  1355. // the decl here.
  1356. if (D->doesThisDeclarationHaveABody())
  1357. return false;
  1358. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1359. return CD->isCopyConstructor();
  1360. return D->isCopyAssignmentOperator();
  1361. }
  1362. // We need this to handle
  1363. //
  1364. // typedef struct {
  1365. // void *foo() { return 0; }
  1366. // } A;
  1367. //
  1368. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1369. // for example. If 'A', foo will have external linkage. If we have '*A',
  1370. // foo will have no linkage. Since we can't know until we get to the end
  1371. // of the typedef, this function finds out if D might have non-external linkage.
  1372. // Callers should verify at the end of the TU if it D has external linkage or
  1373. // not.
  1374. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1375. const DeclContext *DC = D->getDeclContext();
  1376. while (!DC->isTranslationUnit()) {
  1377. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1378. if (!RD->hasNameForLinkage())
  1379. return true;
  1380. }
  1381. DC = DC->getParent();
  1382. }
  1383. return !D->isExternallyVisible();
  1384. }
  1385. // FIXME: This needs to be refactored; some other isInMainFile users want
  1386. // these semantics.
  1387. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1388. if (S.TUKind != TU_Complete)
  1389. return false;
  1390. return S.SourceMgr.isInMainFile(Loc);
  1391. }
  1392. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1393. assert(D);
  1394. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1395. return false;
  1396. // Ignore all entities declared within templates, and out-of-line definitions
  1397. // of members of class templates.
  1398. if (D->getDeclContext()->isDependentContext() ||
  1399. D->getLexicalDeclContext()->isDependentContext())
  1400. return false;
  1401. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1402. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1403. return false;
  1404. // A non-out-of-line declaration of a member specialization was implicitly
  1405. // instantiated; it's the out-of-line declaration that we're interested in.
  1406. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1407. FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
  1408. return false;
  1409. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1410. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1411. return false;
  1412. } else {
  1413. // 'static inline' functions are defined in headers; don't warn.
  1414. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1415. return false;
  1416. }
  1417. if (FD->doesThisDeclarationHaveABody() &&
  1418. Context.DeclMustBeEmitted(FD))
  1419. return false;
  1420. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1421. // Constants and utility variables are defined in headers with internal
  1422. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1423. // like "inline".)
  1424. if (!isMainFileLoc(*this, VD->getLocation()))
  1425. return false;
  1426. if (Context.DeclMustBeEmitted(VD))
  1427. return false;
  1428. if (VD->isStaticDataMember() &&
  1429. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1430. return false;
  1431. if (VD->isStaticDataMember() &&
  1432. VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1433. VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
  1434. return false;
  1435. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1436. return false;
  1437. } else {
  1438. return false;
  1439. }
  1440. // Only warn for unused decls internal to the translation unit.
  1441. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1442. // for inline functions defined in the main source file, for instance.
  1443. return mightHaveNonExternalLinkage(D);
  1444. }
  1445. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1446. if (!D)
  1447. return;
  1448. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1449. const FunctionDecl *First = FD->getFirstDecl();
  1450. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1451. return; // First should already be in the vector.
  1452. }
  1453. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1454. const VarDecl *First = VD->getFirstDecl();
  1455. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1456. return; // First should already be in the vector.
  1457. }
  1458. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1459. UnusedFileScopedDecls.push_back(D);
  1460. }
  1461. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1462. if (D->isInvalidDecl())
  1463. return false;
  1464. bool Referenced = false;
  1465. if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
  1466. // For a decomposition declaration, warn if none of the bindings are
  1467. // referenced, instead of if the variable itself is referenced (which
  1468. // it is, by the bindings' expressions).
  1469. for (auto *BD : DD->bindings()) {
  1470. if (BD->isReferenced()) {
  1471. Referenced = true;
  1472. break;
  1473. }
  1474. }
  1475. } else if (!D->getDeclName()) {
  1476. return false;
  1477. } else if (D->isReferenced() || D->isUsed()) {
  1478. Referenced = true;
  1479. }
  1480. if (Referenced || D->hasAttr<UnusedAttr>() ||
  1481. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1482. return false;
  1483. if (isa<LabelDecl>(D))
  1484. return true;
  1485. // Except for labels, we only care about unused decls that are local to
  1486. // functions.
  1487. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1488. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1489. // For dependent types, the diagnostic is deferred.
  1490. WithinFunction =
  1491. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1492. if (!WithinFunction)
  1493. return false;
  1494. if (isa<TypedefNameDecl>(D))
  1495. return true;
  1496. // White-list anything that isn't a local variable.
  1497. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1498. return false;
  1499. // Types of valid local variables should be complete, so this should succeed.
  1500. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1501. // White-list anything with an __attribute__((unused)) type.
  1502. const auto *Ty = VD->getType().getTypePtr();
  1503. // Only look at the outermost level of typedef.
  1504. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1505. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1506. return false;
  1507. }
  1508. // If we failed to complete the type for some reason, or if the type is
  1509. // dependent, don't diagnose the variable.
  1510. if (Ty->isIncompleteType() || Ty->isDependentType())
  1511. return false;
  1512. // Look at the element type to ensure that the warning behaviour is
  1513. // consistent for both scalars and arrays.
  1514. Ty = Ty->getBaseElementTypeUnsafe();
  1515. if (const TagType *TT = Ty->getAs<TagType>()) {
  1516. const TagDecl *Tag = TT->getDecl();
  1517. if (Tag->hasAttr<UnusedAttr>())
  1518. return false;
  1519. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1520. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1521. return false;
  1522. if (const Expr *Init = VD->getInit()) {
  1523. if (const ExprWithCleanups *Cleanups =
  1524. dyn_cast<ExprWithCleanups>(Init))
  1525. Init = Cleanups->getSubExpr();
  1526. const CXXConstructExpr *Construct =
  1527. dyn_cast<CXXConstructExpr>(Init);
  1528. if (Construct && !Construct->isElidable()) {
  1529. CXXConstructorDecl *CD = Construct->getConstructor();
  1530. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
  1531. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  1532. return false;
  1533. }
  1534. }
  1535. }
  1536. }
  1537. // TODO: __attribute__((unused)) templates?
  1538. }
  1539. return true;
  1540. }
  1541. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1542. FixItHint &Hint) {
  1543. if (isa<LabelDecl>(D)) {
  1544. SourceLocation AfterColon = Lexer::findLocationAfterToken(
  1545. D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
  1546. true);
  1547. if (AfterColon.isInvalid())
  1548. return;
  1549. Hint = FixItHint::CreateRemoval(
  1550. CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
  1551. }
  1552. }
  1553. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1554. if (D->getTypeForDecl()->isDependentType())
  1555. return;
  1556. for (auto *TmpD : D->decls()) {
  1557. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1558. DiagnoseUnusedDecl(T);
  1559. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1560. DiagnoseUnusedNestedTypedefs(R);
  1561. }
  1562. }
  1563. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1564. /// unless they are marked attr(unused).
  1565. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1566. if (!ShouldDiagnoseUnusedDecl(D))
  1567. return;
  1568. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1569. // typedefs can be referenced later on, so the diagnostics are emitted
  1570. // at end-of-translation-unit.
  1571. UnusedLocalTypedefNameCandidates.insert(TD);
  1572. return;
  1573. }
  1574. FixItHint Hint;
  1575. GenerateFixForUnusedDecl(D, Context, Hint);
  1576. unsigned DiagID;
  1577. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1578. DiagID = diag::warn_unused_exception_param;
  1579. else if (isa<LabelDecl>(D))
  1580. DiagID = diag::warn_unused_label;
  1581. else
  1582. DiagID = diag::warn_unused_variable;
  1583. Diag(D->getLocation(), DiagID) << D << Hint;
  1584. }
  1585. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1586. // Verify that we have no forward references left. If so, there was a goto
  1587. // or address of a label taken, but no definition of it. Label fwd
  1588. // definitions are indicated with a null substmt which is also not a resolved
  1589. // MS inline assembly label name.
  1590. bool Diagnose = false;
  1591. if (L->isMSAsmLabel())
  1592. Diagnose = !L->isResolvedMSAsmLabel();
  1593. else
  1594. Diagnose = L->getStmt() == nullptr;
  1595. if (Diagnose)
  1596. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1597. }
  1598. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1599. S->mergeNRVOIntoParent();
  1600. if (S->decl_empty()) return;
  1601. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1602. "Scope shouldn't contain decls!");
  1603. for (auto *TmpD : S->decls()) {
  1604. assert(TmpD && "This decl didn't get pushed??");
  1605. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1606. NamedDecl *D = cast<NamedDecl>(TmpD);
  1607. // Diagnose unused variables in this scope.
  1608. if (!S->hasUnrecoverableErrorOccurred()) {
  1609. DiagnoseUnusedDecl(D);
  1610. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1611. DiagnoseUnusedNestedTypedefs(RD);
  1612. }
  1613. if (!D->getDeclName()) continue;
  1614. // If this was a forward reference to a label, verify it was defined.
  1615. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1616. CheckPoppedLabel(LD, *this);
  1617. // Remove this name from our lexical scope, and warn on it if we haven't
  1618. // already.
  1619. IdResolver.RemoveDecl(D);
  1620. auto ShadowI = ShadowingDecls.find(D);
  1621. if (ShadowI != ShadowingDecls.end()) {
  1622. if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
  1623. Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
  1624. << D << FD << FD->getParent();
  1625. Diag(FD->getLocation(), diag::note_previous_declaration);
  1626. }
  1627. ShadowingDecls.erase(ShadowI);
  1628. }
  1629. }
  1630. }
  1631. /// Look for an Objective-C class in the translation unit.
  1632. ///
  1633. /// \param Id The name of the Objective-C class we're looking for. If
  1634. /// typo-correction fixes this name, the Id will be updated
  1635. /// to the fixed name.
  1636. ///
  1637. /// \param IdLoc The location of the name in the translation unit.
  1638. ///
  1639. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1640. /// if there is no class with the given name.
  1641. ///
  1642. /// \returns The declaration of the named Objective-C class, or NULL if the
  1643. /// class could not be found.
  1644. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1645. SourceLocation IdLoc,
  1646. bool DoTypoCorrection) {
  1647. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1648. // creation from this context.
  1649. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1650. if (!IDecl && DoTypoCorrection) {
  1651. // Perform typo correction at the given location, but only if we
  1652. // find an Objective-C class name.
  1653. DeclFilterCCC<ObjCInterfaceDecl> CCC{};
  1654. if (TypoCorrection C =
  1655. CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
  1656. TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
  1657. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1658. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1659. Id = IDecl->getIdentifier();
  1660. }
  1661. }
  1662. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1663. // This routine must always return a class definition, if any.
  1664. if (Def && Def->getDefinition())
  1665. Def = Def->getDefinition();
  1666. return Def;
  1667. }
  1668. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1669. /// from S, where a non-field would be declared. This routine copes
  1670. /// with the difference between C and C++ scoping rules in structs and
  1671. /// unions. For example, the following code is well-formed in C but
  1672. /// ill-formed in C++:
  1673. /// @code
  1674. /// struct S6 {
  1675. /// enum { BAR } e;
  1676. /// };
  1677. ///
  1678. /// void test_S6() {
  1679. /// struct S6 a;
  1680. /// a.e = BAR;
  1681. /// }
  1682. /// @endcode
  1683. /// For the declaration of BAR, this routine will return a different
  1684. /// scope. The scope S will be the scope of the unnamed enumeration
  1685. /// within S6. In C++, this routine will return the scope associated
  1686. /// with S6, because the enumeration's scope is a transparent
  1687. /// context but structures can contain non-field names. In C, this
  1688. /// routine will return the translation unit scope, since the
  1689. /// enumeration's scope is a transparent context and structures cannot
  1690. /// contain non-field names.
  1691. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1692. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1693. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1694. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1695. S = S->getParent();
  1696. return S;
  1697. }
  1698. /// Looks up the declaration of "struct objc_super" and
  1699. /// saves it for later use in building builtin declaration of
  1700. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1701. /// pre-existing declaration exists no action takes place.
  1702. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1703. IdentifierInfo *II) {
  1704. if (!II->isStr("objc_msgSendSuper"))
  1705. return;
  1706. ASTContext &Context = ThisSema.Context;
  1707. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1708. SourceLocation(), Sema::LookupTagName);
  1709. ThisSema.LookupName(Result, S);
  1710. if (Result.getResultKind() == LookupResult::Found)
  1711. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1712. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1713. }
  1714. static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
  1715. ASTContext::GetBuiltinTypeError Error) {
  1716. switch (Error) {
  1717. case ASTContext::GE_None:
  1718. return "";
  1719. case ASTContext::GE_Missing_type:
  1720. return BuiltinInfo.getHeaderName(ID);
  1721. case ASTContext::GE_Missing_stdio:
  1722. return "stdio.h";
  1723. case ASTContext::GE_Missing_setjmp:
  1724. return "setjmp.h";
  1725. case ASTContext::GE_Missing_ucontext:
  1726. return "ucontext.h";
  1727. }
  1728. llvm_unreachable("unhandled error kind");
  1729. }
  1730. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1731. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1732. /// if we're creating this built-in in anticipation of redeclaring the
  1733. /// built-in.
  1734. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1735. Scope *S, bool ForRedeclaration,
  1736. SourceLocation Loc) {
  1737. LookupPredefedObjCSuperType(*this, S, II);
  1738. ASTContext::GetBuiltinTypeError Error;
  1739. QualType R = Context.GetBuiltinType(ID, Error);
  1740. if (Error) {
  1741. if (ForRedeclaration)
  1742. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1743. << getHeaderName(Context.BuiltinInfo, ID, Error)
  1744. << Context.BuiltinInfo.getName(ID);
  1745. return nullptr;
  1746. }
  1747. if (!ForRedeclaration &&
  1748. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1749. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1750. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1751. << Context.BuiltinInfo.getName(ID) << R;
  1752. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1753. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1754. Diag(Loc, diag::note_include_header_or_declare)
  1755. << Context.BuiltinInfo.getHeaderName(ID)
  1756. << Context.BuiltinInfo.getName(ID);
  1757. }
  1758. if (R.isNull())
  1759. return nullptr;
  1760. DeclContext *Parent = Context.getTranslationUnitDecl();
  1761. if (getLangOpts().CPlusPlus) {
  1762. LinkageSpecDecl *CLinkageDecl =
  1763. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1764. LinkageSpecDecl::lang_c, false);
  1765. CLinkageDecl->setImplicit();
  1766. Parent->addDecl(CLinkageDecl);
  1767. Parent = CLinkageDecl;
  1768. }
  1769. FunctionDecl *New = FunctionDecl::Create(Context,
  1770. Parent,
  1771. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1772. SC_Extern,
  1773. false,
  1774. R->isFunctionProtoType());
  1775. New->setImplicit();
  1776. // Create Decl objects for each parameter, adding them to the
  1777. // FunctionDecl.
  1778. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1779. SmallVector<ParmVarDecl*, 16> Params;
  1780. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1781. ParmVarDecl *parm =
  1782. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1783. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1784. SC_None, nullptr);
  1785. parm->setScopeInfo(0, i);
  1786. Params.push_back(parm);
  1787. }
  1788. New->setParams(Params);
  1789. }
  1790. AddKnownFunctionAttributes(New);
  1791. RegisterLocallyScopedExternCDecl(New, S);
  1792. // TUScope is the translation-unit scope to insert this function into.
  1793. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1794. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1795. // entirely, but we're not there yet.
  1796. DeclContext *SavedContext = CurContext;
  1797. CurContext = Parent;
  1798. PushOnScopeChains(New, TUScope);
  1799. CurContext = SavedContext;
  1800. return New;
  1801. }
  1802. /// Typedef declarations don't have linkage, but they still denote the same
  1803. /// entity if their types are the same.
  1804. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1805. /// isSameEntity.
  1806. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1807. TypedefNameDecl *Decl,
  1808. LookupResult &Previous) {
  1809. // This is only interesting when modules are enabled.
  1810. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1811. return;
  1812. // Empty sets are uninteresting.
  1813. if (Previous.empty())
  1814. return;
  1815. LookupResult::Filter Filter = Previous.makeFilter();
  1816. while (Filter.hasNext()) {
  1817. NamedDecl *Old = Filter.next();
  1818. // Non-hidden declarations are never ignored.
  1819. if (S.isVisible(Old))
  1820. continue;
  1821. // Declarations of the same entity are not ignored, even if they have
  1822. // different linkages.
  1823. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1824. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1825. Decl->getUnderlyingType()))
  1826. continue;
  1827. // If both declarations give a tag declaration a typedef name for linkage
  1828. // purposes, then they declare the same entity.
  1829. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1830. Decl->getAnonDeclWithTypedefName())
  1831. continue;
  1832. }
  1833. Filter.erase();
  1834. }
  1835. Filter.done();
  1836. }
  1837. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1838. QualType OldType;
  1839. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1840. OldType = OldTypedef->getUnderlyingType();
  1841. else
  1842. OldType = Context.getTypeDeclType(Old);
  1843. QualType NewType = New->getUnderlyingType();
  1844. if (NewType->isVariablyModifiedType()) {
  1845. // Must not redefine a typedef with a variably-modified type.
  1846. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1847. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1848. << Kind << NewType;
  1849. if (Old->getLocation().isValid())
  1850. notePreviousDefinition(Old, New->getLocation());
  1851. New->setInvalidDecl();
  1852. return true;
  1853. }
  1854. if (OldType != NewType &&
  1855. !OldType->isDependentType() &&
  1856. !NewType->isDependentType() &&
  1857. !Context.hasSameType(OldType, NewType)) {
  1858. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1859. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1860. << Kind << NewType << OldType;
  1861. if (Old->getLocation().isValid())
  1862. notePreviousDefinition(Old, New->getLocation());
  1863. New->setInvalidDecl();
  1864. return true;
  1865. }
  1866. return false;
  1867. }
  1868. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1869. /// same name and scope as a previous declaration 'Old'. Figure out
  1870. /// how to resolve this situation, merging decls or emitting
  1871. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1872. ///
  1873. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  1874. LookupResult &OldDecls) {
  1875. // If the new decl is known invalid already, don't bother doing any
  1876. // merging checks.
  1877. if (New->isInvalidDecl()) return;
  1878. // Allow multiple definitions for ObjC built-in typedefs.
  1879. // FIXME: Verify the underlying types are equivalent!
  1880. if (getLangOpts().ObjC) {
  1881. const IdentifierInfo *TypeID = New->getIdentifier();
  1882. switch (TypeID->getLength()) {
  1883. default: break;
  1884. case 2:
  1885. {
  1886. if (!TypeID->isStr("id"))
  1887. break;
  1888. QualType T = New->getUnderlyingType();
  1889. if (!T->isPointerType())
  1890. break;
  1891. if (!T->isVoidPointerType()) {
  1892. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1893. if (!PT->isStructureType())
  1894. break;
  1895. }
  1896. Context.setObjCIdRedefinitionType(T);
  1897. // Install the built-in type for 'id', ignoring the current definition.
  1898. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1899. return;
  1900. }
  1901. case 5:
  1902. if (!TypeID->isStr("Class"))
  1903. break;
  1904. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1905. // Install the built-in type for 'Class', ignoring the current definition.
  1906. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1907. return;
  1908. case 3:
  1909. if (!TypeID->isStr("SEL"))
  1910. break;
  1911. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1912. // Install the built-in type for 'SEL', ignoring the current definition.
  1913. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1914. return;
  1915. }
  1916. // Fall through - the typedef name was not a builtin type.
  1917. }
  1918. // Verify the old decl was also a type.
  1919. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1920. if (!Old) {
  1921. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1922. << New->getDeclName();
  1923. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1924. if (OldD->getLocation().isValid())
  1925. notePreviousDefinition(OldD, New->getLocation());
  1926. return New->setInvalidDecl();
  1927. }
  1928. // If the old declaration is invalid, just give up here.
  1929. if (Old->isInvalidDecl())
  1930. return New->setInvalidDecl();
  1931. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1932. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1933. auto *NewTag = New->getAnonDeclWithTypedefName();
  1934. NamedDecl *Hidden = nullptr;
  1935. if (OldTag && NewTag &&
  1936. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1937. !hasVisibleDefinition(OldTag, &Hidden)) {
  1938. // There is a definition of this tag, but it is not visible. Use it
  1939. // instead of our tag.
  1940. New->setTypeForDecl(OldTD->getTypeForDecl());
  1941. if (OldTD->isModed())
  1942. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1943. OldTD->getUnderlyingType());
  1944. else
  1945. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1946. // Make the old tag definition visible.
  1947. makeMergedDefinitionVisible(Hidden);
  1948. // If this was an unscoped enumeration, yank all of its enumerators
  1949. // out of the scope.
  1950. if (isa<EnumDecl>(NewTag)) {
  1951. Scope *EnumScope = getNonFieldDeclScope(S);
  1952. for (auto *D : NewTag->decls()) {
  1953. auto *ED = cast<EnumConstantDecl>(D);
  1954. assert(EnumScope->isDeclScope(ED));
  1955. EnumScope->RemoveDecl(ED);
  1956. IdResolver.RemoveDecl(ED);
  1957. ED->getLexicalDeclContext()->removeDecl(ED);
  1958. }
  1959. }
  1960. }
  1961. }
  1962. // If the typedef types are not identical, reject them in all languages and
  1963. // with any extensions enabled.
  1964. if (isIncompatibleTypedef(Old, New))
  1965. return;
  1966. // The types match. Link up the redeclaration chain and merge attributes if
  1967. // the old declaration was a typedef.
  1968. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1969. New->setPreviousDecl(Typedef);
  1970. mergeDeclAttributes(New, Old);
  1971. }
  1972. if (getLangOpts().MicrosoftExt)
  1973. return;
  1974. if (getLangOpts().CPlusPlus) {
  1975. // C++ [dcl.typedef]p2:
  1976. // In a given non-class scope, a typedef specifier can be used to
  1977. // redefine the name of any type declared in that scope to refer
  1978. // to the type to which it already refers.
  1979. if (!isa<CXXRecordDecl>(CurContext))
  1980. return;
  1981. // C++0x [dcl.typedef]p4:
  1982. // In a given class scope, a typedef specifier can be used to redefine
  1983. // any class-name declared in that scope that is not also a typedef-name
  1984. // to refer to the type to which it already refers.
  1985. //
  1986. // This wording came in via DR424, which was a correction to the
  1987. // wording in DR56, which accidentally banned code like:
  1988. //
  1989. // struct S {
  1990. // typedef struct A { } A;
  1991. // };
  1992. //
  1993. // in the C++03 standard. We implement the C++0x semantics, which
  1994. // allow the above but disallow
  1995. //
  1996. // struct S {
  1997. // typedef int I;
  1998. // typedef int I;
  1999. // };
  2000. //
  2001. // since that was the intent of DR56.
  2002. if (!isa<TypedefNameDecl>(Old))
  2003. return;
  2004. Diag(New->getLocation(), diag::err_redefinition)
  2005. << New->getDeclName();
  2006. notePreviousDefinition(Old, New->getLocation());
  2007. return New->setInvalidDecl();
  2008. }
  2009. // Modules always permit redefinition of typedefs, as does C11.
  2010. if (getLangOpts().Modules || getLangOpts().C11)
  2011. return;
  2012. // If we have a redefinition of a typedef in C, emit a warning. This warning
  2013. // is normally mapped to an error, but can be controlled with
  2014. // -Wtypedef-redefinition. If either the original or the redefinition is
  2015. // in a system header, don't emit this for compatibility with GCC.
  2016. if (getDiagnostics().getSuppressSystemWarnings() &&
  2017. // Some standard types are defined implicitly in Clang (e.g. OpenCL).
  2018. (Old->isImplicit() ||
  2019. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  2020. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  2021. return;
  2022. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  2023. << New->getDeclName();
  2024. notePreviousDefinition(Old, New->getLocation());
  2025. }
  2026. /// DeclhasAttr - returns true if decl Declaration already has the target
  2027. /// attribute.
  2028. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  2029. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  2030. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  2031. for (const auto *i : D->attrs())
  2032. if (i->getKind() == A->getKind()) {
  2033. if (Ann) {
  2034. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  2035. return true;
  2036. continue;
  2037. }
  2038. // FIXME: Don't hardcode this check
  2039. if (OA && isa<OwnershipAttr>(i))
  2040. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  2041. return true;
  2042. }
  2043. return false;
  2044. }
  2045. static bool isAttributeTargetADefinition(Decl *D) {
  2046. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  2047. return VD->isThisDeclarationADefinition();
  2048. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  2049. return TD->isCompleteDefinition() || TD->isBeingDefined();
  2050. return true;
  2051. }
  2052. /// Merge alignment attributes from \p Old to \p New, taking into account the
  2053. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  2054. ///
  2055. /// \return \c true if any attributes were added to \p New.
  2056. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  2057. // Look for alignas attributes on Old, and pick out whichever attribute
  2058. // specifies the strictest alignment requirement.
  2059. AlignedAttr *OldAlignasAttr = nullptr;
  2060. AlignedAttr *OldStrictestAlignAttr = nullptr;
  2061. unsigned OldAlign = 0;
  2062. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  2063. // FIXME: We have no way of representing inherited dependent alignments
  2064. // in a case like:
  2065. // template<int A, int B> struct alignas(A) X;
  2066. // template<int A, int B> struct alignas(B) X {};
  2067. // For now, we just ignore any alignas attributes which are not on the
  2068. // definition in such a case.
  2069. if (I->isAlignmentDependent())
  2070. return false;
  2071. if (I->isAlignas())
  2072. OldAlignasAttr = I;
  2073. unsigned Align = I->getAlignment(S.Context);
  2074. if (Align > OldAlign) {
  2075. OldAlign = Align;
  2076. OldStrictestAlignAttr = I;
  2077. }
  2078. }
  2079. // Look for alignas attributes on New.
  2080. AlignedAttr *NewAlignasAttr = nullptr;
  2081. unsigned NewAlign = 0;
  2082. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  2083. if (I->isAlignmentDependent())
  2084. return false;
  2085. if (I->isAlignas())
  2086. NewAlignasAttr = I;
  2087. unsigned Align = I->getAlignment(S.Context);
  2088. if (Align > NewAlign)
  2089. NewAlign = Align;
  2090. }
  2091. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  2092. // Both declarations have 'alignas' attributes. We require them to match.
  2093. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  2094. // fall short. (If two declarations both have alignas, they must both match
  2095. // every definition, and so must match each other if there is a definition.)
  2096. // If either declaration only contains 'alignas(0)' specifiers, then it
  2097. // specifies the natural alignment for the type.
  2098. if (OldAlign == 0 || NewAlign == 0) {
  2099. QualType Ty;
  2100. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  2101. Ty = VD->getType();
  2102. else
  2103. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  2104. if (OldAlign == 0)
  2105. OldAlign = S.Context.getTypeAlign(Ty);
  2106. if (NewAlign == 0)
  2107. NewAlign = S.Context.getTypeAlign(Ty);
  2108. }
  2109. if (OldAlign != NewAlign) {
  2110. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  2111. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  2112. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  2113. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  2114. }
  2115. }
  2116. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  2117. // C++11 [dcl.align]p6:
  2118. // if any declaration of an entity has an alignment-specifier,
  2119. // every defining declaration of that entity shall specify an
  2120. // equivalent alignment.
  2121. // C11 6.7.5/7:
  2122. // If the definition of an object does not have an alignment
  2123. // specifier, any other declaration of that object shall also
  2124. // have no alignment specifier.
  2125. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2126. << OldAlignasAttr;
  2127. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2128. << OldAlignasAttr;
  2129. }
  2130. bool AnyAdded = false;
  2131. // Ensure we have an attribute representing the strictest alignment.
  2132. if (OldAlign > NewAlign) {
  2133. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2134. Clone->setInherited(true);
  2135. New->addAttr(Clone);
  2136. AnyAdded = true;
  2137. }
  2138. // Ensure we have an alignas attribute if the old declaration had one.
  2139. if (OldAlignasAttr && !NewAlignasAttr &&
  2140. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2141. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2142. Clone->setInherited(true);
  2143. New->addAttr(Clone);
  2144. AnyAdded = true;
  2145. }
  2146. return AnyAdded;
  2147. }
  2148. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2149. const InheritableAttr *Attr,
  2150. Sema::AvailabilityMergeKind AMK) {
  2151. // This function copies an attribute Attr from a previous declaration to the
  2152. // new declaration D if the new declaration doesn't itself have that attribute
  2153. // yet or if that attribute allows duplicates.
  2154. // If you're adding a new attribute that requires logic different from
  2155. // "use explicit attribute on decl if present, else use attribute from
  2156. // previous decl", for example if the attribute needs to be consistent
  2157. // between redeclarations, you need to call a custom merge function here.
  2158. InheritableAttr *NewAttr = nullptr;
  2159. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  2160. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2161. NewAttr = S.mergeAvailabilityAttr(
  2162. D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
  2163. AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
  2164. AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
  2165. AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
  2166. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2167. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2168. AttrSpellingListIndex);
  2169. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2170. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2171. AttrSpellingListIndex);
  2172. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2173. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  2174. AttrSpellingListIndex);
  2175. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2176. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  2177. AttrSpellingListIndex);
  2178. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2179. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  2180. FA->getFormatIdx(), FA->getFirstArg(),
  2181. AttrSpellingListIndex);
  2182. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2183. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  2184. AttrSpellingListIndex);
  2185. else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
  2186. NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
  2187. AttrSpellingListIndex);
  2188. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2189. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  2190. AttrSpellingListIndex,
  2191. IA->getSemanticSpelling());
  2192. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2193. NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
  2194. &S.Context.Idents.get(AA->getSpelling()),
  2195. AttrSpellingListIndex);
  2196. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2197. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2198. isa<CUDAGlobalAttr>(Attr))) {
  2199. // CUDA target attributes are part of function signature for
  2200. // overloading purposes and must not be merged.
  2201. return false;
  2202. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2203. NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
  2204. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2205. NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
  2206. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2207. NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
  2208. else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
  2209. NewAttr = S.mergeCommonAttr(D, *CommonA);
  2210. else if (isa<AlignedAttr>(Attr))
  2211. // AlignedAttrs are handled separately, because we need to handle all
  2212. // such attributes on a declaration at the same time.
  2213. NewAttr = nullptr;
  2214. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2215. (AMK == Sema::AMK_Override ||
  2216. AMK == Sema::AMK_ProtocolImplementation))
  2217. NewAttr = nullptr;
  2218. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2219. NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
  2220. UA->getGuid());
  2221. else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
  2222. NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
  2223. else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
  2224. NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
  2225. else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
  2226. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2227. if (NewAttr) {
  2228. NewAttr->setInherited(true);
  2229. D->addAttr(NewAttr);
  2230. if (isa<MSInheritanceAttr>(NewAttr))
  2231. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2232. return true;
  2233. }
  2234. return false;
  2235. }
  2236. static const NamedDecl *getDefinition(const Decl *D) {
  2237. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2238. return TD->getDefinition();
  2239. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2240. const VarDecl *Def = VD->getDefinition();
  2241. if (Def)
  2242. return Def;
  2243. return VD->getActingDefinition();
  2244. }
  2245. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2246. return FD->getDefinition();
  2247. return nullptr;
  2248. }
  2249. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2250. for (const auto *Attribute : D->attrs())
  2251. if (Attribute->getKind() == Kind)
  2252. return true;
  2253. return false;
  2254. }
  2255. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2256. /// there are no new attributes in this declaration.
  2257. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2258. if (!New->hasAttrs())
  2259. return;
  2260. const NamedDecl *Def = getDefinition(Old);
  2261. if (!Def || Def == New)
  2262. return;
  2263. AttrVec &NewAttributes = New->getAttrs();
  2264. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2265. const Attr *NewAttribute = NewAttributes[I];
  2266. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2267. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2268. Sema::SkipBodyInfo SkipBody;
  2269. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2270. // If we're skipping this definition, drop the "alias" attribute.
  2271. if (SkipBody.ShouldSkip) {
  2272. NewAttributes.erase(NewAttributes.begin() + I);
  2273. --E;
  2274. continue;
  2275. }
  2276. } else {
  2277. VarDecl *VD = cast<VarDecl>(New);
  2278. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2279. VarDecl::TentativeDefinition
  2280. ? diag::err_alias_after_tentative
  2281. : diag::err_redefinition;
  2282. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2283. if (Diag == diag::err_redefinition)
  2284. S.notePreviousDefinition(Def, VD->getLocation());
  2285. else
  2286. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2287. VD->setInvalidDecl();
  2288. }
  2289. ++I;
  2290. continue;
  2291. }
  2292. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2293. // Tentative definitions are only interesting for the alias check above.
  2294. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2295. ++I;
  2296. continue;
  2297. }
  2298. }
  2299. if (hasAttribute(Def, NewAttribute->getKind())) {
  2300. ++I;
  2301. continue; // regular attr merging will take care of validating this.
  2302. }
  2303. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2304. // C's _Noreturn is allowed to be added to a function after it is defined.
  2305. ++I;
  2306. continue;
  2307. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2308. if (AA->isAlignas()) {
  2309. // C++11 [dcl.align]p6:
  2310. // if any declaration of an entity has an alignment-specifier,
  2311. // every defining declaration of that entity shall specify an
  2312. // equivalent alignment.
  2313. // C11 6.7.5/7:
  2314. // If the definition of an object does not have an alignment
  2315. // specifier, any other declaration of that object shall also
  2316. // have no alignment specifier.
  2317. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2318. << AA;
  2319. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2320. << AA;
  2321. NewAttributes.erase(NewAttributes.begin() + I);
  2322. --E;
  2323. continue;
  2324. }
  2325. }
  2326. S.Diag(NewAttribute->getLocation(),
  2327. diag::warn_attribute_precede_definition);
  2328. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2329. NewAttributes.erase(NewAttributes.begin() + I);
  2330. --E;
  2331. }
  2332. }
  2333. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2334. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2335. AvailabilityMergeKind AMK) {
  2336. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2337. UsedAttr *NewAttr = OldAttr->clone(Context);
  2338. NewAttr->setInherited(true);
  2339. New->addAttr(NewAttr);
  2340. }
  2341. if (!Old->hasAttrs() && !New->hasAttrs())
  2342. return;
  2343. // Attributes declared post-definition are currently ignored.
  2344. checkNewAttributesAfterDef(*this, New, Old);
  2345. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2346. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2347. if (OldA->getLabel() != NewA->getLabel()) {
  2348. // This redeclaration changes __asm__ label.
  2349. Diag(New->getLocation(), diag::err_different_asm_label);
  2350. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2351. }
  2352. } else if (Old->isUsed()) {
  2353. // This redeclaration adds an __asm__ label to a declaration that has
  2354. // already been ODR-used.
  2355. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2356. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2357. }
  2358. }
  2359. // Re-declaration cannot add abi_tag's.
  2360. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2361. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2362. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2363. if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
  2364. NewTag) == OldAbiTagAttr->tags_end()) {
  2365. Diag(NewAbiTagAttr->getLocation(),
  2366. diag::err_new_abi_tag_on_redeclaration)
  2367. << NewTag;
  2368. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2369. }
  2370. }
  2371. } else {
  2372. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2373. Diag(Old->getLocation(), diag::note_previous_declaration);
  2374. }
  2375. }
  2376. // This redeclaration adds a section attribute.
  2377. if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
  2378. if (auto *VD = dyn_cast<VarDecl>(New)) {
  2379. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
  2380. Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
  2381. Diag(Old->getLocation(), diag::note_previous_declaration);
  2382. }
  2383. }
  2384. }
  2385. // Redeclaration adds code-seg attribute.
  2386. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  2387. if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
  2388. !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
  2389. Diag(New->getLocation(), diag::warn_mismatched_section)
  2390. << 0 /*codeseg*/;
  2391. Diag(Old->getLocation(), diag::note_previous_declaration);
  2392. }
  2393. if (!Old->hasAttrs())
  2394. return;
  2395. bool foundAny = New->hasAttrs();
  2396. // Ensure that any moving of objects within the allocated map is done before
  2397. // we process them.
  2398. if (!foundAny) New->setAttrs(AttrVec());
  2399. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2400. // Ignore deprecated/unavailable/availability attributes if requested.
  2401. AvailabilityMergeKind LocalAMK = AMK_None;
  2402. if (isa<DeprecatedAttr>(I) ||
  2403. isa<UnavailableAttr>(I) ||
  2404. isa<AvailabilityAttr>(I)) {
  2405. switch (AMK) {
  2406. case AMK_None:
  2407. continue;
  2408. case AMK_Redeclaration:
  2409. case AMK_Override:
  2410. case AMK_ProtocolImplementation:
  2411. LocalAMK = AMK;
  2412. break;
  2413. }
  2414. }
  2415. // Already handled.
  2416. if (isa<UsedAttr>(I))
  2417. continue;
  2418. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2419. foundAny = true;
  2420. }
  2421. if (mergeAlignedAttrs(*this, New, Old))
  2422. foundAny = true;
  2423. if (!foundAny) New->dropAttrs();
  2424. }
  2425. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2426. /// to the new one.
  2427. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2428. const ParmVarDecl *oldDecl,
  2429. Sema &S) {
  2430. // C++11 [dcl.attr.depend]p2:
  2431. // The first declaration of a function shall specify the
  2432. // carries_dependency attribute for its declarator-id if any declaration
  2433. // of the function specifies the carries_dependency attribute.
  2434. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2435. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2436. S.Diag(CDA->getLocation(),
  2437. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2438. // Find the first declaration of the parameter.
  2439. // FIXME: Should we build redeclaration chains for function parameters?
  2440. const FunctionDecl *FirstFD =
  2441. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2442. const ParmVarDecl *FirstVD =
  2443. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2444. S.Diag(FirstVD->getLocation(),
  2445. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2446. }
  2447. if (!oldDecl->hasAttrs())
  2448. return;
  2449. bool foundAny = newDecl->hasAttrs();
  2450. // Ensure that any moving of objects within the allocated map is
  2451. // done before we process them.
  2452. if (!foundAny) newDecl->setAttrs(AttrVec());
  2453. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2454. if (!DeclHasAttr(newDecl, I)) {
  2455. InheritableAttr *newAttr =
  2456. cast<InheritableParamAttr>(I->clone(S.Context));
  2457. newAttr->setInherited(true);
  2458. newDecl->addAttr(newAttr);
  2459. foundAny = true;
  2460. }
  2461. }
  2462. if (!foundAny) newDecl->dropAttrs();
  2463. }
  2464. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2465. const ParmVarDecl *OldParam,
  2466. Sema &S) {
  2467. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2468. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2469. if (*Oldnullability != *Newnullability) {
  2470. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2471. << DiagNullabilityKind(
  2472. *Newnullability,
  2473. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2474. != 0))
  2475. << DiagNullabilityKind(
  2476. *Oldnullability,
  2477. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2478. != 0));
  2479. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2480. }
  2481. } else {
  2482. QualType NewT = NewParam->getType();
  2483. NewT = S.Context.getAttributedType(
  2484. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2485. NewT, NewT);
  2486. NewParam->setType(NewT);
  2487. }
  2488. }
  2489. }
  2490. namespace {
  2491. /// Used in MergeFunctionDecl to keep track of function parameters in
  2492. /// C.
  2493. struct GNUCompatibleParamWarning {
  2494. ParmVarDecl *OldParm;
  2495. ParmVarDecl *NewParm;
  2496. QualType PromotedType;
  2497. };
  2498. } // end anonymous namespace
  2499. /// getSpecialMember - get the special member enum for a method.
  2500. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2501. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2502. if (Ctor->isDefaultConstructor())
  2503. return Sema::CXXDefaultConstructor;
  2504. if (Ctor->isCopyConstructor())
  2505. return Sema::CXXCopyConstructor;
  2506. if (Ctor->isMoveConstructor())
  2507. return Sema::CXXMoveConstructor;
  2508. } else if (isa<CXXDestructorDecl>(MD)) {
  2509. return Sema::CXXDestructor;
  2510. } else if (MD->isCopyAssignmentOperator()) {
  2511. return Sema::CXXCopyAssignment;
  2512. } else if (MD->isMoveAssignmentOperator()) {
  2513. return Sema::CXXMoveAssignment;
  2514. }
  2515. return Sema::CXXInvalid;
  2516. }
  2517. // Determine whether the previous declaration was a definition, implicit
  2518. // declaration, or a declaration.
  2519. template <typename T>
  2520. static std::pair<diag::kind, SourceLocation>
  2521. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2522. diag::kind PrevDiag;
  2523. SourceLocation OldLocation = Old->getLocation();
  2524. if (Old->isThisDeclarationADefinition())
  2525. PrevDiag = diag::note_previous_definition;
  2526. else if (Old->isImplicit()) {
  2527. PrevDiag = diag::note_previous_implicit_declaration;
  2528. if (OldLocation.isInvalid())
  2529. OldLocation = New->getLocation();
  2530. } else
  2531. PrevDiag = diag::note_previous_declaration;
  2532. return std::make_pair(PrevDiag, OldLocation);
  2533. }
  2534. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2535. /// only extern inline functions can be redefined, and even then only in
  2536. /// GNU89 mode.
  2537. static bool canRedefineFunction(const FunctionDecl *FD,
  2538. const LangOptions& LangOpts) {
  2539. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2540. !LangOpts.CPlusPlus &&
  2541. FD->isInlineSpecified() &&
  2542. FD->getStorageClass() == SC_Extern);
  2543. }
  2544. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2545. const AttributedType *AT = T->getAs<AttributedType>();
  2546. while (AT && !AT->isCallingConv())
  2547. AT = AT->getModifiedType()->getAs<AttributedType>();
  2548. return AT;
  2549. }
  2550. template <typename T>
  2551. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2552. const DeclContext *DC = Old->getDeclContext();
  2553. if (DC->isRecord())
  2554. return false;
  2555. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2556. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2557. return true;
  2558. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2559. return true;
  2560. return false;
  2561. }
  2562. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2563. static bool isExternC(VarTemplateDecl *) { return false; }
  2564. /// Check whether a redeclaration of an entity introduced by a
  2565. /// using-declaration is valid, given that we know it's not an overload
  2566. /// (nor a hidden tag declaration).
  2567. template<typename ExpectedDecl>
  2568. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2569. ExpectedDecl *New) {
  2570. // C++11 [basic.scope.declarative]p4:
  2571. // Given a set of declarations in a single declarative region, each of
  2572. // which specifies the same unqualified name,
  2573. // -- they shall all refer to the same entity, or all refer to functions
  2574. // and function templates; or
  2575. // -- exactly one declaration shall declare a class name or enumeration
  2576. // name that is not a typedef name and the other declarations shall all
  2577. // refer to the same variable or enumerator, or all refer to functions
  2578. // and function templates; in this case the class name or enumeration
  2579. // name is hidden (3.3.10).
  2580. // C++11 [namespace.udecl]p14:
  2581. // If a function declaration in namespace scope or block scope has the
  2582. // same name and the same parameter-type-list as a function introduced
  2583. // by a using-declaration, and the declarations do not declare the same
  2584. // function, the program is ill-formed.
  2585. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2586. if (Old &&
  2587. !Old->getDeclContext()->getRedeclContext()->Equals(
  2588. New->getDeclContext()->getRedeclContext()) &&
  2589. !(isExternC(Old) && isExternC(New)))
  2590. Old = nullptr;
  2591. if (!Old) {
  2592. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2593. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2594. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2595. return true;
  2596. }
  2597. return false;
  2598. }
  2599. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2600. const FunctionDecl *B) {
  2601. assert(A->getNumParams() == B->getNumParams());
  2602. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2603. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2604. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2605. if (AttrA == AttrB)
  2606. return true;
  2607. return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
  2608. AttrA->isDynamic() == AttrB->isDynamic();
  2609. };
  2610. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2611. }
  2612. /// If necessary, adjust the semantic declaration context for a qualified
  2613. /// declaration to name the correct inline namespace within the qualifier.
  2614. static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
  2615. DeclaratorDecl *OldD) {
  2616. // The only case where we need to update the DeclContext is when
  2617. // redeclaration lookup for a qualified name finds a declaration
  2618. // in an inline namespace within the context named by the qualifier:
  2619. //
  2620. // inline namespace N { int f(); }
  2621. // int ::f(); // Sema DC needs adjusting from :: to N::.
  2622. //
  2623. // For unqualified declarations, the semantic context *can* change
  2624. // along the redeclaration chain (for local extern declarations,
  2625. // extern "C" declarations, and friend declarations in particular).
  2626. if (!NewD->getQualifier())
  2627. return;
  2628. // NewD is probably already in the right context.
  2629. auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
  2630. auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
  2631. if (NamedDC->Equals(SemaDC))
  2632. return;
  2633. assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
  2634. NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
  2635. "unexpected context for redeclaration");
  2636. auto *LexDC = NewD->getLexicalDeclContext();
  2637. auto FixSemaDC = [=](NamedDecl *D) {
  2638. if (!D)
  2639. return;
  2640. D->setDeclContext(SemaDC);
  2641. D->setLexicalDeclContext(LexDC);
  2642. };
  2643. FixSemaDC(NewD);
  2644. if (auto *FD = dyn_cast<FunctionDecl>(NewD))
  2645. FixSemaDC(FD->getDescribedFunctionTemplate());
  2646. else if (auto *VD = dyn_cast<VarDecl>(NewD))
  2647. FixSemaDC(VD->getDescribedVarTemplate());
  2648. }
  2649. /// MergeFunctionDecl - We just parsed a function 'New' from
  2650. /// declarator D which has the same name and scope as a previous
  2651. /// declaration 'Old'. Figure out how to resolve this situation,
  2652. /// merging decls or emitting diagnostics as appropriate.
  2653. ///
  2654. /// In C++, New and Old must be declarations that are not
  2655. /// overloaded. Use IsOverload to determine whether New and Old are
  2656. /// overloaded, and to select the Old declaration that New should be
  2657. /// merged with.
  2658. ///
  2659. /// Returns true if there was an error, false otherwise.
  2660. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2661. Scope *S, bool MergeTypeWithOld) {
  2662. // Verify the old decl was also a function.
  2663. FunctionDecl *Old = OldD->getAsFunction();
  2664. if (!Old) {
  2665. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2666. if (New->getFriendObjectKind()) {
  2667. Diag(New->getLocation(), diag::err_using_decl_friend);
  2668. Diag(Shadow->getTargetDecl()->getLocation(),
  2669. diag::note_using_decl_target);
  2670. Diag(Shadow->getUsingDecl()->getLocation(),
  2671. diag::note_using_decl) << 0;
  2672. return true;
  2673. }
  2674. // Check whether the two declarations might declare the same function.
  2675. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2676. return true;
  2677. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2678. } else {
  2679. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2680. << New->getDeclName();
  2681. notePreviousDefinition(OldD, New->getLocation());
  2682. return true;
  2683. }
  2684. }
  2685. // If the old declaration is invalid, just give up here.
  2686. if (Old->isInvalidDecl())
  2687. return true;
  2688. // Disallow redeclaration of some builtins.
  2689. if (!getASTContext().canBuiltinBeRedeclared(Old)) {
  2690. Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
  2691. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  2692. << Old << Old->getType();
  2693. return true;
  2694. }
  2695. diag::kind PrevDiag;
  2696. SourceLocation OldLocation;
  2697. std::tie(PrevDiag, OldLocation) =
  2698. getNoteDiagForInvalidRedeclaration(Old, New);
  2699. // Don't complain about this if we're in GNU89 mode and the old function
  2700. // is an extern inline function.
  2701. // Don't complain about specializations. They are not supposed to have
  2702. // storage classes.
  2703. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2704. New->getStorageClass() == SC_Static &&
  2705. Old->hasExternalFormalLinkage() &&
  2706. !New->getTemplateSpecializationInfo() &&
  2707. !canRedefineFunction(Old, getLangOpts())) {
  2708. if (getLangOpts().MicrosoftExt) {
  2709. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2710. Diag(OldLocation, PrevDiag);
  2711. } else {
  2712. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2713. Diag(OldLocation, PrevDiag);
  2714. return true;
  2715. }
  2716. }
  2717. if (New->hasAttr<InternalLinkageAttr>() &&
  2718. !Old->hasAttr<InternalLinkageAttr>()) {
  2719. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  2720. << New->getDeclName();
  2721. notePreviousDefinition(Old, New->getLocation());
  2722. New->dropAttr<InternalLinkageAttr>();
  2723. }
  2724. if (CheckRedeclarationModuleOwnership(New, Old))
  2725. return true;
  2726. if (!getLangOpts().CPlusPlus) {
  2727. bool OldOvl = Old->hasAttr<OverloadableAttr>();
  2728. if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
  2729. Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
  2730. << New << OldOvl;
  2731. // Try our best to find a decl that actually has the overloadable
  2732. // attribute for the note. In most cases (e.g. programs with only one
  2733. // broken declaration/definition), this won't matter.
  2734. //
  2735. // FIXME: We could do this if we juggled some extra state in
  2736. // OverloadableAttr, rather than just removing it.
  2737. const Decl *DiagOld = Old;
  2738. if (OldOvl) {
  2739. auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
  2740. const auto *A = D->getAttr<OverloadableAttr>();
  2741. return A && !A->isImplicit();
  2742. });
  2743. // If we've implicitly added *all* of the overloadable attrs to this
  2744. // chain, emitting a "previous redecl" note is pointless.
  2745. DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
  2746. }
  2747. if (DiagOld)
  2748. Diag(DiagOld->getLocation(),
  2749. diag::note_attribute_overloadable_prev_overload)
  2750. << OldOvl;
  2751. if (OldOvl)
  2752. New->addAttr(OverloadableAttr::CreateImplicit(Context));
  2753. else
  2754. New->dropAttr<OverloadableAttr>();
  2755. }
  2756. }
  2757. // If a function is first declared with a calling convention, but is later
  2758. // declared or defined without one, all following decls assume the calling
  2759. // convention of the first.
  2760. //
  2761. // It's OK if a function is first declared without a calling convention,
  2762. // but is later declared or defined with the default calling convention.
  2763. //
  2764. // To test if either decl has an explicit calling convention, we look for
  2765. // AttributedType sugar nodes on the type as written. If they are missing or
  2766. // were canonicalized away, we assume the calling convention was implicit.
  2767. //
  2768. // Note also that we DO NOT return at this point, because we still have
  2769. // other tests to run.
  2770. QualType OldQType = Context.getCanonicalType(Old->getType());
  2771. QualType NewQType = Context.getCanonicalType(New->getType());
  2772. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2773. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2774. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2775. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2776. bool RequiresAdjustment = false;
  2777. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2778. FunctionDecl *First = Old->getFirstDecl();
  2779. const FunctionType *FT =
  2780. First->getType().getCanonicalType()->castAs<FunctionType>();
  2781. FunctionType::ExtInfo FI = FT->getExtInfo();
  2782. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2783. if (!NewCCExplicit) {
  2784. // Inherit the CC from the previous declaration if it was specified
  2785. // there but not here.
  2786. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2787. RequiresAdjustment = true;
  2788. } else if (New->getBuiltinID()) {
  2789. // Calling Conventions on a Builtin aren't really useful and setting a
  2790. // default calling convention and cdecl'ing some builtin redeclarations is
  2791. // common, so warn and ignore the calling convention on the redeclaration.
  2792. Diag(New->getLocation(), diag::warn_cconv_ignored)
  2793. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2794. << (int)CallingConventionIgnoredReason::BuiltinFunction;
  2795. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2796. RequiresAdjustment = true;
  2797. } else {
  2798. // Calling conventions aren't compatible, so complain.
  2799. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2800. Diag(New->getLocation(), diag::err_cconv_change)
  2801. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2802. << !FirstCCExplicit
  2803. << (!FirstCCExplicit ? "" :
  2804. FunctionType::getNameForCallConv(FI.getCC()));
  2805. // Put the note on the first decl, since it is the one that matters.
  2806. Diag(First->getLocation(), diag::note_previous_declaration);
  2807. return true;
  2808. }
  2809. }
  2810. // FIXME: diagnose the other way around?
  2811. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2812. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2813. RequiresAdjustment = true;
  2814. }
  2815. // Merge regparm attribute.
  2816. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2817. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2818. if (NewTypeInfo.getHasRegParm()) {
  2819. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2820. << NewType->getRegParmType()
  2821. << OldType->getRegParmType();
  2822. Diag(OldLocation, diag::note_previous_declaration);
  2823. return true;
  2824. }
  2825. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2826. RequiresAdjustment = true;
  2827. }
  2828. // Merge ns_returns_retained attribute.
  2829. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2830. if (NewTypeInfo.getProducesResult()) {
  2831. Diag(New->getLocation(), diag::err_function_attribute_mismatch)
  2832. << "'ns_returns_retained'";
  2833. Diag(OldLocation, diag::note_previous_declaration);
  2834. return true;
  2835. }
  2836. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2837. RequiresAdjustment = true;
  2838. }
  2839. if (OldTypeInfo.getNoCallerSavedRegs() !=
  2840. NewTypeInfo.getNoCallerSavedRegs()) {
  2841. if (NewTypeInfo.getNoCallerSavedRegs()) {
  2842. AnyX86NoCallerSavedRegistersAttr *Attr =
  2843. New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
  2844. Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
  2845. Diag(OldLocation, diag::note_previous_declaration);
  2846. return true;
  2847. }
  2848. NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
  2849. RequiresAdjustment = true;
  2850. }
  2851. if (RequiresAdjustment) {
  2852. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2853. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2854. New->setType(QualType(AdjustedType, 0));
  2855. NewQType = Context.getCanonicalType(New->getType());
  2856. NewType = cast<FunctionType>(NewQType);
  2857. }
  2858. // If this redeclaration makes the function inline, we may need to add it to
  2859. // UndefinedButUsed.
  2860. if (!Old->isInlined() && New->isInlined() &&
  2861. !New->hasAttr<GNUInlineAttr>() &&
  2862. !getLangOpts().GNUInline &&
  2863. Old->isUsed(false) &&
  2864. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2865. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2866. SourceLocation()));
  2867. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2868. // about it.
  2869. if (New->hasAttr<GNUInlineAttr>() &&
  2870. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2871. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2872. }
  2873. // If pass_object_size params don't match up perfectly, this isn't a valid
  2874. // redeclaration.
  2875. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  2876. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  2877. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  2878. << New->getDeclName();
  2879. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2880. return true;
  2881. }
  2882. if (getLangOpts().CPlusPlus) {
  2883. // C++1z [over.load]p2
  2884. // Certain function declarations cannot be overloaded:
  2885. // -- Function declarations that differ only in the return type,
  2886. // the exception specification, or both cannot be overloaded.
  2887. // Check the exception specifications match. This may recompute the type of
  2888. // both Old and New if it resolved exception specifications, so grab the
  2889. // types again after this. Because this updates the type, we do this before
  2890. // any of the other checks below, which may update the "de facto" NewQType
  2891. // but do not necessarily update the type of New.
  2892. if (CheckEquivalentExceptionSpec(Old, New))
  2893. return true;
  2894. OldQType = Context.getCanonicalType(Old->getType());
  2895. NewQType = Context.getCanonicalType(New->getType());
  2896. // Go back to the type source info to compare the declared return types,
  2897. // per C++1y [dcl.type.auto]p13:
  2898. // Redeclarations or specializations of a function or function template
  2899. // with a declared return type that uses a placeholder type shall also
  2900. // use that placeholder, not a deduced type.
  2901. QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
  2902. QualType NewDeclaredReturnType = New->getDeclaredReturnType();
  2903. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  2904. canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
  2905. OldDeclaredReturnType)) {
  2906. QualType ResQT;
  2907. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  2908. OldDeclaredReturnType->isObjCObjectPointerType())
  2909. // FIXME: This does the wrong thing for a deduced return type.
  2910. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  2911. if (ResQT.isNull()) {
  2912. if (New->isCXXClassMember() && New->isOutOfLine())
  2913. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  2914. << New << New->getReturnTypeSourceRange();
  2915. else
  2916. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  2917. << New->getReturnTypeSourceRange();
  2918. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  2919. << Old->getReturnTypeSourceRange();
  2920. return true;
  2921. }
  2922. else
  2923. NewQType = ResQT;
  2924. }
  2925. QualType OldReturnType = OldType->getReturnType();
  2926. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  2927. if (OldReturnType != NewReturnType) {
  2928. // If this function has a deduced return type and has already been
  2929. // defined, copy the deduced value from the old declaration.
  2930. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  2931. if (OldAT && OldAT->isDeduced()) {
  2932. New->setType(
  2933. SubstAutoType(New->getType(),
  2934. OldAT->isDependentType() ? Context.DependentTy
  2935. : OldAT->getDeducedType()));
  2936. NewQType = Context.getCanonicalType(
  2937. SubstAutoType(NewQType,
  2938. OldAT->isDependentType() ? Context.DependentTy
  2939. : OldAT->getDeducedType()));
  2940. }
  2941. }
  2942. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  2943. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  2944. if (OldMethod && NewMethod) {
  2945. // Preserve triviality.
  2946. NewMethod->setTrivial(OldMethod->isTrivial());
  2947. // MSVC allows explicit template specialization at class scope:
  2948. // 2 CXXMethodDecls referring to the same function will be injected.
  2949. // We don't want a redeclaration error.
  2950. bool IsClassScopeExplicitSpecialization =
  2951. OldMethod->isFunctionTemplateSpecialization() &&
  2952. NewMethod->isFunctionTemplateSpecialization();
  2953. bool isFriend = NewMethod->getFriendObjectKind();
  2954. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  2955. !IsClassScopeExplicitSpecialization) {
  2956. // -- Member function declarations with the same name and the
  2957. // same parameter types cannot be overloaded if any of them
  2958. // is a static member function declaration.
  2959. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  2960. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  2961. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2962. return true;
  2963. }
  2964. // C++ [class.mem]p1:
  2965. // [...] A member shall not be declared twice in the
  2966. // member-specification, except that a nested class or member
  2967. // class template can be declared and then later defined.
  2968. if (!inTemplateInstantiation()) {
  2969. unsigned NewDiag;
  2970. if (isa<CXXConstructorDecl>(OldMethod))
  2971. NewDiag = diag::err_constructor_redeclared;
  2972. else if (isa<CXXDestructorDecl>(NewMethod))
  2973. NewDiag = diag::err_destructor_redeclared;
  2974. else if (isa<CXXConversionDecl>(NewMethod))
  2975. NewDiag = diag::err_conv_function_redeclared;
  2976. else
  2977. NewDiag = diag::err_member_redeclared;
  2978. Diag(New->getLocation(), NewDiag);
  2979. } else {
  2980. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2981. << New << New->getType();
  2982. }
  2983. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2984. return true;
  2985. // Complain if this is an explicit declaration of a special
  2986. // member that was initially declared implicitly.
  2987. //
  2988. // As an exception, it's okay to befriend such methods in order
  2989. // to permit the implicit constructor/destructor/operator calls.
  2990. } else if (OldMethod->isImplicit()) {
  2991. if (isFriend) {
  2992. NewMethod->setImplicit();
  2993. } else {
  2994. Diag(NewMethod->getLocation(),
  2995. diag::err_definition_of_implicitly_declared_member)
  2996. << New << getSpecialMember(OldMethod);
  2997. return true;
  2998. }
  2999. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  3000. Diag(NewMethod->getLocation(),
  3001. diag::err_definition_of_explicitly_defaulted_member)
  3002. << getSpecialMember(OldMethod);
  3003. return true;
  3004. }
  3005. }
  3006. // C++11 [dcl.attr.noreturn]p1:
  3007. // The first declaration of a function shall specify the noreturn
  3008. // attribute if any declaration of that function specifies the noreturn
  3009. // attribute.
  3010. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  3011. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  3012. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  3013. Diag(Old->getFirstDecl()->getLocation(),
  3014. diag::note_noreturn_missing_first_decl);
  3015. }
  3016. // C++11 [dcl.attr.depend]p2:
  3017. // The first declaration of a function shall specify the
  3018. // carries_dependency attribute for its declarator-id if any declaration
  3019. // of the function specifies the carries_dependency attribute.
  3020. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  3021. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  3022. Diag(CDA->getLocation(),
  3023. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  3024. Diag(Old->getFirstDecl()->getLocation(),
  3025. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  3026. }
  3027. // (C++98 8.3.5p3):
  3028. // All declarations for a function shall agree exactly in both the
  3029. // return type and the parameter-type-list.
  3030. // We also want to respect all the extended bits except noreturn.
  3031. // noreturn should now match unless the old type info didn't have it.
  3032. QualType OldQTypeForComparison = OldQType;
  3033. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  3034. auto *OldType = OldQType->castAs<FunctionProtoType>();
  3035. const FunctionType *OldTypeForComparison
  3036. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  3037. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  3038. assert(OldQTypeForComparison.isCanonical());
  3039. }
  3040. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3041. // As a special case, retain the language linkage from previous
  3042. // declarations of a friend function as an extension.
  3043. //
  3044. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  3045. // and is useful because there's otherwise no way to specify language
  3046. // linkage within class scope.
  3047. //
  3048. // Check cautiously as the friend object kind isn't yet complete.
  3049. if (New->getFriendObjectKind() != Decl::FOK_None) {
  3050. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  3051. Diag(OldLocation, PrevDiag);
  3052. } else {
  3053. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3054. Diag(OldLocation, PrevDiag);
  3055. return true;
  3056. }
  3057. }
  3058. if (OldQTypeForComparison == NewQType)
  3059. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3060. // If the types are imprecise (due to dependent constructs in friends or
  3061. // local extern declarations), it's OK if they differ. We'll check again
  3062. // during instantiation.
  3063. if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
  3064. return false;
  3065. // Fall through for conflicting redeclarations and redefinitions.
  3066. }
  3067. // C: Function types need to be compatible, not identical. This handles
  3068. // duplicate function decls like "void f(int); void f(enum X);" properly.
  3069. if (!getLangOpts().CPlusPlus &&
  3070. Context.typesAreCompatible(OldQType, NewQType)) {
  3071. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  3072. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  3073. const FunctionProtoType *OldProto = nullptr;
  3074. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  3075. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  3076. // The old declaration provided a function prototype, but the
  3077. // new declaration does not. Merge in the prototype.
  3078. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  3079. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  3080. NewQType =
  3081. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  3082. OldProto->getExtProtoInfo());
  3083. New->setType(NewQType);
  3084. New->setHasInheritedPrototype();
  3085. // Synthesize parameters with the same types.
  3086. SmallVector<ParmVarDecl*, 16> Params;
  3087. for (const auto &ParamType : OldProto->param_types()) {
  3088. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  3089. SourceLocation(), nullptr,
  3090. ParamType, /*TInfo=*/nullptr,
  3091. SC_None, nullptr);
  3092. Param->setScopeInfo(0, Params.size());
  3093. Param->setImplicit();
  3094. Params.push_back(Param);
  3095. }
  3096. New->setParams(Params);
  3097. }
  3098. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3099. }
  3100. // GNU C permits a K&R definition to follow a prototype declaration
  3101. // if the declared types of the parameters in the K&R definition
  3102. // match the types in the prototype declaration, even when the
  3103. // promoted types of the parameters from the K&R definition differ
  3104. // from the types in the prototype. GCC then keeps the types from
  3105. // the prototype.
  3106. //
  3107. // If a variadic prototype is followed by a non-variadic K&R definition,
  3108. // the K&R definition becomes variadic. This is sort of an edge case, but
  3109. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  3110. // C99 6.9.1p8.
  3111. if (!getLangOpts().CPlusPlus &&
  3112. Old->hasPrototype() && !New->hasPrototype() &&
  3113. New->getType()->getAs<FunctionProtoType>() &&
  3114. Old->getNumParams() == New->getNumParams()) {
  3115. SmallVector<QualType, 16> ArgTypes;
  3116. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  3117. const FunctionProtoType *OldProto
  3118. = Old->getType()->getAs<FunctionProtoType>();
  3119. const FunctionProtoType *NewProto
  3120. = New->getType()->getAs<FunctionProtoType>();
  3121. // Determine whether this is the GNU C extension.
  3122. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  3123. NewProto->getReturnType());
  3124. bool LooseCompatible = !MergedReturn.isNull();
  3125. for (unsigned Idx = 0, End = Old->getNumParams();
  3126. LooseCompatible && Idx != End; ++Idx) {
  3127. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  3128. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  3129. if (Context.typesAreCompatible(OldParm->getType(),
  3130. NewProto->getParamType(Idx))) {
  3131. ArgTypes.push_back(NewParm->getType());
  3132. } else if (Context.typesAreCompatible(OldParm->getType(),
  3133. NewParm->getType(),
  3134. /*CompareUnqualified=*/true)) {
  3135. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  3136. NewProto->getParamType(Idx) };
  3137. Warnings.push_back(Warn);
  3138. ArgTypes.push_back(NewParm->getType());
  3139. } else
  3140. LooseCompatible = false;
  3141. }
  3142. if (LooseCompatible) {
  3143. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  3144. Diag(Warnings[Warn].NewParm->getLocation(),
  3145. diag::ext_param_promoted_not_compatible_with_prototype)
  3146. << Warnings[Warn].PromotedType
  3147. << Warnings[Warn].OldParm->getType();
  3148. if (Warnings[Warn].OldParm->getLocation().isValid())
  3149. Diag(Warnings[Warn].OldParm->getLocation(),
  3150. diag::note_previous_declaration);
  3151. }
  3152. if (MergeTypeWithOld)
  3153. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  3154. OldProto->getExtProtoInfo()));
  3155. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3156. }
  3157. // Fall through to diagnose conflicting types.
  3158. }
  3159. // A function that has already been declared has been redeclared or
  3160. // defined with a different type; show an appropriate diagnostic.
  3161. // If the previous declaration was an implicitly-generated builtin
  3162. // declaration, then at the very least we should use a specialized note.
  3163. unsigned BuiltinID;
  3164. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  3165. // If it's actually a library-defined builtin function like 'malloc'
  3166. // or 'printf', just warn about the incompatible redeclaration.
  3167. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  3168. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  3169. Diag(OldLocation, diag::note_previous_builtin_declaration)
  3170. << Old << Old->getType();
  3171. // If this is a global redeclaration, just forget hereafter
  3172. // about the "builtin-ness" of the function.
  3173. //
  3174. // Doing this for local extern declarations is problematic. If
  3175. // the builtin declaration remains visible, a second invalid
  3176. // local declaration will produce a hard error; if it doesn't
  3177. // remain visible, a single bogus local redeclaration (which is
  3178. // actually only a warning) could break all the downstream code.
  3179. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  3180. New->getIdentifier()->revertBuiltin();
  3181. return false;
  3182. }
  3183. PrevDiag = diag::note_previous_builtin_declaration;
  3184. }
  3185. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  3186. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3187. return true;
  3188. }
  3189. /// Completes the merge of two function declarations that are
  3190. /// known to be compatible.
  3191. ///
  3192. /// This routine handles the merging of attributes and other
  3193. /// properties of function declarations from the old declaration to
  3194. /// the new declaration, once we know that New is in fact a
  3195. /// redeclaration of Old.
  3196. ///
  3197. /// \returns false
  3198. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  3199. Scope *S, bool MergeTypeWithOld) {
  3200. // Merge the attributes
  3201. mergeDeclAttributes(New, Old);
  3202. // Merge "pure" flag.
  3203. if (Old->isPure())
  3204. New->setPure();
  3205. // Merge "used" flag.
  3206. if (Old->getMostRecentDecl()->isUsed(false))
  3207. New->setIsUsed();
  3208. // Merge attributes from the parameters. These can mismatch with K&R
  3209. // declarations.
  3210. if (New->getNumParams() == Old->getNumParams())
  3211. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  3212. ParmVarDecl *NewParam = New->getParamDecl(i);
  3213. ParmVarDecl *OldParam = Old->getParamDecl(i);
  3214. mergeParamDeclAttributes(NewParam, OldParam, *this);
  3215. mergeParamDeclTypes(NewParam, OldParam, *this);
  3216. }
  3217. if (getLangOpts().CPlusPlus)
  3218. return MergeCXXFunctionDecl(New, Old, S);
  3219. // Merge the function types so the we get the composite types for the return
  3220. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  3221. // was visible.
  3222. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  3223. if (!Merged.isNull() && MergeTypeWithOld)
  3224. New->setType(Merged);
  3225. return false;
  3226. }
  3227. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  3228. ObjCMethodDecl *oldMethod) {
  3229. // Merge the attributes, including deprecated/unavailable
  3230. AvailabilityMergeKind MergeKind =
  3231. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  3232. ? AMK_ProtocolImplementation
  3233. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  3234. : AMK_Override;
  3235. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  3236. // Merge attributes from the parameters.
  3237. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3238. oe = oldMethod->param_end();
  3239. for (ObjCMethodDecl::param_iterator
  3240. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3241. ni != ne && oi != oe; ++ni, ++oi)
  3242. mergeParamDeclAttributes(*ni, *oi, *this);
  3243. CheckObjCMethodOverride(newMethod, oldMethod);
  3244. }
  3245. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3246. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3247. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3248. ? diag::err_redefinition_different_type
  3249. : diag::err_redeclaration_different_type)
  3250. << New->getDeclName() << New->getType() << Old->getType();
  3251. diag::kind PrevDiag;
  3252. SourceLocation OldLocation;
  3253. std::tie(PrevDiag, OldLocation)
  3254. = getNoteDiagForInvalidRedeclaration(Old, New);
  3255. S.Diag(OldLocation, PrevDiag);
  3256. New->setInvalidDecl();
  3257. }
  3258. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3259. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3260. /// emitting diagnostics as appropriate.
  3261. ///
  3262. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3263. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3264. /// is attached.
  3265. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3266. bool MergeTypeWithOld) {
  3267. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3268. return;
  3269. QualType MergedT;
  3270. if (getLangOpts().CPlusPlus) {
  3271. if (New->getType()->isUndeducedType()) {
  3272. // We don't know what the new type is until the initializer is attached.
  3273. return;
  3274. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3275. // These could still be something that needs exception specs checked.
  3276. return MergeVarDeclExceptionSpecs(New, Old);
  3277. }
  3278. // C++ [basic.link]p10:
  3279. // [...] the types specified by all declarations referring to a given
  3280. // object or function shall be identical, except that declarations for an
  3281. // array object can specify array types that differ by the presence or
  3282. // absence of a major array bound (8.3.4).
  3283. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3284. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3285. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3286. // We are merging a variable declaration New into Old. If it has an array
  3287. // bound, and that bound differs from Old's bound, we should diagnose the
  3288. // mismatch.
  3289. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3290. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3291. PrevVD = PrevVD->getPreviousDecl()) {
  3292. const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
  3293. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3294. continue;
  3295. if (!Context.hasSameType(NewArray, PrevVDTy))
  3296. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3297. }
  3298. }
  3299. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3300. if (Context.hasSameType(OldArray->getElementType(),
  3301. NewArray->getElementType()))
  3302. MergedT = New->getType();
  3303. }
  3304. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3305. // has no array bound, it should not inherit one from Old, if Old is not
  3306. // visible.
  3307. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3308. if (Context.hasSameType(OldArray->getElementType(),
  3309. NewArray->getElementType()))
  3310. MergedT = Old->getType();
  3311. }
  3312. }
  3313. else if (New->getType()->isObjCObjectPointerType() &&
  3314. Old->getType()->isObjCObjectPointerType()) {
  3315. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3316. Old->getType());
  3317. }
  3318. } else {
  3319. // C 6.2.7p2:
  3320. // All declarations that refer to the same object or function shall have
  3321. // compatible type.
  3322. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3323. }
  3324. if (MergedT.isNull()) {
  3325. // It's OK if we couldn't merge types if either type is dependent, for a
  3326. // block-scope variable. In other cases (static data members of class
  3327. // templates, variable templates, ...), we require the types to be
  3328. // equivalent.
  3329. // FIXME: The C++ standard doesn't say anything about this.
  3330. if ((New->getType()->isDependentType() ||
  3331. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3332. // If the old type was dependent, we can't merge with it, so the new type
  3333. // becomes dependent for now. We'll reproduce the original type when we
  3334. // instantiate the TypeSourceInfo for the variable.
  3335. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3336. New->setType(Context.DependentTy);
  3337. return;
  3338. }
  3339. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3340. }
  3341. // Don't actually update the type on the new declaration if the old
  3342. // declaration was an extern declaration in a different scope.
  3343. if (MergeTypeWithOld)
  3344. New->setType(MergedT);
  3345. }
  3346. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3347. LookupResult &Previous) {
  3348. // C11 6.2.7p4:
  3349. // For an identifier with internal or external linkage declared
  3350. // in a scope in which a prior declaration of that identifier is
  3351. // visible, if the prior declaration specifies internal or
  3352. // external linkage, the type of the identifier at the later
  3353. // declaration becomes the composite type.
  3354. //
  3355. // If the variable isn't visible, we do not merge with its type.
  3356. if (Previous.isShadowed())
  3357. return false;
  3358. if (S.getLangOpts().CPlusPlus) {
  3359. // C++11 [dcl.array]p3:
  3360. // If there is a preceding declaration of the entity in the same
  3361. // scope in which the bound was specified, an omitted array bound
  3362. // is taken to be the same as in that earlier declaration.
  3363. return NewVD->isPreviousDeclInSameBlockScope() ||
  3364. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3365. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3366. } else {
  3367. // If the old declaration was function-local, don't merge with its
  3368. // type unless we're in the same function.
  3369. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3370. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3371. }
  3372. }
  3373. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3374. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3375. /// situation, merging decls or emitting diagnostics as appropriate.
  3376. ///
  3377. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3378. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3379. /// definitions here, since the initializer hasn't been attached.
  3380. ///
  3381. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3382. // If the new decl is already invalid, don't do any other checking.
  3383. if (New->isInvalidDecl())
  3384. return;
  3385. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3386. return;
  3387. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3388. // Verify the old decl was also a variable or variable template.
  3389. VarDecl *Old = nullptr;
  3390. VarTemplateDecl *OldTemplate = nullptr;
  3391. if (Previous.isSingleResult()) {
  3392. if (NewTemplate) {
  3393. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3394. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3395. if (auto *Shadow =
  3396. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3397. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3398. return New->setInvalidDecl();
  3399. } else {
  3400. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3401. if (auto *Shadow =
  3402. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3403. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3404. return New->setInvalidDecl();
  3405. }
  3406. }
  3407. if (!Old) {
  3408. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3409. << New->getDeclName();
  3410. notePreviousDefinition(Previous.getRepresentativeDecl(),
  3411. New->getLocation());
  3412. return New->setInvalidDecl();
  3413. }
  3414. // Ensure the template parameters are compatible.
  3415. if (NewTemplate &&
  3416. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3417. OldTemplate->getTemplateParameters(),
  3418. /*Complain=*/true, TPL_TemplateMatch))
  3419. return New->setInvalidDecl();
  3420. // C++ [class.mem]p1:
  3421. // A member shall not be declared twice in the member-specification [...]
  3422. //
  3423. // Here, we need only consider static data members.
  3424. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3425. Diag(New->getLocation(), diag::err_duplicate_member)
  3426. << New->getIdentifier();
  3427. Diag(Old->getLocation(), diag::note_previous_declaration);
  3428. New->setInvalidDecl();
  3429. }
  3430. mergeDeclAttributes(New, Old);
  3431. // Warn if an already-declared variable is made a weak_import in a subsequent
  3432. // declaration
  3433. if (New->hasAttr<WeakImportAttr>() &&
  3434. Old->getStorageClass() == SC_None &&
  3435. !Old->hasAttr<WeakImportAttr>()) {
  3436. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3437. notePreviousDefinition(Old, New->getLocation());
  3438. // Remove weak_import attribute on new declaration.
  3439. New->dropAttr<WeakImportAttr>();
  3440. }
  3441. if (New->hasAttr<InternalLinkageAttr>() &&
  3442. !Old->hasAttr<InternalLinkageAttr>()) {
  3443. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  3444. << New->getDeclName();
  3445. notePreviousDefinition(Old, New->getLocation());
  3446. New->dropAttr<InternalLinkageAttr>();
  3447. }
  3448. // Merge the types.
  3449. VarDecl *MostRecent = Old->getMostRecentDecl();
  3450. if (MostRecent != Old) {
  3451. MergeVarDeclTypes(New, MostRecent,
  3452. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3453. if (New->isInvalidDecl())
  3454. return;
  3455. }
  3456. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3457. if (New->isInvalidDecl())
  3458. return;
  3459. diag::kind PrevDiag;
  3460. SourceLocation OldLocation;
  3461. std::tie(PrevDiag, OldLocation) =
  3462. getNoteDiagForInvalidRedeclaration(Old, New);
  3463. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3464. if (New->getStorageClass() == SC_Static &&
  3465. !New->isStaticDataMember() &&
  3466. Old->hasExternalFormalLinkage()) {
  3467. if (getLangOpts().MicrosoftExt) {
  3468. Diag(New->getLocation(), diag::ext_static_non_static)
  3469. << New->getDeclName();
  3470. Diag(OldLocation, PrevDiag);
  3471. } else {
  3472. Diag(New->getLocation(), diag::err_static_non_static)
  3473. << New->getDeclName();
  3474. Diag(OldLocation, PrevDiag);
  3475. return New->setInvalidDecl();
  3476. }
  3477. }
  3478. // C99 6.2.2p4:
  3479. // For an identifier declared with the storage-class specifier
  3480. // extern in a scope in which a prior declaration of that
  3481. // identifier is visible,23) if the prior declaration specifies
  3482. // internal or external linkage, the linkage of the identifier at
  3483. // the later declaration is the same as the linkage specified at
  3484. // the prior declaration. If no prior declaration is visible, or
  3485. // if the prior declaration specifies no linkage, then the
  3486. // identifier has external linkage.
  3487. if (New->hasExternalStorage() && Old->hasLinkage())
  3488. /* Okay */;
  3489. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3490. !New->isStaticDataMember() &&
  3491. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3492. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3493. Diag(OldLocation, PrevDiag);
  3494. return New->setInvalidDecl();
  3495. }
  3496. // Check if extern is followed by non-extern and vice-versa.
  3497. if (New->hasExternalStorage() &&
  3498. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3499. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3500. Diag(OldLocation, PrevDiag);
  3501. return New->setInvalidDecl();
  3502. }
  3503. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3504. !New->hasExternalStorage()) {
  3505. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3506. Diag(OldLocation, PrevDiag);
  3507. return New->setInvalidDecl();
  3508. }
  3509. if (CheckRedeclarationModuleOwnership(New, Old))
  3510. return;
  3511. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3512. // FIXME: The test for external storage here seems wrong? We still
  3513. // need to check for mismatches.
  3514. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3515. // Don't complain about out-of-line definitions of static members.
  3516. !(Old->getLexicalDeclContext()->isRecord() &&
  3517. !New->getLexicalDeclContext()->isRecord())) {
  3518. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3519. Diag(OldLocation, PrevDiag);
  3520. return New->setInvalidDecl();
  3521. }
  3522. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3523. if (VarDecl *Def = Old->getDefinition()) {
  3524. // C++1z [dcl.fcn.spec]p4:
  3525. // If the definition of a variable appears in a translation unit before
  3526. // its first declaration as inline, the program is ill-formed.
  3527. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3528. Diag(Def->getLocation(), diag::note_previous_definition);
  3529. }
  3530. }
  3531. // If this redeclaration makes the variable inline, we may need to add it to
  3532. // UndefinedButUsed.
  3533. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3534. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3535. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3536. SourceLocation()));
  3537. if (New->getTLSKind() != Old->getTLSKind()) {
  3538. if (!Old->getTLSKind()) {
  3539. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3540. Diag(OldLocation, PrevDiag);
  3541. } else if (!New->getTLSKind()) {
  3542. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3543. Diag(OldLocation, PrevDiag);
  3544. } else {
  3545. // Do not allow redeclaration to change the variable between requiring
  3546. // static and dynamic initialization.
  3547. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3548. // declaration to determine the kind. Do we need to be compatible here?
  3549. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3550. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3551. Diag(OldLocation, PrevDiag);
  3552. }
  3553. }
  3554. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3555. if (getLangOpts().CPlusPlus &&
  3556. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3557. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3558. Old->getCanonicalDecl()->isConstexpr()) {
  3559. // This definition won't be a definition any more once it's been merged.
  3560. Diag(New->getLocation(),
  3561. diag::warn_deprecated_redundant_constexpr_static_def);
  3562. } else if (VarDecl *Def = Old->getDefinition()) {
  3563. if (checkVarDeclRedefinition(Def, New))
  3564. return;
  3565. }
  3566. }
  3567. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3568. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3569. Diag(OldLocation, PrevDiag);
  3570. New->setInvalidDecl();
  3571. return;
  3572. }
  3573. // Merge "used" flag.
  3574. if (Old->getMostRecentDecl()->isUsed(false))
  3575. New->setIsUsed();
  3576. // Keep a chain of previous declarations.
  3577. New->setPreviousDecl(Old);
  3578. if (NewTemplate)
  3579. NewTemplate->setPreviousDecl(OldTemplate);
  3580. adjustDeclContextForDeclaratorDecl(New, Old);
  3581. // Inherit access appropriately.
  3582. New->setAccess(Old->getAccess());
  3583. if (NewTemplate)
  3584. NewTemplate->setAccess(New->getAccess());
  3585. if (Old->isInline())
  3586. New->setImplicitlyInline();
  3587. }
  3588. void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
  3589. SourceManager &SrcMgr = getSourceManager();
  3590. auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
  3591. auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
  3592. auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
  3593. auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
  3594. auto &HSI = PP.getHeaderSearchInfo();
  3595. StringRef HdrFilename =
  3596. SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
  3597. auto noteFromModuleOrInclude = [&](Module *Mod,
  3598. SourceLocation IncLoc) -> bool {
  3599. // Redefinition errors with modules are common with non modular mapped
  3600. // headers, example: a non-modular header H in module A that also gets
  3601. // included directly in a TU. Pointing twice to the same header/definition
  3602. // is confusing, try to get better diagnostics when modules is on.
  3603. if (IncLoc.isValid()) {
  3604. if (Mod) {
  3605. Diag(IncLoc, diag::note_redefinition_modules_same_file)
  3606. << HdrFilename.str() << Mod->getFullModuleName();
  3607. if (!Mod->DefinitionLoc.isInvalid())
  3608. Diag(Mod->DefinitionLoc, diag::note_defined_here)
  3609. << Mod->getFullModuleName();
  3610. } else {
  3611. Diag(IncLoc, diag::note_redefinition_include_same_file)
  3612. << HdrFilename.str();
  3613. }
  3614. return true;
  3615. }
  3616. return false;
  3617. };
  3618. // Is it the same file and same offset? Provide more information on why
  3619. // this leads to a redefinition error.
  3620. bool EmittedDiag = false;
  3621. if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
  3622. SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
  3623. SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
  3624. EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
  3625. EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
  3626. // If the header has no guards, emit a note suggesting one.
  3627. if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
  3628. Diag(Old->getLocation(), diag::note_use_ifdef_guards);
  3629. if (EmittedDiag)
  3630. return;
  3631. }
  3632. // Redefinition coming from different files or couldn't do better above.
  3633. if (Old->getLocation().isValid())
  3634. Diag(Old->getLocation(), diag::note_previous_definition);
  3635. }
  3636. /// We've just determined that \p Old and \p New both appear to be definitions
  3637. /// of the same variable. Either diagnose or fix the problem.
  3638. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3639. if (!hasVisibleDefinition(Old) &&
  3640. (New->getFormalLinkage() == InternalLinkage ||
  3641. New->isInline() ||
  3642. New->getDescribedVarTemplate() ||
  3643. New->getNumTemplateParameterLists() ||
  3644. New->getDeclContext()->isDependentContext())) {
  3645. // The previous definition is hidden, and multiple definitions are
  3646. // permitted (in separate TUs). Demote this to a declaration.
  3647. New->demoteThisDefinitionToDeclaration();
  3648. // Make the canonical definition visible.
  3649. if (auto *OldTD = Old->getDescribedVarTemplate())
  3650. makeMergedDefinitionVisible(OldTD);
  3651. makeMergedDefinitionVisible(Old);
  3652. return false;
  3653. } else {
  3654. Diag(New->getLocation(), diag::err_redefinition) << New;
  3655. notePreviousDefinition(Old, New->getLocation());
  3656. New->setInvalidDecl();
  3657. return true;
  3658. }
  3659. }
  3660. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3661. /// no declarator (e.g. "struct foo;") is parsed.
  3662. Decl *
  3663. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3664. RecordDecl *&AnonRecord) {
  3665. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3666. AnonRecord);
  3667. }
  3668. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3669. // disambiguate entities defined in different scopes.
  3670. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3671. // compatibility.
  3672. // We will pick our mangling number depending on which version of MSVC is being
  3673. // targeted.
  3674. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3675. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3676. ? S->getMSCurManglingNumber()
  3677. : S->getMSLastManglingNumber();
  3678. }
  3679. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3680. if (!Context.getLangOpts().CPlusPlus)
  3681. return;
  3682. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3683. // If this tag is the direct child of a class, number it if
  3684. // it is anonymous.
  3685. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3686. return;
  3687. MangleNumberingContext &MCtx =
  3688. Context.getManglingNumberContext(Tag->getParent());
  3689. Context.setManglingNumber(
  3690. Tag, MCtx.getManglingNumber(
  3691. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3692. return;
  3693. }
  3694. // If this tag isn't a direct child of a class, number it if it is local.
  3695. Decl *ManglingContextDecl;
  3696. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3697. Tag->getDeclContext(), ManglingContextDecl)) {
  3698. Context.setManglingNumber(
  3699. Tag, MCtx->getManglingNumber(
  3700. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3701. }
  3702. }
  3703. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3704. TypedefNameDecl *NewTD) {
  3705. if (TagFromDeclSpec->isInvalidDecl())
  3706. return;
  3707. // Do nothing if the tag already has a name for linkage purposes.
  3708. if (TagFromDeclSpec->hasNameForLinkage())
  3709. return;
  3710. // A well-formed anonymous tag must always be a TUK_Definition.
  3711. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3712. // The type must match the tag exactly; no qualifiers allowed.
  3713. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3714. Context.getTagDeclType(TagFromDeclSpec))) {
  3715. if (getLangOpts().CPlusPlus)
  3716. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3717. return;
  3718. }
  3719. // If we've already computed linkage for the anonymous tag, then
  3720. // adding a typedef name for the anonymous decl can change that
  3721. // linkage, which might be a serious problem. Diagnose this as
  3722. // unsupported and ignore the typedef name. TODO: we should
  3723. // pursue this as a language defect and establish a formal rule
  3724. // for how to handle it.
  3725. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3726. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3727. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3728. tagLoc = getLocForEndOfToken(tagLoc);
  3729. llvm::SmallString<40> textToInsert;
  3730. textToInsert += ' ';
  3731. textToInsert += NewTD->getIdentifier()->getName();
  3732. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3733. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3734. return;
  3735. }
  3736. // Otherwise, set this is the anon-decl typedef for the tag.
  3737. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3738. }
  3739. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3740. switch (T) {
  3741. case DeclSpec::TST_class:
  3742. return 0;
  3743. case DeclSpec::TST_struct:
  3744. return 1;
  3745. case DeclSpec::TST_interface:
  3746. return 2;
  3747. case DeclSpec::TST_union:
  3748. return 3;
  3749. case DeclSpec::TST_enum:
  3750. return 4;
  3751. default:
  3752. llvm_unreachable("unexpected type specifier");
  3753. }
  3754. }
  3755. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3756. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3757. /// parameters to cope with template friend declarations.
  3758. Decl *
  3759. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3760. MultiTemplateParamsArg TemplateParams,
  3761. bool IsExplicitInstantiation,
  3762. RecordDecl *&AnonRecord) {
  3763. Decl *TagD = nullptr;
  3764. TagDecl *Tag = nullptr;
  3765. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3766. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3767. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3768. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3769. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3770. TagD = DS.getRepAsDecl();
  3771. if (!TagD) // We probably had an error
  3772. return nullptr;
  3773. // Note that the above type specs guarantee that the
  3774. // type rep is a Decl, whereas in many of the others
  3775. // it's a Type.
  3776. if (isa<TagDecl>(TagD))
  3777. Tag = cast<TagDecl>(TagD);
  3778. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3779. Tag = CTD->getTemplatedDecl();
  3780. }
  3781. if (Tag) {
  3782. handleTagNumbering(Tag, S);
  3783. Tag->setFreeStanding();
  3784. if (Tag->isInvalidDecl())
  3785. return Tag;
  3786. }
  3787. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3788. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3789. // or incomplete types shall not be restrict-qualified."
  3790. if (TypeQuals & DeclSpec::TQ_restrict)
  3791. Diag(DS.getRestrictSpecLoc(),
  3792. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3793. << DS.getSourceRange();
  3794. }
  3795. if (DS.isInlineSpecified())
  3796. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  3797. << getLangOpts().CPlusPlus17;
  3798. if (DS.isConstexprSpecified()) {
  3799. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3800. // and definitions of functions and variables.
  3801. if (Tag)
  3802. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3803. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
  3804. else
  3805. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  3806. // Don't emit warnings after this error.
  3807. return TagD;
  3808. }
  3809. DiagnoseFunctionSpecifiers(DS);
  3810. if (DS.isFriendSpecified()) {
  3811. // If we're dealing with a decl but not a TagDecl, assume that
  3812. // whatever routines created it handled the friendship aspect.
  3813. if (TagD && !Tag)
  3814. return nullptr;
  3815. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3816. }
  3817. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3818. bool IsExplicitSpecialization =
  3819. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3820. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3821. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  3822. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  3823. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3824. // nested-name-specifier unless it is an explicit instantiation
  3825. // or an explicit specialization.
  3826. //
  3827. // FIXME: We allow class template partial specializations here too, per the
  3828. // obvious intent of DR1819.
  3829. //
  3830. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3831. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3832. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3833. return nullptr;
  3834. }
  3835. // Track whether this decl-specifier declares anything.
  3836. bool DeclaresAnything = true;
  3837. // Handle anonymous struct definitions.
  3838. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3839. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3840. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3841. if (getLangOpts().CPlusPlus ||
  3842. Record->getDeclContext()->isRecord()) {
  3843. // If CurContext is a DeclContext that can contain statements,
  3844. // RecursiveASTVisitor won't visit the decls that
  3845. // BuildAnonymousStructOrUnion() will put into CurContext.
  3846. // Also store them here so that they can be part of the
  3847. // DeclStmt that gets created in this case.
  3848. // FIXME: Also return the IndirectFieldDecls created by
  3849. // BuildAnonymousStructOr union, for the same reason?
  3850. if (CurContext->isFunctionOrMethod())
  3851. AnonRecord = Record;
  3852. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3853. Context.getPrintingPolicy());
  3854. }
  3855. DeclaresAnything = false;
  3856. }
  3857. }
  3858. // C11 6.7.2.1p2:
  3859. // A struct-declaration that does not declare an anonymous structure or
  3860. // anonymous union shall contain a struct-declarator-list.
  3861. //
  3862. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3863. // did not permit a struct-declaration without a struct-declarator-list.
  3864. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3865. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3866. // Check for Microsoft C extension: anonymous struct/union member.
  3867. // Handle 2 kinds of anonymous struct/union:
  3868. // struct STRUCT;
  3869. // union UNION;
  3870. // and
  3871. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3872. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3873. if ((Tag && Tag->getDeclName()) ||
  3874. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3875. RecordDecl *Record = nullptr;
  3876. if (Tag)
  3877. Record = dyn_cast<RecordDecl>(Tag);
  3878. else if (const RecordType *RT =
  3879. DS.getRepAsType().get()->getAsStructureType())
  3880. Record = RT->getDecl();
  3881. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3882. Record = UT->getDecl();
  3883. if (Record && getLangOpts().MicrosoftExt) {
  3884. Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
  3885. << Record->isUnion() << DS.getSourceRange();
  3886. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3887. }
  3888. DeclaresAnything = false;
  3889. }
  3890. }
  3891. // Skip all the checks below if we have a type error.
  3892. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3893. (TagD && TagD->isInvalidDecl()))
  3894. return TagD;
  3895. if (getLangOpts().CPlusPlus &&
  3896. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3897. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  3898. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  3899. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  3900. DeclaresAnything = false;
  3901. if (!DS.isMissingDeclaratorOk()) {
  3902. // Customize diagnostic for a typedef missing a name.
  3903. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  3904. Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
  3905. << DS.getSourceRange();
  3906. else
  3907. DeclaresAnything = false;
  3908. }
  3909. if (DS.isModulePrivateSpecified() &&
  3910. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  3911. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  3912. << Tag->getTagKind()
  3913. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  3914. ActOnDocumentableDecl(TagD);
  3915. // C 6.7/2:
  3916. // A declaration [...] shall declare at least a declarator [...], a tag,
  3917. // or the members of an enumeration.
  3918. // C++ [dcl.dcl]p3:
  3919. // [If there are no declarators], and except for the declaration of an
  3920. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  3921. // names into the program, or shall redeclare a name introduced by a
  3922. // previous declaration.
  3923. if (!DeclaresAnything) {
  3924. // In C, we allow this as a (popular) extension / bug. Don't bother
  3925. // producing further diagnostics for redundant qualifiers after this.
  3926. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  3927. return TagD;
  3928. }
  3929. // C++ [dcl.stc]p1:
  3930. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  3931. // init-declarator-list of the declaration shall not be empty.
  3932. // C++ [dcl.fct.spec]p1:
  3933. // If a cv-qualifier appears in a decl-specifier-seq, the
  3934. // init-declarator-list of the declaration shall not be empty.
  3935. //
  3936. // Spurious qualifiers here appear to be valid in C.
  3937. unsigned DiagID = diag::warn_standalone_specifier;
  3938. if (getLangOpts().CPlusPlus)
  3939. DiagID = diag::ext_standalone_specifier;
  3940. // Note that a linkage-specification sets a storage class, but
  3941. // 'extern "C" struct foo;' is actually valid and not theoretically
  3942. // useless.
  3943. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3944. if (SCS == DeclSpec::SCS_mutable)
  3945. // Since mutable is not a viable storage class specifier in C, there is
  3946. // no reason to treat it as an extension. Instead, diagnose as an error.
  3947. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  3948. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  3949. Diag(DS.getStorageClassSpecLoc(), DiagID)
  3950. << DeclSpec::getSpecifierName(SCS);
  3951. }
  3952. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  3953. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  3954. << DeclSpec::getSpecifierName(TSCS);
  3955. if (DS.getTypeQualifiers()) {
  3956. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3957. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  3958. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3959. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  3960. // Restrict is covered above.
  3961. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3962. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  3963. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  3964. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  3965. }
  3966. // Warn about ignored type attributes, for example:
  3967. // __attribute__((aligned)) struct A;
  3968. // Attributes should be placed after tag to apply to type declaration.
  3969. if (!DS.getAttributes().empty()) {
  3970. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  3971. if (TypeSpecType == DeclSpec::TST_class ||
  3972. TypeSpecType == DeclSpec::TST_struct ||
  3973. TypeSpecType == DeclSpec::TST_interface ||
  3974. TypeSpecType == DeclSpec::TST_union ||
  3975. TypeSpecType == DeclSpec::TST_enum) {
  3976. for (const ParsedAttr &AL : DS.getAttributes())
  3977. Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
  3978. << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  3979. }
  3980. }
  3981. return TagD;
  3982. }
  3983. /// We are trying to inject an anonymous member into the given scope;
  3984. /// check if there's an existing declaration that can't be overloaded.
  3985. ///
  3986. /// \return true if this is a forbidden redeclaration
  3987. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  3988. Scope *S,
  3989. DeclContext *Owner,
  3990. DeclarationName Name,
  3991. SourceLocation NameLoc,
  3992. bool IsUnion) {
  3993. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  3994. Sema::ForVisibleRedeclaration);
  3995. if (!SemaRef.LookupName(R, S)) return false;
  3996. // Pick a representative declaration.
  3997. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  3998. assert(PrevDecl && "Expected a non-null Decl");
  3999. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  4000. return false;
  4001. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  4002. << IsUnion << Name;
  4003. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  4004. return true;
  4005. }
  4006. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  4007. /// anonymous struct or union AnonRecord into the owning context Owner
  4008. /// and scope S. This routine will be invoked just after we realize
  4009. /// that an unnamed union or struct is actually an anonymous union or
  4010. /// struct, e.g.,
  4011. ///
  4012. /// @code
  4013. /// union {
  4014. /// int i;
  4015. /// float f;
  4016. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  4017. /// // f into the surrounding scope.x
  4018. /// @endcode
  4019. ///
  4020. /// This routine is recursive, injecting the names of nested anonymous
  4021. /// structs/unions into the owning context and scope as well.
  4022. static bool
  4023. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  4024. RecordDecl *AnonRecord, AccessSpecifier AS,
  4025. SmallVectorImpl<NamedDecl *> &Chaining) {
  4026. bool Invalid = false;
  4027. // Look every FieldDecl and IndirectFieldDecl with a name.
  4028. for (auto *D : AnonRecord->decls()) {
  4029. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  4030. cast<NamedDecl>(D)->getDeclName()) {
  4031. ValueDecl *VD = cast<ValueDecl>(D);
  4032. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  4033. VD->getLocation(),
  4034. AnonRecord->isUnion())) {
  4035. // C++ [class.union]p2:
  4036. // The names of the members of an anonymous union shall be
  4037. // distinct from the names of any other entity in the
  4038. // scope in which the anonymous union is declared.
  4039. Invalid = true;
  4040. } else {
  4041. // C++ [class.union]p2:
  4042. // For the purpose of name lookup, after the anonymous union
  4043. // definition, the members of the anonymous union are
  4044. // considered to have been defined in the scope in which the
  4045. // anonymous union is declared.
  4046. unsigned OldChainingSize = Chaining.size();
  4047. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  4048. Chaining.append(IF->chain_begin(), IF->chain_end());
  4049. else
  4050. Chaining.push_back(VD);
  4051. assert(Chaining.size() >= 2);
  4052. NamedDecl **NamedChain =
  4053. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  4054. for (unsigned i = 0; i < Chaining.size(); i++)
  4055. NamedChain[i] = Chaining[i];
  4056. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  4057. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  4058. VD->getType(), {NamedChain, Chaining.size()});
  4059. for (const auto *Attr : VD->attrs())
  4060. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  4061. IndirectField->setAccess(AS);
  4062. IndirectField->setImplicit();
  4063. SemaRef.PushOnScopeChains(IndirectField, S);
  4064. // That includes picking up the appropriate access specifier.
  4065. if (AS != AS_none) IndirectField->setAccess(AS);
  4066. Chaining.resize(OldChainingSize);
  4067. }
  4068. }
  4069. }
  4070. return Invalid;
  4071. }
  4072. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  4073. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  4074. /// illegal input values are mapped to SC_None.
  4075. static StorageClass
  4076. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  4077. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  4078. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  4079. "Parser allowed 'typedef' as storage class VarDecl.");
  4080. switch (StorageClassSpec) {
  4081. case DeclSpec::SCS_unspecified: return SC_None;
  4082. case DeclSpec::SCS_extern:
  4083. if (DS.isExternInLinkageSpec())
  4084. return SC_None;
  4085. return SC_Extern;
  4086. case DeclSpec::SCS_static: return SC_Static;
  4087. case DeclSpec::SCS_auto: return SC_Auto;
  4088. case DeclSpec::SCS_register: return SC_Register;
  4089. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4090. // Illegal SCSs map to None: error reporting is up to the caller.
  4091. case DeclSpec::SCS_mutable: // Fall through.
  4092. case DeclSpec::SCS_typedef: return SC_None;
  4093. }
  4094. llvm_unreachable("unknown storage class specifier");
  4095. }
  4096. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  4097. assert(Record->hasInClassInitializer());
  4098. for (const auto *I : Record->decls()) {
  4099. const auto *FD = dyn_cast<FieldDecl>(I);
  4100. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  4101. FD = IFD->getAnonField();
  4102. if (FD && FD->hasInClassInitializer())
  4103. return FD->getLocation();
  4104. }
  4105. llvm_unreachable("couldn't find in-class initializer");
  4106. }
  4107. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4108. SourceLocation DefaultInitLoc) {
  4109. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4110. return;
  4111. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  4112. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  4113. }
  4114. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4115. CXXRecordDecl *AnonUnion) {
  4116. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4117. return;
  4118. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  4119. }
  4120. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  4121. /// anonymous structure or union. Anonymous unions are a C++ feature
  4122. /// (C++ [class.union]) and a C11 feature; anonymous structures
  4123. /// are a C11 feature and GNU C++ extension.
  4124. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  4125. AccessSpecifier AS,
  4126. RecordDecl *Record,
  4127. const PrintingPolicy &Policy) {
  4128. DeclContext *Owner = Record->getDeclContext();
  4129. // Diagnose whether this anonymous struct/union is an extension.
  4130. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  4131. Diag(Record->getLocation(), diag::ext_anonymous_union);
  4132. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  4133. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  4134. else if (!Record->isUnion() && !getLangOpts().C11)
  4135. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  4136. // C and C++ require different kinds of checks for anonymous
  4137. // structs/unions.
  4138. bool Invalid = false;
  4139. if (getLangOpts().CPlusPlus) {
  4140. const char *PrevSpec = nullptr;
  4141. unsigned DiagID;
  4142. if (Record->isUnion()) {
  4143. // C++ [class.union]p6:
  4144. // C++17 [class.union.anon]p2:
  4145. // Anonymous unions declared in a named namespace or in the
  4146. // global namespace shall be declared static.
  4147. DeclContext *OwnerScope = Owner->getRedeclContext();
  4148. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  4149. (OwnerScope->isTranslationUnit() ||
  4150. (OwnerScope->isNamespace() &&
  4151. !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
  4152. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  4153. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  4154. // Recover by adding 'static'.
  4155. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  4156. PrevSpec, DiagID, Policy);
  4157. }
  4158. // C++ [class.union]p6:
  4159. // A storage class is not allowed in a declaration of an
  4160. // anonymous union in a class scope.
  4161. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  4162. isa<RecordDecl>(Owner)) {
  4163. Diag(DS.getStorageClassSpecLoc(),
  4164. diag::err_anonymous_union_with_storage_spec)
  4165. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  4166. // Recover by removing the storage specifier.
  4167. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  4168. SourceLocation(),
  4169. PrevSpec, DiagID, Context.getPrintingPolicy());
  4170. }
  4171. }
  4172. // Ignore const/volatile/restrict qualifiers.
  4173. if (DS.getTypeQualifiers()) {
  4174. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4175. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  4176. << Record->isUnion() << "const"
  4177. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  4178. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4179. Diag(DS.getVolatileSpecLoc(),
  4180. diag::ext_anonymous_struct_union_qualified)
  4181. << Record->isUnion() << "volatile"
  4182. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  4183. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  4184. Diag(DS.getRestrictSpecLoc(),
  4185. diag::ext_anonymous_struct_union_qualified)
  4186. << Record->isUnion() << "restrict"
  4187. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  4188. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4189. Diag(DS.getAtomicSpecLoc(),
  4190. diag::ext_anonymous_struct_union_qualified)
  4191. << Record->isUnion() << "_Atomic"
  4192. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  4193. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4194. Diag(DS.getUnalignedSpecLoc(),
  4195. diag::ext_anonymous_struct_union_qualified)
  4196. << Record->isUnion() << "__unaligned"
  4197. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  4198. DS.ClearTypeQualifiers();
  4199. }
  4200. // C++ [class.union]p2:
  4201. // The member-specification of an anonymous union shall only
  4202. // define non-static data members. [Note: nested types and
  4203. // functions cannot be declared within an anonymous union. ]
  4204. for (auto *Mem : Record->decls()) {
  4205. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  4206. // C++ [class.union]p3:
  4207. // An anonymous union shall not have private or protected
  4208. // members (clause 11).
  4209. assert(FD->getAccess() != AS_none);
  4210. if (FD->getAccess() != AS_public) {
  4211. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  4212. << Record->isUnion() << (FD->getAccess() == AS_protected);
  4213. Invalid = true;
  4214. }
  4215. // C++ [class.union]p1
  4216. // An object of a class with a non-trivial constructor, a non-trivial
  4217. // copy constructor, a non-trivial destructor, or a non-trivial copy
  4218. // assignment operator cannot be a member of a union, nor can an
  4219. // array of such objects.
  4220. if (CheckNontrivialField(FD))
  4221. Invalid = true;
  4222. } else if (Mem->isImplicit()) {
  4223. // Any implicit members are fine.
  4224. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  4225. // This is a type that showed up in an
  4226. // elaborated-type-specifier inside the anonymous struct or
  4227. // union, but which actually declares a type outside of the
  4228. // anonymous struct or union. It's okay.
  4229. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  4230. if (!MemRecord->isAnonymousStructOrUnion() &&
  4231. MemRecord->getDeclName()) {
  4232. // Visual C++ allows type definition in anonymous struct or union.
  4233. if (getLangOpts().MicrosoftExt)
  4234. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  4235. << Record->isUnion();
  4236. else {
  4237. // This is a nested type declaration.
  4238. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  4239. << Record->isUnion();
  4240. Invalid = true;
  4241. }
  4242. } else {
  4243. // This is an anonymous type definition within another anonymous type.
  4244. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  4245. // not part of standard C++.
  4246. Diag(MemRecord->getLocation(),
  4247. diag::ext_anonymous_record_with_anonymous_type)
  4248. << Record->isUnion();
  4249. }
  4250. } else if (isa<AccessSpecDecl>(Mem)) {
  4251. // Any access specifier is fine.
  4252. } else if (isa<StaticAssertDecl>(Mem)) {
  4253. // In C++1z, static_assert declarations are also fine.
  4254. } else {
  4255. // We have something that isn't a non-static data
  4256. // member. Complain about it.
  4257. unsigned DK = diag::err_anonymous_record_bad_member;
  4258. if (isa<TypeDecl>(Mem))
  4259. DK = diag::err_anonymous_record_with_type;
  4260. else if (isa<FunctionDecl>(Mem))
  4261. DK = diag::err_anonymous_record_with_function;
  4262. else if (isa<VarDecl>(Mem))
  4263. DK = diag::err_anonymous_record_with_static;
  4264. // Visual C++ allows type definition in anonymous struct or union.
  4265. if (getLangOpts().MicrosoftExt &&
  4266. DK == diag::err_anonymous_record_with_type)
  4267. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  4268. << Record->isUnion();
  4269. else {
  4270. Diag(Mem->getLocation(), DK) << Record->isUnion();
  4271. Invalid = true;
  4272. }
  4273. }
  4274. }
  4275. // C++11 [class.union]p8 (DR1460):
  4276. // At most one variant member of a union may have a
  4277. // brace-or-equal-initializer.
  4278. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  4279. Owner->isRecord())
  4280. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  4281. cast<CXXRecordDecl>(Record));
  4282. }
  4283. if (!Record->isUnion() && !Owner->isRecord()) {
  4284. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  4285. << getLangOpts().CPlusPlus;
  4286. Invalid = true;
  4287. }
  4288. // C++ [dcl.dcl]p3:
  4289. // [If there are no declarators], and except for the declaration of an
  4290. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  4291. // names into the program
  4292. // C++ [class.mem]p2:
  4293. // each such member-declaration shall either declare at least one member
  4294. // name of the class or declare at least one unnamed bit-field
  4295. //
  4296. // For C this is an error even for a named struct, and is diagnosed elsewhere.
  4297. if (getLangOpts().CPlusPlus && Record->field_empty())
  4298. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  4299. // Mock up a declarator.
  4300. Declarator Dc(DS, DeclaratorContext::MemberContext);
  4301. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4302. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  4303. // Create a declaration for this anonymous struct/union.
  4304. NamedDecl *Anon = nullptr;
  4305. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  4306. Anon = FieldDecl::Create(
  4307. Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
  4308. /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
  4309. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4310. /*InitStyle=*/ICIS_NoInit);
  4311. Anon->setAccess(AS);
  4312. if (getLangOpts().CPlusPlus)
  4313. FieldCollector->Add(cast<FieldDecl>(Anon));
  4314. } else {
  4315. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  4316. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  4317. if (SCSpec == DeclSpec::SCS_mutable) {
  4318. // mutable can only appear on non-static class members, so it's always
  4319. // an error here
  4320. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  4321. Invalid = true;
  4322. SC = SC_None;
  4323. }
  4324. Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
  4325. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  4326. Context.getTypeDeclType(Record), TInfo, SC);
  4327. // Default-initialize the implicit variable. This initialization will be
  4328. // trivial in almost all cases, except if a union member has an in-class
  4329. // initializer:
  4330. // union { int n = 0; };
  4331. ActOnUninitializedDecl(Anon);
  4332. }
  4333. Anon->setImplicit();
  4334. // Mark this as an anonymous struct/union type.
  4335. Record->setAnonymousStructOrUnion(true);
  4336. // Add the anonymous struct/union object to the current
  4337. // context. We'll be referencing this object when we refer to one of
  4338. // its members.
  4339. Owner->addDecl(Anon);
  4340. // Inject the members of the anonymous struct/union into the owning
  4341. // context and into the identifier resolver chain for name lookup
  4342. // purposes.
  4343. SmallVector<NamedDecl*, 2> Chain;
  4344. Chain.push_back(Anon);
  4345. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4346. Invalid = true;
  4347. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4348. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4349. Decl *ManglingContextDecl;
  4350. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  4351. NewVD->getDeclContext(), ManglingContextDecl)) {
  4352. Context.setManglingNumber(
  4353. NewVD, MCtx->getManglingNumber(
  4354. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4355. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4356. }
  4357. }
  4358. }
  4359. if (Invalid)
  4360. Anon->setInvalidDecl();
  4361. return Anon;
  4362. }
  4363. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4364. /// Microsoft C anonymous structure.
  4365. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4366. /// Example:
  4367. ///
  4368. /// struct A { int a; };
  4369. /// struct B { struct A; int b; };
  4370. ///
  4371. /// void foo() {
  4372. /// B var;
  4373. /// var.a = 3;
  4374. /// }
  4375. ///
  4376. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4377. RecordDecl *Record) {
  4378. assert(Record && "expected a record!");
  4379. // Mock up a declarator.
  4380. Declarator Dc(DS, DeclaratorContext::TypeNameContext);
  4381. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4382. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4383. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4384. QualType RecTy = Context.getTypeDeclType(Record);
  4385. // Create a declaration for this anonymous struct.
  4386. NamedDecl *Anon =
  4387. FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
  4388. /*IdentifierInfo=*/nullptr, RecTy, TInfo,
  4389. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4390. /*InitStyle=*/ICIS_NoInit);
  4391. Anon->setImplicit();
  4392. // Add the anonymous struct object to the current context.
  4393. CurContext->addDecl(Anon);
  4394. // Inject the members of the anonymous struct into the current
  4395. // context and into the identifier resolver chain for name lookup
  4396. // purposes.
  4397. SmallVector<NamedDecl*, 2> Chain;
  4398. Chain.push_back(Anon);
  4399. RecordDecl *RecordDef = Record->getDefinition();
  4400. if (RequireCompleteType(Anon->getLocation(), RecTy,
  4401. diag::err_field_incomplete) ||
  4402. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4403. AS_none, Chain)) {
  4404. Anon->setInvalidDecl();
  4405. ParentDecl->setInvalidDecl();
  4406. }
  4407. return Anon;
  4408. }
  4409. /// GetNameForDeclarator - Determine the full declaration name for the
  4410. /// given Declarator.
  4411. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4412. return GetNameFromUnqualifiedId(D.getName());
  4413. }
  4414. /// Retrieves the declaration name from a parsed unqualified-id.
  4415. DeclarationNameInfo
  4416. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4417. DeclarationNameInfo NameInfo;
  4418. NameInfo.setLoc(Name.StartLocation);
  4419. switch (Name.getKind()) {
  4420. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  4421. case UnqualifiedIdKind::IK_Identifier:
  4422. NameInfo.setName(Name.Identifier);
  4423. return NameInfo;
  4424. case UnqualifiedIdKind::IK_DeductionGuideName: {
  4425. // C++ [temp.deduct.guide]p3:
  4426. // The simple-template-id shall name a class template specialization.
  4427. // The template-name shall be the same identifier as the template-name
  4428. // of the simple-template-id.
  4429. // These together intend to imply that the template-name shall name a
  4430. // class template.
  4431. // FIXME: template<typename T> struct X {};
  4432. // template<typename T> using Y = X<T>;
  4433. // Y(int) -> Y<int>;
  4434. // satisfies these rules but does not name a class template.
  4435. TemplateName TN = Name.TemplateName.get().get();
  4436. auto *Template = TN.getAsTemplateDecl();
  4437. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  4438. Diag(Name.StartLocation,
  4439. diag::err_deduction_guide_name_not_class_template)
  4440. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  4441. if (Template)
  4442. Diag(Template->getLocation(), diag::note_template_decl_here);
  4443. return DeclarationNameInfo();
  4444. }
  4445. NameInfo.setName(
  4446. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  4447. return NameInfo;
  4448. }
  4449. case UnqualifiedIdKind::IK_OperatorFunctionId:
  4450. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4451. Name.OperatorFunctionId.Operator));
  4452. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  4453. = Name.OperatorFunctionId.SymbolLocations[0];
  4454. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  4455. = Name.EndLocation.getRawEncoding();
  4456. return NameInfo;
  4457. case UnqualifiedIdKind::IK_LiteralOperatorId:
  4458. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4459. Name.Identifier));
  4460. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4461. return NameInfo;
  4462. case UnqualifiedIdKind::IK_ConversionFunctionId: {
  4463. TypeSourceInfo *TInfo;
  4464. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4465. if (Ty.isNull())
  4466. return DeclarationNameInfo();
  4467. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4468. Context.getCanonicalType(Ty)));
  4469. NameInfo.setNamedTypeInfo(TInfo);
  4470. return NameInfo;
  4471. }
  4472. case UnqualifiedIdKind::IK_ConstructorName: {
  4473. TypeSourceInfo *TInfo;
  4474. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4475. if (Ty.isNull())
  4476. return DeclarationNameInfo();
  4477. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4478. Context.getCanonicalType(Ty)));
  4479. NameInfo.setNamedTypeInfo(TInfo);
  4480. return NameInfo;
  4481. }
  4482. case UnqualifiedIdKind::IK_ConstructorTemplateId: {
  4483. // In well-formed code, we can only have a constructor
  4484. // template-id that refers to the current context, so go there
  4485. // to find the actual type being constructed.
  4486. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4487. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4488. return DeclarationNameInfo();
  4489. // Determine the type of the class being constructed.
  4490. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4491. // FIXME: Check two things: that the template-id names the same type as
  4492. // CurClassType, and that the template-id does not occur when the name
  4493. // was qualified.
  4494. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4495. Context.getCanonicalType(CurClassType)));
  4496. // FIXME: should we retrieve TypeSourceInfo?
  4497. NameInfo.setNamedTypeInfo(nullptr);
  4498. return NameInfo;
  4499. }
  4500. case UnqualifiedIdKind::IK_DestructorName: {
  4501. TypeSourceInfo *TInfo;
  4502. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4503. if (Ty.isNull())
  4504. return DeclarationNameInfo();
  4505. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4506. Context.getCanonicalType(Ty)));
  4507. NameInfo.setNamedTypeInfo(TInfo);
  4508. return NameInfo;
  4509. }
  4510. case UnqualifiedIdKind::IK_TemplateId: {
  4511. TemplateName TName = Name.TemplateId->Template.get();
  4512. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4513. return Context.getNameForTemplate(TName, TNameLoc);
  4514. }
  4515. } // switch (Name.getKind())
  4516. llvm_unreachable("Unknown name kind");
  4517. }
  4518. static QualType getCoreType(QualType Ty) {
  4519. do {
  4520. if (Ty->isPointerType() || Ty->isReferenceType())
  4521. Ty = Ty->getPointeeType();
  4522. else if (Ty->isArrayType())
  4523. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4524. else
  4525. return Ty.withoutLocalFastQualifiers();
  4526. } while (true);
  4527. }
  4528. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4529. /// and Definition have "nearly" matching parameters. This heuristic is
  4530. /// used to improve diagnostics in the case where an out-of-line function
  4531. /// definition doesn't match any declaration within the class or namespace.
  4532. /// Also sets Params to the list of indices to the parameters that differ
  4533. /// between the declaration and the definition. If hasSimilarParameters
  4534. /// returns true and Params is empty, then all of the parameters match.
  4535. static bool hasSimilarParameters(ASTContext &Context,
  4536. FunctionDecl *Declaration,
  4537. FunctionDecl *Definition,
  4538. SmallVectorImpl<unsigned> &Params) {
  4539. Params.clear();
  4540. if (Declaration->param_size() != Definition->param_size())
  4541. return false;
  4542. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4543. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4544. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4545. // The parameter types are identical
  4546. if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
  4547. continue;
  4548. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4549. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4550. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4551. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4552. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4553. (DeclTyName && DeclTyName == DefTyName))
  4554. Params.push_back(Idx);
  4555. else // The two parameters aren't even close
  4556. return false;
  4557. }
  4558. return true;
  4559. }
  4560. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4561. /// declarator needs to be rebuilt in the current instantiation.
  4562. /// Any bits of declarator which appear before the name are valid for
  4563. /// consideration here. That's specifically the type in the decl spec
  4564. /// and the base type in any member-pointer chunks.
  4565. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4566. DeclarationName Name) {
  4567. // The types we specifically need to rebuild are:
  4568. // - typenames, typeofs, and decltypes
  4569. // - types which will become injected class names
  4570. // Of course, we also need to rebuild any type referencing such a
  4571. // type. It's safest to just say "dependent", but we call out a
  4572. // few cases here.
  4573. DeclSpec &DS = D.getMutableDeclSpec();
  4574. switch (DS.getTypeSpecType()) {
  4575. case DeclSpec::TST_typename:
  4576. case DeclSpec::TST_typeofType:
  4577. case DeclSpec::TST_underlyingType:
  4578. case DeclSpec::TST_atomic: {
  4579. // Grab the type from the parser.
  4580. TypeSourceInfo *TSI = nullptr;
  4581. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4582. if (T.isNull() || !T->isDependentType()) break;
  4583. // Make sure there's a type source info. This isn't really much
  4584. // of a waste; most dependent types should have type source info
  4585. // attached already.
  4586. if (!TSI)
  4587. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4588. // Rebuild the type in the current instantiation.
  4589. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4590. if (!TSI) return true;
  4591. // Store the new type back in the decl spec.
  4592. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4593. DS.UpdateTypeRep(LocType);
  4594. break;
  4595. }
  4596. case DeclSpec::TST_decltype:
  4597. case DeclSpec::TST_typeofExpr: {
  4598. Expr *E = DS.getRepAsExpr();
  4599. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4600. if (Result.isInvalid()) return true;
  4601. DS.UpdateExprRep(Result.get());
  4602. break;
  4603. }
  4604. default:
  4605. // Nothing to do for these decl specs.
  4606. break;
  4607. }
  4608. // It doesn't matter what order we do this in.
  4609. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4610. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4611. // The only type information in the declarator which can come
  4612. // before the declaration name is the base type of a member
  4613. // pointer.
  4614. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4615. continue;
  4616. // Rebuild the scope specifier in-place.
  4617. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4618. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4619. return true;
  4620. }
  4621. return false;
  4622. }
  4623. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4624. D.setFunctionDefinitionKind(FDK_Declaration);
  4625. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4626. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4627. Dcl && Dcl->getDeclContext()->isFileContext())
  4628. Dcl->setTopLevelDeclInObjCContainer();
  4629. if (getLangOpts().OpenCL)
  4630. setCurrentOpenCLExtensionForDecl(Dcl);
  4631. return Dcl;
  4632. }
  4633. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4634. /// If T is the name of a class, then each of the following shall have a
  4635. /// name different from T:
  4636. /// - every static data member of class T;
  4637. /// - every member function of class T
  4638. /// - every member of class T that is itself a type;
  4639. /// \returns true if the declaration name violates these rules.
  4640. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4641. DeclarationNameInfo NameInfo) {
  4642. DeclarationName Name = NameInfo.getName();
  4643. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  4644. while (Record && Record->isAnonymousStructOrUnion())
  4645. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  4646. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  4647. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4648. return true;
  4649. }
  4650. return false;
  4651. }
  4652. /// Diagnose a declaration whose declarator-id has the given
  4653. /// nested-name-specifier.
  4654. ///
  4655. /// \param SS The nested-name-specifier of the declarator-id.
  4656. ///
  4657. /// \param DC The declaration context to which the nested-name-specifier
  4658. /// resolves.
  4659. ///
  4660. /// \param Name The name of the entity being declared.
  4661. ///
  4662. /// \param Loc The location of the name of the entity being declared.
  4663. ///
  4664. /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
  4665. /// we're declaring an explicit / partial specialization / instantiation.
  4666. ///
  4667. /// \returns true if we cannot safely recover from this error, false otherwise.
  4668. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4669. DeclarationName Name,
  4670. SourceLocation Loc, bool IsTemplateId) {
  4671. DeclContext *Cur = CurContext;
  4672. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4673. Cur = Cur->getParent();
  4674. // If the user provided a superfluous scope specifier that refers back to the
  4675. // class in which the entity is already declared, diagnose and ignore it.
  4676. //
  4677. // class X {
  4678. // void X::f();
  4679. // };
  4680. //
  4681. // Note, it was once ill-formed to give redundant qualification in all
  4682. // contexts, but that rule was removed by DR482.
  4683. if (Cur->Equals(DC)) {
  4684. if (Cur->isRecord()) {
  4685. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4686. : diag::err_member_extra_qualification)
  4687. << Name << FixItHint::CreateRemoval(SS.getRange());
  4688. SS.clear();
  4689. } else {
  4690. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4691. }
  4692. return false;
  4693. }
  4694. // Check whether the qualifying scope encloses the scope of the original
  4695. // declaration. For a template-id, we perform the checks in
  4696. // CheckTemplateSpecializationScope.
  4697. if (!Cur->Encloses(DC) && !IsTemplateId) {
  4698. if (Cur->isRecord())
  4699. Diag(Loc, diag::err_member_qualification)
  4700. << Name << SS.getRange();
  4701. else if (isa<TranslationUnitDecl>(DC))
  4702. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4703. << Name << SS.getRange();
  4704. else if (isa<FunctionDecl>(Cur))
  4705. Diag(Loc, diag::err_invalid_declarator_in_function)
  4706. << Name << SS.getRange();
  4707. else if (isa<BlockDecl>(Cur))
  4708. Diag(Loc, diag::err_invalid_declarator_in_block)
  4709. << Name << SS.getRange();
  4710. else
  4711. Diag(Loc, diag::err_invalid_declarator_scope)
  4712. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4713. return true;
  4714. }
  4715. if (Cur->isRecord()) {
  4716. // Cannot qualify members within a class.
  4717. Diag(Loc, diag::err_member_qualification)
  4718. << Name << SS.getRange();
  4719. SS.clear();
  4720. // C++ constructors and destructors with incorrect scopes can break
  4721. // our AST invariants by having the wrong underlying types. If
  4722. // that's the case, then drop this declaration entirely.
  4723. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4724. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4725. !Context.hasSameType(Name.getCXXNameType(),
  4726. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4727. return true;
  4728. return false;
  4729. }
  4730. // C++11 [dcl.meaning]p1:
  4731. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4732. // not begin with a decltype-specifer"
  4733. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4734. while (SpecLoc.getPrefix())
  4735. SpecLoc = SpecLoc.getPrefix();
  4736. if (dyn_cast_or_null<DecltypeType>(
  4737. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4738. Diag(Loc, diag::err_decltype_in_declarator)
  4739. << SpecLoc.getTypeLoc().getSourceRange();
  4740. return false;
  4741. }
  4742. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4743. MultiTemplateParamsArg TemplateParamLists) {
  4744. // TODO: consider using NameInfo for diagnostic.
  4745. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4746. DeclarationName Name = NameInfo.getName();
  4747. // All of these full declarators require an identifier. If it doesn't have
  4748. // one, the ParsedFreeStandingDeclSpec action should be used.
  4749. if (D.isDecompositionDeclarator()) {
  4750. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  4751. } else if (!Name) {
  4752. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4753. Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
  4754. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4755. return nullptr;
  4756. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4757. return nullptr;
  4758. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4759. // we find one that is.
  4760. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4761. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4762. S = S->getParent();
  4763. DeclContext *DC = CurContext;
  4764. if (D.getCXXScopeSpec().isInvalid())
  4765. D.setInvalidType();
  4766. else if (D.getCXXScopeSpec().isSet()) {
  4767. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4768. UPPC_DeclarationQualifier))
  4769. return nullptr;
  4770. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4771. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4772. if (!DC || isa<EnumDecl>(DC)) {
  4773. // If we could not compute the declaration context, it's because the
  4774. // declaration context is dependent but does not refer to a class,
  4775. // class template, or class template partial specialization. Complain
  4776. // and return early, to avoid the coming semantic disaster.
  4777. Diag(D.getIdentifierLoc(),
  4778. diag::err_template_qualified_declarator_no_match)
  4779. << D.getCXXScopeSpec().getScopeRep()
  4780. << D.getCXXScopeSpec().getRange();
  4781. return nullptr;
  4782. }
  4783. bool IsDependentContext = DC->isDependentContext();
  4784. if (!IsDependentContext &&
  4785. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4786. return nullptr;
  4787. // If a class is incomplete, do not parse entities inside it.
  4788. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4789. Diag(D.getIdentifierLoc(),
  4790. diag::err_member_def_undefined_record)
  4791. << Name << DC << D.getCXXScopeSpec().getRange();
  4792. return nullptr;
  4793. }
  4794. if (!D.getDeclSpec().isFriendSpecified()) {
  4795. if (diagnoseQualifiedDeclaration(
  4796. D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
  4797. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
  4798. if (DC->isRecord())
  4799. return nullptr;
  4800. D.setInvalidType();
  4801. }
  4802. }
  4803. // Check whether we need to rebuild the type of the given
  4804. // declaration in the current instantiation.
  4805. if (EnteringContext && IsDependentContext &&
  4806. TemplateParamLists.size() != 0) {
  4807. ContextRAII SavedContext(*this, DC);
  4808. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4809. D.setInvalidType();
  4810. }
  4811. }
  4812. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4813. QualType R = TInfo->getType();
  4814. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4815. UPPC_DeclarationType))
  4816. D.setInvalidType();
  4817. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4818. forRedeclarationInCurContext());
  4819. // See if this is a redefinition of a variable in the same scope.
  4820. if (!D.getCXXScopeSpec().isSet()) {
  4821. bool IsLinkageLookup = false;
  4822. bool CreateBuiltins = false;
  4823. // If the declaration we're planning to build will be a function
  4824. // or object with linkage, then look for another declaration with
  4825. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4826. //
  4827. // If the declaration we're planning to build will be declared with
  4828. // external linkage in the translation unit, create any builtin with
  4829. // the same name.
  4830. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4831. /* Do nothing*/;
  4832. else if (CurContext->isFunctionOrMethod() &&
  4833. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4834. R->isFunctionType())) {
  4835. IsLinkageLookup = true;
  4836. CreateBuiltins =
  4837. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4838. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4839. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4840. CreateBuiltins = true;
  4841. if (IsLinkageLookup) {
  4842. Previous.clear(LookupRedeclarationWithLinkage);
  4843. Previous.setRedeclarationKind(ForExternalRedeclaration);
  4844. }
  4845. LookupName(Previous, S, CreateBuiltins);
  4846. } else { // Something like "int foo::x;"
  4847. LookupQualifiedName(Previous, DC);
  4848. // C++ [dcl.meaning]p1:
  4849. // When the declarator-id is qualified, the declaration shall refer to a
  4850. // previously declared member of the class or namespace to which the
  4851. // qualifier refers (or, in the case of a namespace, of an element of the
  4852. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4853. // thereof; [...]
  4854. //
  4855. // Note that we already checked the context above, and that we do not have
  4856. // enough information to make sure that Previous contains the declaration
  4857. // we want to match. For example, given:
  4858. //
  4859. // class X {
  4860. // void f();
  4861. // void f(float);
  4862. // };
  4863. //
  4864. // void X::f(int) { } // ill-formed
  4865. //
  4866. // In this case, Previous will point to the overload set
  4867. // containing the two f's declared in X, but neither of them
  4868. // matches.
  4869. // C++ [dcl.meaning]p1:
  4870. // [...] the member shall not merely have been introduced by a
  4871. // using-declaration in the scope of the class or namespace nominated by
  4872. // the nested-name-specifier of the declarator-id.
  4873. RemoveUsingDecls(Previous);
  4874. }
  4875. if (Previous.isSingleResult() &&
  4876. Previous.getFoundDecl()->isTemplateParameter()) {
  4877. // Maybe we will complain about the shadowed template parameter.
  4878. if (!D.isInvalidType())
  4879. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4880. Previous.getFoundDecl());
  4881. // Just pretend that we didn't see the previous declaration.
  4882. Previous.clear();
  4883. }
  4884. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4885. // Forget that the previous declaration is the injected-class-name.
  4886. Previous.clear();
  4887. // In C++, the previous declaration we find might be a tag type
  4888. // (class or enum). In this case, the new declaration will hide the
  4889. // tag type. Note that this applies to functions, function templates, and
  4890. // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
  4891. if (Previous.isSingleTagDecl() &&
  4892. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  4893. (TemplateParamLists.size() == 0 || R->isFunctionType()))
  4894. Previous.clear();
  4895. // Check that there are no default arguments other than in the parameters
  4896. // of a function declaration (C++ only).
  4897. if (getLangOpts().CPlusPlus)
  4898. CheckExtraCXXDefaultArguments(D);
  4899. NamedDecl *New;
  4900. bool AddToScope = true;
  4901. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  4902. if (TemplateParamLists.size()) {
  4903. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  4904. return nullptr;
  4905. }
  4906. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  4907. } else if (R->isFunctionType()) {
  4908. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  4909. TemplateParamLists,
  4910. AddToScope);
  4911. } else {
  4912. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  4913. AddToScope);
  4914. }
  4915. if (!New)
  4916. return nullptr;
  4917. // If this has an identifier and is not a function template specialization,
  4918. // add it to the scope stack.
  4919. if (New->getDeclName() && AddToScope)
  4920. PushOnScopeChains(New, S);
  4921. if (isInOpenMPDeclareTargetContext())
  4922. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  4923. return New;
  4924. }
  4925. /// Helper method to turn variable array types into constant array
  4926. /// types in certain situations which would otherwise be errors (for
  4927. /// GCC compatibility).
  4928. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  4929. ASTContext &Context,
  4930. bool &SizeIsNegative,
  4931. llvm::APSInt &Oversized) {
  4932. // This method tries to turn a variable array into a constant
  4933. // array even when the size isn't an ICE. This is necessary
  4934. // for compatibility with code that depends on gcc's buggy
  4935. // constant expression folding, like struct {char x[(int)(char*)2];}
  4936. SizeIsNegative = false;
  4937. Oversized = 0;
  4938. if (T->isDependentType())
  4939. return QualType();
  4940. QualifierCollector Qs;
  4941. const Type *Ty = Qs.strip(T);
  4942. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  4943. QualType Pointee = PTy->getPointeeType();
  4944. QualType FixedType =
  4945. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  4946. Oversized);
  4947. if (FixedType.isNull()) return FixedType;
  4948. FixedType = Context.getPointerType(FixedType);
  4949. return Qs.apply(Context, FixedType);
  4950. }
  4951. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  4952. QualType Inner = PTy->getInnerType();
  4953. QualType FixedType =
  4954. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  4955. Oversized);
  4956. if (FixedType.isNull()) return FixedType;
  4957. FixedType = Context.getParenType(FixedType);
  4958. return Qs.apply(Context, FixedType);
  4959. }
  4960. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  4961. if (!VLATy)
  4962. return QualType();
  4963. // FIXME: We should probably handle this case
  4964. if (VLATy->getElementType()->isVariablyModifiedType())
  4965. return QualType();
  4966. Expr::EvalResult Result;
  4967. if (!VLATy->getSizeExpr() ||
  4968. !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
  4969. return QualType();
  4970. llvm::APSInt Res = Result.Val.getInt();
  4971. // Check whether the array size is negative.
  4972. if (Res.isSigned() && Res.isNegative()) {
  4973. SizeIsNegative = true;
  4974. return QualType();
  4975. }
  4976. // Check whether the array is too large to be addressed.
  4977. unsigned ActiveSizeBits
  4978. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  4979. Res);
  4980. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  4981. Oversized = Res;
  4982. return QualType();
  4983. }
  4984. return Context.getConstantArrayType(VLATy->getElementType(),
  4985. Res, ArrayType::Normal, 0);
  4986. }
  4987. static void
  4988. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  4989. SrcTL = SrcTL.getUnqualifiedLoc();
  4990. DstTL = DstTL.getUnqualifiedLoc();
  4991. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  4992. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  4993. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  4994. DstPTL.getPointeeLoc());
  4995. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  4996. return;
  4997. }
  4998. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  4999. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  5000. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  5001. DstPTL.getInnerLoc());
  5002. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  5003. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  5004. return;
  5005. }
  5006. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  5007. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  5008. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  5009. TypeLoc DstElemTL = DstATL.getElementLoc();
  5010. DstElemTL.initializeFullCopy(SrcElemTL);
  5011. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  5012. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  5013. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  5014. }
  5015. /// Helper method to turn variable array types into constant array
  5016. /// types in certain situations which would otherwise be errors (for
  5017. /// GCC compatibility).
  5018. static TypeSourceInfo*
  5019. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  5020. ASTContext &Context,
  5021. bool &SizeIsNegative,
  5022. llvm::APSInt &Oversized) {
  5023. QualType FixedTy
  5024. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  5025. SizeIsNegative, Oversized);
  5026. if (FixedTy.isNull())
  5027. return nullptr;
  5028. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  5029. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  5030. FixedTInfo->getTypeLoc());
  5031. return FixedTInfo;
  5032. }
  5033. /// Register the given locally-scoped extern "C" declaration so
  5034. /// that it can be found later for redeclarations. We include any extern "C"
  5035. /// declaration that is not visible in the translation unit here, not just
  5036. /// function-scope declarations.
  5037. void
  5038. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  5039. if (!getLangOpts().CPlusPlus &&
  5040. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  5041. // Don't need to track declarations in the TU in C.
  5042. return;
  5043. // Note that we have a locally-scoped external with this name.
  5044. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  5045. }
  5046. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  5047. // FIXME: We can have multiple results via __attribute__((overloadable)).
  5048. auto Result = Context.getExternCContextDecl()->lookup(Name);
  5049. return Result.empty() ? nullptr : *Result.begin();
  5050. }
  5051. /// Diagnose function specifiers on a declaration of an identifier that
  5052. /// does not identify a function.
  5053. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  5054. // FIXME: We should probably indicate the identifier in question to avoid
  5055. // confusion for constructs like "virtual int a(), b;"
  5056. if (DS.isVirtualSpecified())
  5057. Diag(DS.getVirtualSpecLoc(),
  5058. diag::err_virtual_non_function);
  5059. if (DS.hasExplicitSpecifier())
  5060. Diag(DS.getExplicitSpecLoc(),
  5061. diag::err_explicit_non_function);
  5062. if (DS.isNoreturnSpecified())
  5063. Diag(DS.getNoreturnSpecLoc(),
  5064. diag::err_noreturn_non_function);
  5065. }
  5066. NamedDecl*
  5067. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  5068. TypeSourceInfo *TInfo, LookupResult &Previous) {
  5069. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  5070. if (D.getCXXScopeSpec().isSet()) {
  5071. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  5072. << D.getCXXScopeSpec().getRange();
  5073. D.setInvalidType();
  5074. // Pretend we didn't see the scope specifier.
  5075. DC = CurContext;
  5076. Previous.clear();
  5077. }
  5078. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5079. if (D.getDeclSpec().isInlineSpecified())
  5080. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5081. << getLangOpts().CPlusPlus17;
  5082. if (D.getDeclSpec().isConstexprSpecified())
  5083. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5084. << 1;
  5085. if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
  5086. if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
  5087. Diag(D.getName().StartLocation,
  5088. diag::err_deduction_guide_invalid_specifier)
  5089. << "typedef";
  5090. else
  5091. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  5092. << D.getName().getSourceRange();
  5093. return nullptr;
  5094. }
  5095. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  5096. if (!NewTD) return nullptr;
  5097. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5098. ProcessDeclAttributes(S, NewTD, D);
  5099. CheckTypedefForVariablyModifiedType(S, NewTD);
  5100. bool Redeclaration = D.isRedeclaration();
  5101. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  5102. D.setRedeclaration(Redeclaration);
  5103. return ND;
  5104. }
  5105. void
  5106. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  5107. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  5108. // then it shall have block scope.
  5109. // Note that variably modified types must be fixed before merging the decl so
  5110. // that redeclarations will match.
  5111. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  5112. QualType T = TInfo->getType();
  5113. if (T->isVariablyModifiedType()) {
  5114. setFunctionHasBranchProtectedScope();
  5115. if (S->getFnParent() == nullptr) {
  5116. bool SizeIsNegative;
  5117. llvm::APSInt Oversized;
  5118. TypeSourceInfo *FixedTInfo =
  5119. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5120. SizeIsNegative,
  5121. Oversized);
  5122. if (FixedTInfo) {
  5123. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  5124. NewTD->setTypeSourceInfo(FixedTInfo);
  5125. } else {
  5126. if (SizeIsNegative)
  5127. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  5128. else if (T->isVariableArrayType())
  5129. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  5130. else if (Oversized.getBoolValue())
  5131. Diag(NewTD->getLocation(), diag::err_array_too_large)
  5132. << Oversized.toString(10);
  5133. else
  5134. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  5135. NewTD->setInvalidDecl();
  5136. }
  5137. }
  5138. }
  5139. }
  5140. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  5141. /// declares a typedef-name, either using the 'typedef' type specifier or via
  5142. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  5143. NamedDecl*
  5144. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  5145. LookupResult &Previous, bool &Redeclaration) {
  5146. // Find the shadowed declaration before filtering for scope.
  5147. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
  5148. // Merge the decl with the existing one if appropriate. If the decl is
  5149. // in an outer scope, it isn't the same thing.
  5150. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  5151. /*AllowInlineNamespace*/false);
  5152. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  5153. if (!Previous.empty()) {
  5154. Redeclaration = true;
  5155. MergeTypedefNameDecl(S, NewTD, Previous);
  5156. }
  5157. if (ShadowedDecl && !Redeclaration)
  5158. CheckShadow(NewTD, ShadowedDecl, Previous);
  5159. // If this is the C FILE type, notify the AST context.
  5160. if (IdentifierInfo *II = NewTD->getIdentifier())
  5161. if (!NewTD->isInvalidDecl() &&
  5162. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5163. if (II->isStr("FILE"))
  5164. Context.setFILEDecl(NewTD);
  5165. else if (II->isStr("jmp_buf"))
  5166. Context.setjmp_bufDecl(NewTD);
  5167. else if (II->isStr("sigjmp_buf"))
  5168. Context.setsigjmp_bufDecl(NewTD);
  5169. else if (II->isStr("ucontext_t"))
  5170. Context.setucontext_tDecl(NewTD);
  5171. }
  5172. return NewTD;
  5173. }
  5174. /// Determines whether the given declaration is an out-of-scope
  5175. /// previous declaration.
  5176. ///
  5177. /// This routine should be invoked when name lookup has found a
  5178. /// previous declaration (PrevDecl) that is not in the scope where a
  5179. /// new declaration by the same name is being introduced. If the new
  5180. /// declaration occurs in a local scope, previous declarations with
  5181. /// linkage may still be considered previous declarations (C99
  5182. /// 6.2.2p4-5, C++ [basic.link]p6).
  5183. ///
  5184. /// \param PrevDecl the previous declaration found by name
  5185. /// lookup
  5186. ///
  5187. /// \param DC the context in which the new declaration is being
  5188. /// declared.
  5189. ///
  5190. /// \returns true if PrevDecl is an out-of-scope previous declaration
  5191. /// for a new delcaration with the same name.
  5192. static bool
  5193. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  5194. ASTContext &Context) {
  5195. if (!PrevDecl)
  5196. return false;
  5197. if (!PrevDecl->hasLinkage())
  5198. return false;
  5199. if (Context.getLangOpts().CPlusPlus) {
  5200. // C++ [basic.link]p6:
  5201. // If there is a visible declaration of an entity with linkage
  5202. // having the same name and type, ignoring entities declared
  5203. // outside the innermost enclosing namespace scope, the block
  5204. // scope declaration declares that same entity and receives the
  5205. // linkage of the previous declaration.
  5206. DeclContext *OuterContext = DC->getRedeclContext();
  5207. if (!OuterContext->isFunctionOrMethod())
  5208. // This rule only applies to block-scope declarations.
  5209. return false;
  5210. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  5211. if (PrevOuterContext->isRecord())
  5212. // We found a member function: ignore it.
  5213. return false;
  5214. // Find the innermost enclosing namespace for the new and
  5215. // previous declarations.
  5216. OuterContext = OuterContext->getEnclosingNamespaceContext();
  5217. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  5218. // The previous declaration is in a different namespace, so it
  5219. // isn't the same function.
  5220. if (!OuterContext->Equals(PrevOuterContext))
  5221. return false;
  5222. }
  5223. return true;
  5224. }
  5225. static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
  5226. CXXScopeSpec &SS = D.getCXXScopeSpec();
  5227. if (!SS.isSet()) return;
  5228. DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
  5229. }
  5230. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  5231. QualType type = decl->getType();
  5232. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  5233. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  5234. // Various kinds of declaration aren't allowed to be __autoreleasing.
  5235. unsigned kind = -1U;
  5236. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5237. if (var->hasAttr<BlocksAttr>())
  5238. kind = 0; // __block
  5239. else if (!var->hasLocalStorage())
  5240. kind = 1; // global
  5241. } else if (isa<ObjCIvarDecl>(decl)) {
  5242. kind = 3; // ivar
  5243. } else if (isa<FieldDecl>(decl)) {
  5244. kind = 2; // field
  5245. }
  5246. if (kind != -1U) {
  5247. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  5248. << kind;
  5249. }
  5250. } else if (lifetime == Qualifiers::OCL_None) {
  5251. // Try to infer lifetime.
  5252. if (!type->isObjCLifetimeType())
  5253. return false;
  5254. lifetime = type->getObjCARCImplicitLifetime();
  5255. type = Context.getLifetimeQualifiedType(type, lifetime);
  5256. decl->setType(type);
  5257. }
  5258. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5259. // Thread-local variables cannot have lifetime.
  5260. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  5261. var->getTLSKind()) {
  5262. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  5263. << var->getType();
  5264. return true;
  5265. }
  5266. }
  5267. return false;
  5268. }
  5269. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  5270. // Ensure that an auto decl is deduced otherwise the checks below might cache
  5271. // the wrong linkage.
  5272. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  5273. // 'weak' only applies to declarations with external linkage.
  5274. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  5275. if (!ND.isExternallyVisible()) {
  5276. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  5277. ND.dropAttr<WeakAttr>();
  5278. }
  5279. }
  5280. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  5281. if (ND.isExternallyVisible()) {
  5282. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  5283. ND.dropAttr<WeakRefAttr>();
  5284. ND.dropAttr<AliasAttr>();
  5285. }
  5286. }
  5287. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  5288. if (VD->hasInit()) {
  5289. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  5290. assert(VD->isThisDeclarationADefinition() &&
  5291. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  5292. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  5293. VD->dropAttr<AliasAttr>();
  5294. }
  5295. }
  5296. }
  5297. // 'selectany' only applies to externally visible variable declarations.
  5298. // It does not apply to functions.
  5299. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  5300. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  5301. S.Diag(Attr->getLocation(),
  5302. diag::err_attribute_selectany_non_extern_data);
  5303. ND.dropAttr<SelectAnyAttr>();
  5304. }
  5305. }
  5306. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  5307. auto *VD = dyn_cast<VarDecl>(&ND);
  5308. bool IsAnonymousNS = false;
  5309. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5310. if (VD) {
  5311. const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
  5312. while (NS && !IsAnonymousNS) {
  5313. IsAnonymousNS = NS->isAnonymousNamespace();
  5314. NS = dyn_cast<NamespaceDecl>(NS->getParent());
  5315. }
  5316. }
  5317. // dll attributes require external linkage. Static locals may have external
  5318. // linkage but still cannot be explicitly imported or exported.
  5319. // In Microsoft mode, a variable defined in anonymous namespace must have
  5320. // external linkage in order to be exported.
  5321. bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
  5322. if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
  5323. (!AnonNSInMicrosoftMode &&
  5324. (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
  5325. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  5326. << &ND << Attr;
  5327. ND.setInvalidDecl();
  5328. }
  5329. }
  5330. // Virtual functions cannot be marked as 'notail'.
  5331. if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
  5332. if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
  5333. if (MD->isVirtual()) {
  5334. S.Diag(ND.getLocation(),
  5335. diag::err_invalid_attribute_on_virtual_function)
  5336. << Attr;
  5337. ND.dropAttr<NotTailCalledAttr>();
  5338. }
  5339. // Check the attributes on the function type, if any.
  5340. if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
  5341. // Don't declare this variable in the second operand of the for-statement;
  5342. // GCC miscompiles that by ending its lifetime before evaluating the
  5343. // third operand. See gcc.gnu.org/PR86769.
  5344. AttributedTypeLoc ATL;
  5345. for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
  5346. (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
  5347. TL = ATL.getModifiedLoc()) {
  5348. // The [[lifetimebound]] attribute can be applied to the implicit object
  5349. // parameter of a non-static member function (other than a ctor or dtor)
  5350. // by applying it to the function type.
  5351. if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
  5352. const auto *MD = dyn_cast<CXXMethodDecl>(FD);
  5353. if (!MD || MD->isStatic()) {
  5354. S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
  5355. << !MD << A->getRange();
  5356. } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
  5357. S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
  5358. << isa<CXXDestructorDecl>(MD) << A->getRange();
  5359. }
  5360. }
  5361. }
  5362. }
  5363. }
  5364. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  5365. NamedDecl *NewDecl,
  5366. bool IsSpecialization,
  5367. bool IsDefinition) {
  5368. if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
  5369. return;
  5370. bool IsTemplate = false;
  5371. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  5372. OldDecl = OldTD->getTemplatedDecl();
  5373. IsTemplate = true;
  5374. if (!IsSpecialization)
  5375. IsDefinition = false;
  5376. }
  5377. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  5378. NewDecl = NewTD->getTemplatedDecl();
  5379. IsTemplate = true;
  5380. }
  5381. if (!OldDecl || !NewDecl)
  5382. return;
  5383. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  5384. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5385. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5386. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5387. // dllimport and dllexport are inheritable attributes so we have to exclude
  5388. // inherited attribute instances.
  5389. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5390. (NewExportAttr && !NewExportAttr->isInherited());
  5391. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5392. // the only exception being explicit specializations.
  5393. // Implicitly generated declarations are also excluded for now because there
  5394. // is no other way to switch these to use dllimport or dllexport.
  5395. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5396. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5397. // Allow with a warning for free functions and global variables.
  5398. bool JustWarn = false;
  5399. if (!OldDecl->isCXXClassMember()) {
  5400. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5401. if (VD && !VD->getDescribedVarTemplate())
  5402. JustWarn = true;
  5403. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5404. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5405. JustWarn = true;
  5406. }
  5407. // We cannot change a declaration that's been used because IR has already
  5408. // been emitted. Dllimported functions will still work though (modulo
  5409. // address equality) as they can use the thunk.
  5410. if (OldDecl->isUsed())
  5411. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5412. JustWarn = false;
  5413. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5414. : diag::err_attribute_dll_redeclaration;
  5415. S.Diag(NewDecl->getLocation(), DiagID)
  5416. << NewDecl
  5417. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5418. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5419. if (!JustWarn) {
  5420. NewDecl->setInvalidDecl();
  5421. return;
  5422. }
  5423. }
  5424. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5425. // exceptions being inline function definitions (except for function
  5426. // templates), local extern declarations, qualified friend declarations or
  5427. // special MSVC extension: in the last case, the declaration is treated as if
  5428. // it were marked dllexport.
  5429. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5430. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5431. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5432. // Ignore static data because out-of-line definitions are diagnosed
  5433. // separately.
  5434. IsStaticDataMember = VD->isStaticDataMember();
  5435. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5436. VarDecl::DeclarationOnly;
  5437. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5438. IsInline = FD->isInlined();
  5439. IsQualifiedFriend = FD->getQualifier() &&
  5440. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5441. }
  5442. if (OldImportAttr && !HasNewAttr &&
  5443. (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
  5444. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5445. if (IsMicrosoft && IsDefinition) {
  5446. S.Diag(NewDecl->getLocation(),
  5447. diag::warn_redeclaration_without_import_attribute)
  5448. << NewDecl;
  5449. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5450. NewDecl->dropAttr<DLLImportAttr>();
  5451. NewDecl->addAttr(::new (S.Context) DLLExportAttr(
  5452. NewImportAttr->getRange(), S.Context,
  5453. NewImportAttr->getSpellingListIndex()));
  5454. } else {
  5455. S.Diag(NewDecl->getLocation(),
  5456. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5457. << NewDecl << OldImportAttr;
  5458. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5459. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5460. OldDecl->dropAttr<DLLImportAttr>();
  5461. NewDecl->dropAttr<DLLImportAttr>();
  5462. }
  5463. } else if (IsInline && OldImportAttr && !IsMicrosoft) {
  5464. // In MinGW, seeing a function declared inline drops the dllimport
  5465. // attribute.
  5466. OldDecl->dropAttr<DLLImportAttr>();
  5467. NewDecl->dropAttr<DLLImportAttr>();
  5468. S.Diag(NewDecl->getLocation(),
  5469. diag::warn_dllimport_dropped_from_inline_function)
  5470. << NewDecl << OldImportAttr;
  5471. }
  5472. // A specialization of a class template member function is processed here
  5473. // since it's a redeclaration. If the parent class is dllexport, the
  5474. // specialization inherits that attribute. This doesn't happen automatically
  5475. // since the parent class isn't instantiated until later.
  5476. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
  5477. if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
  5478. !NewImportAttr && !NewExportAttr) {
  5479. if (const DLLExportAttr *ParentExportAttr =
  5480. MD->getParent()->getAttr<DLLExportAttr>()) {
  5481. DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
  5482. NewAttr->setInherited(true);
  5483. NewDecl->addAttr(NewAttr);
  5484. }
  5485. }
  5486. }
  5487. }
  5488. /// Given that we are within the definition of the given function,
  5489. /// will that definition behave like C99's 'inline', where the
  5490. /// definition is discarded except for optimization purposes?
  5491. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  5492. // Try to avoid calling GetGVALinkageForFunction.
  5493. // All cases of this require the 'inline' keyword.
  5494. if (!FD->isInlined()) return false;
  5495. // This is only possible in C++ with the gnu_inline attribute.
  5496. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  5497. return false;
  5498. // Okay, go ahead and call the relatively-more-expensive function.
  5499. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  5500. }
  5501. /// Determine whether a variable is extern "C" prior to attaching
  5502. /// an initializer. We can't just call isExternC() here, because that
  5503. /// will also compute and cache whether the declaration is externally
  5504. /// visible, which might change when we attach the initializer.
  5505. ///
  5506. /// This can only be used if the declaration is known to not be a
  5507. /// redeclaration of an internal linkage declaration.
  5508. ///
  5509. /// For instance:
  5510. ///
  5511. /// auto x = []{};
  5512. ///
  5513. /// Attaching the initializer here makes this declaration not externally
  5514. /// visible, because its type has internal linkage.
  5515. ///
  5516. /// FIXME: This is a hack.
  5517. template<typename T>
  5518. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  5519. if (S.getLangOpts().CPlusPlus) {
  5520. // In C++, the overloadable attribute negates the effects of extern "C".
  5521. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  5522. return false;
  5523. // So do CUDA's host/device attributes.
  5524. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  5525. D->template hasAttr<CUDAHostAttr>()))
  5526. return false;
  5527. }
  5528. return D->isExternC();
  5529. }
  5530. static bool shouldConsiderLinkage(const VarDecl *VD) {
  5531. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  5532. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
  5533. isa<OMPDeclareMapperDecl>(DC))
  5534. return VD->hasExternalStorage();
  5535. if (DC->isFileContext())
  5536. return true;
  5537. if (DC->isRecord())
  5538. return false;
  5539. llvm_unreachable("Unexpected context");
  5540. }
  5541. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  5542. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  5543. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  5544. isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
  5545. return true;
  5546. if (DC->isRecord())
  5547. return false;
  5548. llvm_unreachable("Unexpected context");
  5549. }
  5550. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  5551. ParsedAttr::Kind Kind) {
  5552. // Check decl attributes on the DeclSpec.
  5553. if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
  5554. return true;
  5555. // Walk the declarator structure, checking decl attributes that were in a type
  5556. // position to the decl itself.
  5557. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  5558. if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
  5559. return true;
  5560. }
  5561. // Finally, check attributes on the decl itself.
  5562. return PD.getAttributes().hasAttribute(Kind);
  5563. }
  5564. /// Adjust the \c DeclContext for a function or variable that might be a
  5565. /// function-local external declaration.
  5566. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  5567. if (!DC->isFunctionOrMethod())
  5568. return false;
  5569. // If this is a local extern function or variable declared within a function
  5570. // template, don't add it into the enclosing namespace scope until it is
  5571. // instantiated; it might have a dependent type right now.
  5572. if (DC->isDependentContext())
  5573. return true;
  5574. // C++11 [basic.link]p7:
  5575. // When a block scope declaration of an entity with linkage is not found to
  5576. // refer to some other declaration, then that entity is a member of the
  5577. // innermost enclosing namespace.
  5578. //
  5579. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  5580. // semantically-enclosing namespace, not a lexically-enclosing one.
  5581. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  5582. DC = DC->getParent();
  5583. return true;
  5584. }
  5585. /// Returns true if given declaration has external C language linkage.
  5586. static bool isDeclExternC(const Decl *D) {
  5587. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  5588. return FD->isExternC();
  5589. if (const auto *VD = dyn_cast<VarDecl>(D))
  5590. return VD->isExternC();
  5591. llvm_unreachable("Unknown type of decl!");
  5592. }
  5593. NamedDecl *Sema::ActOnVariableDeclarator(
  5594. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  5595. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  5596. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  5597. QualType R = TInfo->getType();
  5598. DeclarationName Name = GetNameForDeclarator(D).getName();
  5599. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5600. if (D.isDecompositionDeclarator()) {
  5601. // Take the name of the first declarator as our name for diagnostic
  5602. // purposes.
  5603. auto &Decomp = D.getDecompositionDeclarator();
  5604. if (!Decomp.bindings().empty()) {
  5605. II = Decomp.bindings()[0].Name;
  5606. Name = II;
  5607. }
  5608. } else if (!II) {
  5609. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
  5610. return nullptr;
  5611. }
  5612. if (getLangOpts().OpenCL) {
  5613. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  5614. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  5615. // argument.
  5616. if (R->isImageType() || R->isPipeType()) {
  5617. Diag(D.getIdentifierLoc(),
  5618. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  5619. << R;
  5620. D.setInvalidType();
  5621. return nullptr;
  5622. }
  5623. // OpenCL v1.2 s6.9.r:
  5624. // The event type cannot be used to declare a program scope variable.
  5625. // OpenCL v2.0 s6.9.q:
  5626. // The clk_event_t and reserve_id_t types cannot be declared in program scope.
  5627. if (NULL == S->getParent()) {
  5628. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  5629. Diag(D.getIdentifierLoc(),
  5630. diag::err_invalid_type_for_program_scope_var) << R;
  5631. D.setInvalidType();
  5632. return nullptr;
  5633. }
  5634. }
  5635. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  5636. QualType NR = R;
  5637. while (NR->isPointerType()) {
  5638. if (NR->isFunctionPointerType()) {
  5639. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
  5640. D.setInvalidType();
  5641. break;
  5642. }
  5643. NR = NR->getPointeeType();
  5644. }
  5645. if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  5646. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5647. // half array type (unless the cl_khr_fp16 extension is enabled).
  5648. if (Context.getBaseElementType(R)->isHalfType()) {
  5649. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5650. D.setInvalidType();
  5651. }
  5652. }
  5653. if (R->isSamplerT()) {
  5654. // OpenCL v1.2 s6.9.b p4:
  5655. // The sampler type cannot be used with the __local and __global address
  5656. // space qualifiers.
  5657. if (R.getAddressSpace() == LangAS::opencl_local ||
  5658. R.getAddressSpace() == LangAS::opencl_global) {
  5659. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5660. }
  5661. // OpenCL v1.2 s6.12.14.1:
  5662. // A global sampler must be declared with either the constant address
  5663. // space qualifier or with the const qualifier.
  5664. if (DC->isTranslationUnit() &&
  5665. !(R.getAddressSpace() == LangAS::opencl_constant ||
  5666. R.isConstQualified())) {
  5667. Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
  5668. D.setInvalidType();
  5669. }
  5670. }
  5671. // OpenCL v1.2 s6.9.r:
  5672. // The event type cannot be used with the __local, __constant and __global
  5673. // address space qualifiers.
  5674. if (R->isEventT()) {
  5675. if (R.getAddressSpace() != LangAS::opencl_private) {
  5676. Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
  5677. D.setInvalidType();
  5678. }
  5679. }
  5680. // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
  5681. // supported. OpenCL C does not support thread_local either, and
  5682. // also reject all other thread storage class specifiers.
  5683. DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
  5684. if (TSC != TSCS_unspecified) {
  5685. bool IsCXX = getLangOpts().OpenCLCPlusPlus;
  5686. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5687. diag::err_opencl_unknown_type_specifier)
  5688. << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
  5689. << DeclSpec::getSpecifierName(TSC) << 1;
  5690. D.setInvalidType();
  5691. return nullptr;
  5692. }
  5693. }
  5694. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  5695. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  5696. // dllimport globals without explicit storage class are treated as extern. We
  5697. // have to change the storage class this early to get the right DeclContext.
  5698. if (SC == SC_None && !DC->isRecord() &&
  5699. hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
  5700. !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
  5701. SC = SC_Extern;
  5702. DeclContext *OriginalDC = DC;
  5703. bool IsLocalExternDecl = SC == SC_Extern &&
  5704. adjustContextForLocalExternDecl(DC);
  5705. if (SCSpec == DeclSpec::SCS_mutable) {
  5706. // mutable can only appear on non-static class members, so it's always
  5707. // an error here
  5708. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5709. D.setInvalidType();
  5710. SC = SC_None;
  5711. }
  5712. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5713. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5714. D.getDeclSpec().getStorageClassSpecLoc())) {
  5715. // In C++11, the 'register' storage class specifier is deprecated.
  5716. // Suppress the warning in system macros, it's used in macros in some
  5717. // popular C system headers, such as in glibc's htonl() macro.
  5718. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5719. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  5720. : diag::warn_deprecated_register)
  5721. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5722. }
  5723. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5724. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5725. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5726. // appear in the declaration specifiers in an external declaration.
  5727. // Global Register+Asm is a GNU extension we support.
  5728. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5729. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5730. D.setInvalidType();
  5731. }
  5732. }
  5733. bool IsMemberSpecialization = false;
  5734. bool IsVariableTemplateSpecialization = false;
  5735. bool IsPartialSpecialization = false;
  5736. bool IsVariableTemplate = false;
  5737. VarDecl *NewVD = nullptr;
  5738. VarTemplateDecl *NewTemplate = nullptr;
  5739. TemplateParameterList *TemplateParams = nullptr;
  5740. if (!getLangOpts().CPlusPlus) {
  5741. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
  5742. II, R, TInfo, SC);
  5743. if (R->getContainedDeducedType())
  5744. ParsingInitForAutoVars.insert(NewVD);
  5745. if (D.isInvalidType())
  5746. NewVD->setInvalidDecl();
  5747. } else {
  5748. bool Invalid = false;
  5749. if (DC->isRecord() && !CurContext->isRecord()) {
  5750. // This is an out-of-line definition of a static data member.
  5751. switch (SC) {
  5752. case SC_None:
  5753. break;
  5754. case SC_Static:
  5755. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5756. diag::err_static_out_of_line)
  5757. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5758. break;
  5759. case SC_Auto:
  5760. case SC_Register:
  5761. case SC_Extern:
  5762. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5763. // to names of variables declared in a block or to function parameters.
  5764. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5765. // of class members
  5766. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5767. diag::err_storage_class_for_static_member)
  5768. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5769. break;
  5770. case SC_PrivateExtern:
  5771. llvm_unreachable("C storage class in c++!");
  5772. }
  5773. }
  5774. if (SC == SC_Static && CurContext->isRecord()) {
  5775. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5776. if (RD->isLocalClass())
  5777. Diag(D.getIdentifierLoc(),
  5778. diag::err_static_data_member_not_allowed_in_local_class)
  5779. << Name << RD->getDeclName();
  5780. // C++98 [class.union]p1: If a union contains a static data member,
  5781. // the program is ill-formed. C++11 drops this restriction.
  5782. if (RD->isUnion())
  5783. Diag(D.getIdentifierLoc(),
  5784. getLangOpts().CPlusPlus11
  5785. ? diag::warn_cxx98_compat_static_data_member_in_union
  5786. : diag::ext_static_data_member_in_union) << Name;
  5787. // We conservatively disallow static data members in anonymous structs.
  5788. else if (!RD->getDeclName())
  5789. Diag(D.getIdentifierLoc(),
  5790. diag::err_static_data_member_not_allowed_in_anon_struct)
  5791. << Name << RD->isUnion();
  5792. }
  5793. }
  5794. // Match up the template parameter lists with the scope specifier, then
  5795. // determine whether we have a template or a template specialization.
  5796. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5797. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  5798. D.getCXXScopeSpec(),
  5799. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  5800. ? D.getName().TemplateId
  5801. : nullptr,
  5802. TemplateParamLists,
  5803. /*never a friend*/ false, IsMemberSpecialization, Invalid);
  5804. if (TemplateParams) {
  5805. if (!TemplateParams->size() &&
  5806. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  5807. // There is an extraneous 'template<>' for this variable. Complain
  5808. // about it, but allow the declaration of the variable.
  5809. Diag(TemplateParams->getTemplateLoc(),
  5810. diag::err_template_variable_noparams)
  5811. << II
  5812. << SourceRange(TemplateParams->getTemplateLoc(),
  5813. TemplateParams->getRAngleLoc());
  5814. TemplateParams = nullptr;
  5815. } else {
  5816. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  5817. // This is an explicit specialization or a partial specialization.
  5818. // FIXME: Check that we can declare a specialization here.
  5819. IsVariableTemplateSpecialization = true;
  5820. IsPartialSpecialization = TemplateParams->size() > 0;
  5821. } else { // if (TemplateParams->size() > 0)
  5822. // This is a template declaration.
  5823. IsVariableTemplate = true;
  5824. // Check that we can declare a template here.
  5825. if (CheckTemplateDeclScope(S, TemplateParams))
  5826. return nullptr;
  5827. // Only C++1y supports variable templates (N3651).
  5828. Diag(D.getIdentifierLoc(),
  5829. getLangOpts().CPlusPlus14
  5830. ? diag::warn_cxx11_compat_variable_template
  5831. : diag::ext_variable_template);
  5832. }
  5833. }
  5834. } else {
  5835. assert((Invalid ||
  5836. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
  5837. "should have a 'template<>' for this decl");
  5838. }
  5839. if (IsVariableTemplateSpecialization) {
  5840. SourceLocation TemplateKWLoc =
  5841. TemplateParamLists.size() > 0
  5842. ? TemplateParamLists[0]->getTemplateLoc()
  5843. : SourceLocation();
  5844. DeclResult Res = ActOnVarTemplateSpecialization(
  5845. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5846. IsPartialSpecialization);
  5847. if (Res.isInvalid())
  5848. return nullptr;
  5849. NewVD = cast<VarDecl>(Res.get());
  5850. AddToScope = false;
  5851. } else if (D.isDecompositionDeclarator()) {
  5852. NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
  5853. D.getIdentifierLoc(), R, TInfo, SC,
  5854. Bindings);
  5855. } else
  5856. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
  5857. D.getIdentifierLoc(), II, R, TInfo, SC);
  5858. // If this is supposed to be a variable template, create it as such.
  5859. if (IsVariableTemplate) {
  5860. NewTemplate =
  5861. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5862. TemplateParams, NewVD);
  5863. NewVD->setDescribedVarTemplate(NewTemplate);
  5864. }
  5865. // If this decl has an auto type in need of deduction, make a note of the
  5866. // Decl so we can diagnose uses of it in its own initializer.
  5867. if (R->getContainedDeducedType())
  5868. ParsingInitForAutoVars.insert(NewVD);
  5869. if (D.isInvalidType() || Invalid) {
  5870. NewVD->setInvalidDecl();
  5871. if (NewTemplate)
  5872. NewTemplate->setInvalidDecl();
  5873. }
  5874. SetNestedNameSpecifier(*this, NewVD, D);
  5875. // If we have any template parameter lists that don't directly belong to
  5876. // the variable (matching the scope specifier), store them.
  5877. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5878. if (TemplateParamLists.size() > VDTemplateParamLists)
  5879. NewVD->setTemplateParameterListsInfo(
  5880. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  5881. if (D.getDeclSpec().isConstexprSpecified()) {
  5882. NewVD->setConstexpr(true);
  5883. // C++1z [dcl.spec.constexpr]p1:
  5884. // A static data member declared with the constexpr specifier is
  5885. // implicitly an inline variable.
  5886. if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
  5887. NewVD->setImplicitlyInline();
  5888. }
  5889. }
  5890. if (D.getDeclSpec().isInlineSpecified()) {
  5891. if (!getLangOpts().CPlusPlus) {
  5892. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5893. << 0;
  5894. } else if (CurContext->isFunctionOrMethod()) {
  5895. // 'inline' is not allowed on block scope variable declaration.
  5896. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5897. diag::err_inline_declaration_block_scope) << Name
  5898. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  5899. } else {
  5900. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5901. getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
  5902. : diag::ext_inline_variable);
  5903. NewVD->setInlineSpecified();
  5904. }
  5905. }
  5906. // Set the lexical context. If the declarator has a C++ scope specifier, the
  5907. // lexical context will be different from the semantic context.
  5908. NewVD->setLexicalDeclContext(CurContext);
  5909. if (NewTemplate)
  5910. NewTemplate->setLexicalDeclContext(CurContext);
  5911. if (IsLocalExternDecl) {
  5912. if (D.isDecompositionDeclarator())
  5913. for (auto *B : Bindings)
  5914. B->setLocalExternDecl();
  5915. else
  5916. NewVD->setLocalExternDecl();
  5917. }
  5918. bool EmitTLSUnsupportedError = false;
  5919. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  5920. // C++11 [dcl.stc]p4:
  5921. // When thread_local is applied to a variable of block scope the
  5922. // storage-class-specifier static is implied if it does not appear
  5923. // explicitly.
  5924. // Core issue: 'static' is not implied if the variable is declared
  5925. // 'extern'.
  5926. if (NewVD->hasLocalStorage() &&
  5927. (SCSpec != DeclSpec::SCS_unspecified ||
  5928. TSCS != DeclSpec::TSCS_thread_local ||
  5929. !DC->isFunctionOrMethod()))
  5930. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5931. diag::err_thread_non_global)
  5932. << DeclSpec::getSpecifierName(TSCS);
  5933. else if (!Context.getTargetInfo().isTLSSupported()) {
  5934. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  5935. // Postpone error emission until we've collected attributes required to
  5936. // figure out whether it's a host or device variable and whether the
  5937. // error should be ignored.
  5938. EmitTLSUnsupportedError = true;
  5939. // We still need to mark the variable as TLS so it shows up in AST with
  5940. // proper storage class for other tools to use even if we're not going
  5941. // to emit any code for it.
  5942. NewVD->setTSCSpec(TSCS);
  5943. } else
  5944. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5945. diag::err_thread_unsupported);
  5946. } else
  5947. NewVD->setTSCSpec(TSCS);
  5948. }
  5949. // C99 6.7.4p3
  5950. // An inline definition of a function with external linkage shall
  5951. // not contain a definition of a modifiable object with static or
  5952. // thread storage duration...
  5953. // We only apply this when the function is required to be defined
  5954. // elsewhere, i.e. when the function is not 'extern inline'. Note
  5955. // that a local variable with thread storage duration still has to
  5956. // be marked 'static'. Also note that it's possible to get these
  5957. // semantics in C++ using __attribute__((gnu_inline)).
  5958. if (SC == SC_Static && S->getFnParent() != nullptr &&
  5959. !NewVD->getType().isConstQualified()) {
  5960. FunctionDecl *CurFD = getCurFunctionDecl();
  5961. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  5962. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5963. diag::warn_static_local_in_extern_inline);
  5964. MaybeSuggestAddingStaticToDecl(CurFD);
  5965. }
  5966. }
  5967. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5968. if (IsVariableTemplateSpecialization)
  5969. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5970. << (IsPartialSpecialization ? 1 : 0)
  5971. << FixItHint::CreateRemoval(
  5972. D.getDeclSpec().getModulePrivateSpecLoc());
  5973. else if (IsMemberSpecialization)
  5974. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5975. << 2
  5976. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5977. else if (NewVD->hasLocalStorage())
  5978. Diag(NewVD->getLocation(), diag::err_module_private_local)
  5979. << 0 << NewVD->getDeclName()
  5980. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5981. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5982. else {
  5983. NewVD->setModulePrivate();
  5984. if (NewTemplate)
  5985. NewTemplate->setModulePrivate();
  5986. for (auto *B : Bindings)
  5987. B->setModulePrivate();
  5988. }
  5989. }
  5990. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5991. ProcessDeclAttributes(S, NewVD, D);
  5992. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  5993. if (EmitTLSUnsupportedError &&
  5994. ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
  5995. (getLangOpts().OpenMPIsDevice &&
  5996. NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
  5997. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5998. diag::err_thread_unsupported);
  5999. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  6000. // storage [duration]."
  6001. if (SC == SC_None && S->getFnParent() != nullptr &&
  6002. (NewVD->hasAttr<CUDASharedAttr>() ||
  6003. NewVD->hasAttr<CUDAConstantAttr>())) {
  6004. NewVD->setStorageClass(SC_Static);
  6005. }
  6006. }
  6007. // Ensure that dllimport globals without explicit storage class are treated as
  6008. // extern. The storage class is set above using parsed attributes. Now we can
  6009. // check the VarDecl itself.
  6010. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  6011. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  6012. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  6013. // In auto-retain/release, infer strong retension for variables of
  6014. // retainable type.
  6015. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  6016. NewVD->setInvalidDecl();
  6017. // Handle GNU asm-label extension (encoded as an attribute).
  6018. if (Expr *E = (Expr*)D.getAsmLabel()) {
  6019. // The parser guarantees this is a string.
  6020. StringLiteral *SE = cast<StringLiteral>(E);
  6021. StringRef Label = SE->getString();
  6022. if (S->getFnParent() != nullptr) {
  6023. switch (SC) {
  6024. case SC_None:
  6025. case SC_Auto:
  6026. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  6027. break;
  6028. case SC_Register:
  6029. // Local Named register
  6030. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  6031. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  6032. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6033. break;
  6034. case SC_Static:
  6035. case SC_Extern:
  6036. case SC_PrivateExtern:
  6037. break;
  6038. }
  6039. } else if (SC == SC_Register) {
  6040. // Global Named register
  6041. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  6042. const auto &TI = Context.getTargetInfo();
  6043. bool HasSizeMismatch;
  6044. if (!TI.isValidGCCRegisterName(Label))
  6045. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6046. else if (!TI.validateGlobalRegisterVariable(Label,
  6047. Context.getTypeSize(R),
  6048. HasSizeMismatch))
  6049. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  6050. else if (HasSizeMismatch)
  6051. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  6052. }
  6053. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  6054. Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
  6055. NewVD->setInvalidDecl(true);
  6056. }
  6057. }
  6058. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  6059. Context, Label, 0));
  6060. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  6061. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6062. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  6063. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6064. if (isDeclExternC(NewVD)) {
  6065. NewVD->addAttr(I->second);
  6066. ExtnameUndeclaredIdentifiers.erase(I);
  6067. } else
  6068. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  6069. << /*Variable*/1 << NewVD;
  6070. }
  6071. }
  6072. // Find the shadowed declaration before filtering for scope.
  6073. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  6074. ? getShadowedDeclaration(NewVD, Previous)
  6075. : nullptr;
  6076. // Don't consider existing declarations that are in a different
  6077. // scope and are out-of-semantic-context declarations (if the new
  6078. // declaration has linkage).
  6079. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  6080. D.getCXXScopeSpec().isNotEmpty() ||
  6081. IsMemberSpecialization ||
  6082. IsVariableTemplateSpecialization);
  6083. // Check whether the previous declaration is in the same block scope. This
  6084. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  6085. if (getLangOpts().CPlusPlus &&
  6086. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  6087. NewVD->setPreviousDeclInSameBlockScope(
  6088. Previous.isSingleResult() && !Previous.isShadowed() &&
  6089. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  6090. if (!getLangOpts().CPlusPlus) {
  6091. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6092. } else {
  6093. // If this is an explicit specialization of a static data member, check it.
  6094. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  6095. CheckMemberSpecialization(NewVD, Previous))
  6096. NewVD->setInvalidDecl();
  6097. // Merge the decl with the existing one if appropriate.
  6098. if (!Previous.empty()) {
  6099. if (Previous.isSingleResult() &&
  6100. isa<FieldDecl>(Previous.getFoundDecl()) &&
  6101. D.getCXXScopeSpec().isSet()) {
  6102. // The user tried to define a non-static data member
  6103. // out-of-line (C++ [dcl.meaning]p1).
  6104. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  6105. << D.getCXXScopeSpec().getRange();
  6106. Previous.clear();
  6107. NewVD->setInvalidDecl();
  6108. }
  6109. } else if (D.getCXXScopeSpec().isSet()) {
  6110. // No previous declaration in the qualifying scope.
  6111. Diag(D.getIdentifierLoc(), diag::err_no_member)
  6112. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  6113. << D.getCXXScopeSpec().getRange();
  6114. NewVD->setInvalidDecl();
  6115. }
  6116. if (!IsVariableTemplateSpecialization)
  6117. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6118. if (NewTemplate) {
  6119. VarTemplateDecl *PrevVarTemplate =
  6120. NewVD->getPreviousDecl()
  6121. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  6122. : nullptr;
  6123. // Check the template parameter list of this declaration, possibly
  6124. // merging in the template parameter list from the previous variable
  6125. // template declaration.
  6126. if (CheckTemplateParameterList(
  6127. TemplateParams,
  6128. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  6129. : nullptr,
  6130. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  6131. DC->isDependentContext())
  6132. ? TPC_ClassTemplateMember
  6133. : TPC_VarTemplate))
  6134. NewVD->setInvalidDecl();
  6135. // If we are providing an explicit specialization of a static variable
  6136. // template, make a note of that.
  6137. if (PrevVarTemplate &&
  6138. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  6139. PrevVarTemplate->setMemberSpecialization();
  6140. }
  6141. }
  6142. // Diagnose shadowed variables iff this isn't a redeclaration.
  6143. if (ShadowedDecl && !D.isRedeclaration())
  6144. CheckShadow(NewVD, ShadowedDecl, Previous);
  6145. ProcessPragmaWeak(S, NewVD);
  6146. // If this is the first declaration of an extern C variable, update
  6147. // the map of such variables.
  6148. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  6149. isIncompleteDeclExternC(*this, NewVD))
  6150. RegisterLocallyScopedExternCDecl(NewVD, S);
  6151. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  6152. Decl *ManglingContextDecl;
  6153. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  6154. NewVD->getDeclContext(), ManglingContextDecl)) {
  6155. Context.setManglingNumber(
  6156. NewVD, MCtx->getManglingNumber(
  6157. NewVD, getMSManglingNumber(getLangOpts(), S)));
  6158. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  6159. }
  6160. }
  6161. // Special handling of variable named 'main'.
  6162. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  6163. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  6164. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  6165. // C++ [basic.start.main]p3
  6166. // A program that declares a variable main at global scope is ill-formed.
  6167. if (getLangOpts().CPlusPlus)
  6168. Diag(D.getBeginLoc(), diag::err_main_global_variable);
  6169. // In C, and external-linkage variable named main results in undefined
  6170. // behavior.
  6171. else if (NewVD->hasExternalFormalLinkage())
  6172. Diag(D.getBeginLoc(), diag::warn_main_redefined);
  6173. }
  6174. if (D.isRedeclaration() && !Previous.empty()) {
  6175. NamedDecl *Prev = Previous.getRepresentativeDecl();
  6176. checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
  6177. D.isFunctionDefinition());
  6178. }
  6179. if (NewTemplate) {
  6180. if (NewVD->isInvalidDecl())
  6181. NewTemplate->setInvalidDecl();
  6182. ActOnDocumentableDecl(NewTemplate);
  6183. return NewTemplate;
  6184. }
  6185. if (IsMemberSpecialization && !NewVD->isInvalidDecl())
  6186. CompleteMemberSpecialization(NewVD, Previous);
  6187. return NewVD;
  6188. }
  6189. /// Enum describing the %select options in diag::warn_decl_shadow.
  6190. enum ShadowedDeclKind {
  6191. SDK_Local,
  6192. SDK_Global,
  6193. SDK_StaticMember,
  6194. SDK_Field,
  6195. SDK_Typedef,
  6196. SDK_Using
  6197. };
  6198. /// Determine what kind of declaration we're shadowing.
  6199. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  6200. const DeclContext *OldDC) {
  6201. if (isa<TypeAliasDecl>(ShadowedDecl))
  6202. return SDK_Using;
  6203. else if (isa<TypedefDecl>(ShadowedDecl))
  6204. return SDK_Typedef;
  6205. else if (isa<RecordDecl>(OldDC))
  6206. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  6207. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  6208. }
  6209. /// Return the location of the capture if the given lambda captures the given
  6210. /// variable \p VD, or an invalid source location otherwise.
  6211. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  6212. const VarDecl *VD) {
  6213. for (const Capture &Capture : LSI->Captures) {
  6214. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  6215. return Capture.getLocation();
  6216. }
  6217. return SourceLocation();
  6218. }
  6219. static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
  6220. const LookupResult &R) {
  6221. // Only diagnose if we're shadowing an unambiguous field or variable.
  6222. if (R.getResultKind() != LookupResult::Found)
  6223. return false;
  6224. // Return false if warning is ignored.
  6225. return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
  6226. }
  6227. /// Return the declaration shadowed by the given variable \p D, or null
  6228. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6229. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  6230. const LookupResult &R) {
  6231. if (!shouldWarnIfShadowedDecl(Diags, R))
  6232. return nullptr;
  6233. // Don't diagnose declarations at file scope.
  6234. if (D->hasGlobalStorage())
  6235. return nullptr;
  6236. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6237. return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
  6238. ? ShadowedDecl
  6239. : nullptr;
  6240. }
  6241. /// Return the declaration shadowed by the given typedef \p D, or null
  6242. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6243. NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
  6244. const LookupResult &R) {
  6245. // Don't warn if typedef declaration is part of a class
  6246. if (D->getDeclContext()->isRecord())
  6247. return nullptr;
  6248. if (!shouldWarnIfShadowedDecl(Diags, R))
  6249. return nullptr;
  6250. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6251. return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
  6252. }
  6253. /// Diagnose variable or built-in function shadowing. Implements
  6254. /// -Wshadow.
  6255. ///
  6256. /// This method is called whenever a VarDecl is added to a "useful"
  6257. /// scope.
  6258. ///
  6259. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  6260. /// \param R the lookup of the name
  6261. ///
  6262. void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
  6263. const LookupResult &R) {
  6264. DeclContext *NewDC = D->getDeclContext();
  6265. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  6266. // Fields are not shadowed by variables in C++ static methods.
  6267. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  6268. if (MD->isStatic())
  6269. return;
  6270. // Fields shadowed by constructor parameters are a special case. Usually
  6271. // the constructor initializes the field with the parameter.
  6272. if (isa<CXXConstructorDecl>(NewDC))
  6273. if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
  6274. // Remember that this was shadowed so we can either warn about its
  6275. // modification or its existence depending on warning settings.
  6276. ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
  6277. return;
  6278. }
  6279. }
  6280. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  6281. if (shadowedVar->isExternC()) {
  6282. // For shadowing external vars, make sure that we point to the global
  6283. // declaration, not a locally scoped extern declaration.
  6284. for (auto I : shadowedVar->redecls())
  6285. if (I->isFileVarDecl()) {
  6286. ShadowedDecl = I;
  6287. break;
  6288. }
  6289. }
  6290. DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
  6291. unsigned WarningDiag = diag::warn_decl_shadow;
  6292. SourceLocation CaptureLoc;
  6293. if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
  6294. isa<CXXMethodDecl>(NewDC)) {
  6295. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  6296. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  6297. if (RD->getLambdaCaptureDefault() == LCD_None) {
  6298. // Try to avoid warnings for lambdas with an explicit capture list.
  6299. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  6300. // Warn only when the lambda captures the shadowed decl explicitly.
  6301. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  6302. if (CaptureLoc.isInvalid())
  6303. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  6304. } else {
  6305. // Remember that this was shadowed so we can avoid the warning if the
  6306. // shadowed decl isn't captured and the warning settings allow it.
  6307. cast<LambdaScopeInfo>(getCurFunction())
  6308. ->ShadowingDecls.push_back(
  6309. {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
  6310. return;
  6311. }
  6312. }
  6313. if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
  6314. // A variable can't shadow a local variable in an enclosing scope, if
  6315. // they are separated by a non-capturing declaration context.
  6316. for (DeclContext *ParentDC = NewDC;
  6317. ParentDC && !ParentDC->Equals(OldDC);
  6318. ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
  6319. // Only block literals, captured statements, and lambda expressions
  6320. // can capture; other scopes don't.
  6321. if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
  6322. !isLambdaCallOperator(ParentDC)) {
  6323. return;
  6324. }
  6325. }
  6326. }
  6327. }
  6328. }
  6329. // Only warn about certain kinds of shadowing for class members.
  6330. if (NewDC && NewDC->isRecord()) {
  6331. // In particular, don't warn about shadowing non-class members.
  6332. if (!OldDC->isRecord())
  6333. return;
  6334. // TODO: should we warn about static data members shadowing
  6335. // static data members from base classes?
  6336. // TODO: don't diagnose for inaccessible shadowed members.
  6337. // This is hard to do perfectly because we might friend the
  6338. // shadowing context, but that's just a false negative.
  6339. }
  6340. DeclarationName Name = R.getLookupName();
  6341. // Emit warning and note.
  6342. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  6343. return;
  6344. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  6345. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  6346. if (!CaptureLoc.isInvalid())
  6347. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6348. << Name << /*explicitly*/ 1;
  6349. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6350. }
  6351. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  6352. /// when these variables are captured by the lambda.
  6353. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  6354. for (const auto &Shadow : LSI->ShadowingDecls) {
  6355. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  6356. // Try to avoid the warning when the shadowed decl isn't captured.
  6357. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  6358. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6359. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  6360. ? diag::warn_decl_shadow_uncaptured_local
  6361. : diag::warn_decl_shadow)
  6362. << Shadow.VD->getDeclName()
  6363. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  6364. if (!CaptureLoc.isInvalid())
  6365. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6366. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  6367. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6368. }
  6369. }
  6370. /// Check -Wshadow without the advantage of a previous lookup.
  6371. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  6372. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  6373. return;
  6374. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  6375. Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  6376. LookupName(R, S);
  6377. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  6378. CheckShadow(D, ShadowedDecl, R);
  6379. }
  6380. /// Check if 'E', which is an expression that is about to be modified, refers
  6381. /// to a constructor parameter that shadows a field.
  6382. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  6383. // Quickly ignore expressions that can't be shadowing ctor parameters.
  6384. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  6385. return;
  6386. E = E->IgnoreParenImpCasts();
  6387. auto *DRE = dyn_cast<DeclRefExpr>(E);
  6388. if (!DRE)
  6389. return;
  6390. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  6391. auto I = ShadowingDecls.find(D);
  6392. if (I == ShadowingDecls.end())
  6393. return;
  6394. const NamedDecl *ShadowedDecl = I->second;
  6395. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6396. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  6397. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  6398. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6399. // Avoid issuing multiple warnings about the same decl.
  6400. ShadowingDecls.erase(I);
  6401. }
  6402. /// Check for conflict between this global or extern "C" declaration and
  6403. /// previous global or extern "C" declarations. This is only used in C++.
  6404. template<typename T>
  6405. static bool checkGlobalOrExternCConflict(
  6406. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  6407. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  6408. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  6409. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  6410. // The common case: this global doesn't conflict with any extern "C"
  6411. // declaration.
  6412. return false;
  6413. }
  6414. if (Prev) {
  6415. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  6416. // Both the old and new declarations have C language linkage. This is a
  6417. // redeclaration.
  6418. Previous.clear();
  6419. Previous.addDecl(Prev);
  6420. return true;
  6421. }
  6422. // This is a global, non-extern "C" declaration, and there is a previous
  6423. // non-global extern "C" declaration. Diagnose if this is a variable
  6424. // declaration.
  6425. if (!isa<VarDecl>(ND))
  6426. return false;
  6427. } else {
  6428. // The declaration is extern "C". Check for any declaration in the
  6429. // translation unit which might conflict.
  6430. if (IsGlobal) {
  6431. // We have already performed the lookup into the translation unit.
  6432. IsGlobal = false;
  6433. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6434. I != E; ++I) {
  6435. if (isa<VarDecl>(*I)) {
  6436. Prev = *I;
  6437. break;
  6438. }
  6439. }
  6440. } else {
  6441. DeclContext::lookup_result R =
  6442. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  6443. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  6444. I != E; ++I) {
  6445. if (isa<VarDecl>(*I)) {
  6446. Prev = *I;
  6447. break;
  6448. }
  6449. // FIXME: If we have any other entity with this name in global scope,
  6450. // the declaration is ill-formed, but that is a defect: it breaks the
  6451. // 'stat' hack, for instance. Only variables can have mangled name
  6452. // clashes with extern "C" declarations, so only they deserve a
  6453. // diagnostic.
  6454. }
  6455. }
  6456. if (!Prev)
  6457. return false;
  6458. }
  6459. // Use the first declaration's location to ensure we point at something which
  6460. // is lexically inside an extern "C" linkage-spec.
  6461. assert(Prev && "should have found a previous declaration to diagnose");
  6462. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  6463. Prev = FD->getFirstDecl();
  6464. else
  6465. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  6466. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  6467. << IsGlobal << ND;
  6468. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  6469. << IsGlobal;
  6470. return false;
  6471. }
  6472. /// Apply special rules for handling extern "C" declarations. Returns \c true
  6473. /// if we have found that this is a redeclaration of some prior entity.
  6474. ///
  6475. /// Per C++ [dcl.link]p6:
  6476. /// Two declarations [for a function or variable] with C language linkage
  6477. /// with the same name that appear in different scopes refer to the same
  6478. /// [entity]. An entity with C language linkage shall not be declared with
  6479. /// the same name as an entity in global scope.
  6480. template<typename T>
  6481. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  6482. LookupResult &Previous) {
  6483. if (!S.getLangOpts().CPlusPlus) {
  6484. // In C, when declaring a global variable, look for a corresponding 'extern'
  6485. // variable declared in function scope. We don't need this in C++, because
  6486. // we find local extern decls in the surrounding file-scope DeclContext.
  6487. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6488. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  6489. Previous.clear();
  6490. Previous.addDecl(Prev);
  6491. return true;
  6492. }
  6493. }
  6494. return false;
  6495. }
  6496. // A declaration in the translation unit can conflict with an extern "C"
  6497. // declaration.
  6498. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  6499. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  6500. // An extern "C" declaration can conflict with a declaration in the
  6501. // translation unit or can be a redeclaration of an extern "C" declaration
  6502. // in another scope.
  6503. if (isIncompleteDeclExternC(S,ND))
  6504. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  6505. // Neither global nor extern "C": nothing to do.
  6506. return false;
  6507. }
  6508. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  6509. // If the decl is already known invalid, don't check it.
  6510. if (NewVD->isInvalidDecl())
  6511. return;
  6512. QualType T = NewVD->getType();
  6513. // Defer checking an 'auto' type until its initializer is attached.
  6514. if (T->isUndeducedType())
  6515. return;
  6516. if (NewVD->hasAttrs())
  6517. CheckAlignasUnderalignment(NewVD);
  6518. if (T->isObjCObjectType()) {
  6519. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  6520. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  6521. T = Context.getObjCObjectPointerType(T);
  6522. NewVD->setType(T);
  6523. }
  6524. // Emit an error if an address space was applied to decl with local storage.
  6525. // This includes arrays of objects with address space qualifiers, but not
  6526. // automatic variables that point to other address spaces.
  6527. // ISO/IEC TR 18037 S5.1.2
  6528. if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
  6529. T.getAddressSpace() != LangAS::Default) {
  6530. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
  6531. NewVD->setInvalidDecl();
  6532. return;
  6533. }
  6534. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  6535. // scope.
  6536. if (getLangOpts().OpenCLVersion == 120 &&
  6537. !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
  6538. NewVD->isStaticLocal()) {
  6539. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  6540. NewVD->setInvalidDecl();
  6541. return;
  6542. }
  6543. if (getLangOpts().OpenCL) {
  6544. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  6545. if (NewVD->hasAttr<BlocksAttr>()) {
  6546. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  6547. return;
  6548. }
  6549. if (T->isBlockPointerType()) {
  6550. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  6551. // can't use 'extern' storage class.
  6552. if (!T.isConstQualified()) {
  6553. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  6554. << 0 /*const*/;
  6555. NewVD->setInvalidDecl();
  6556. return;
  6557. }
  6558. if (NewVD->hasExternalStorage()) {
  6559. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  6560. NewVD->setInvalidDecl();
  6561. return;
  6562. }
  6563. }
  6564. // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
  6565. // __constant address space.
  6566. // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
  6567. // variables inside a function can also be declared in the global
  6568. // address space.
  6569. // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local
  6570. // address space additionally.
  6571. // FIXME: Add local AS for OpenCL C++.
  6572. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  6573. NewVD->hasExternalStorage()) {
  6574. if (!T->isSamplerT() &&
  6575. !(T.getAddressSpace() == LangAS::opencl_constant ||
  6576. (T.getAddressSpace() == LangAS::opencl_global &&
  6577. (getLangOpts().OpenCLVersion == 200 ||
  6578. getLangOpts().OpenCLCPlusPlus)))) {
  6579. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  6580. if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
  6581. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6582. << Scope << "global or constant";
  6583. else
  6584. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6585. << Scope << "constant";
  6586. NewVD->setInvalidDecl();
  6587. return;
  6588. }
  6589. } else {
  6590. if (T.getAddressSpace() == LangAS::opencl_global) {
  6591. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6592. << 1 /*is any function*/ << "global";
  6593. NewVD->setInvalidDecl();
  6594. return;
  6595. }
  6596. if (T.getAddressSpace() == LangAS::opencl_constant ||
  6597. T.getAddressSpace() == LangAS::opencl_local) {
  6598. FunctionDecl *FD = getCurFunctionDecl();
  6599. // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
  6600. // in functions.
  6601. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  6602. if (T.getAddressSpace() == LangAS::opencl_constant)
  6603. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6604. << 0 /*non-kernel only*/ << "constant";
  6605. else
  6606. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6607. << 0 /*non-kernel only*/ << "local";
  6608. NewVD->setInvalidDecl();
  6609. return;
  6610. }
  6611. // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
  6612. // in the outermost scope of a kernel function.
  6613. if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
  6614. if (!getCurScope()->isFunctionScope()) {
  6615. if (T.getAddressSpace() == LangAS::opencl_constant)
  6616. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6617. << "constant";
  6618. else
  6619. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6620. << "local";
  6621. NewVD->setInvalidDecl();
  6622. return;
  6623. }
  6624. }
  6625. } else if (T.getAddressSpace() != LangAS::opencl_private) {
  6626. // Do not allow other address spaces on automatic variable.
  6627. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
  6628. NewVD->setInvalidDecl();
  6629. return;
  6630. }
  6631. }
  6632. }
  6633. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  6634. && !NewVD->hasAttr<BlocksAttr>()) {
  6635. if (getLangOpts().getGC() != LangOptions::NonGC)
  6636. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  6637. else {
  6638. assert(!getLangOpts().ObjCAutoRefCount);
  6639. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  6640. }
  6641. }
  6642. bool isVM = T->isVariablyModifiedType();
  6643. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  6644. NewVD->hasAttr<BlocksAttr>())
  6645. setFunctionHasBranchProtectedScope();
  6646. if ((isVM && NewVD->hasLinkage()) ||
  6647. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  6648. bool SizeIsNegative;
  6649. llvm::APSInt Oversized;
  6650. TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
  6651. NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
  6652. QualType FixedT;
  6653. if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
  6654. FixedT = FixedTInfo->getType();
  6655. else if (FixedTInfo) {
  6656. // Type and type-as-written are canonically different. We need to fix up
  6657. // both types separately.
  6658. FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  6659. Oversized);
  6660. }
  6661. if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
  6662. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  6663. // FIXME: This won't give the correct result for
  6664. // int a[10][n];
  6665. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  6666. if (NewVD->isFileVarDecl())
  6667. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  6668. << SizeRange;
  6669. else if (NewVD->isStaticLocal())
  6670. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  6671. << SizeRange;
  6672. else
  6673. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  6674. << SizeRange;
  6675. NewVD->setInvalidDecl();
  6676. return;
  6677. }
  6678. if (!FixedTInfo) {
  6679. if (NewVD->isFileVarDecl())
  6680. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  6681. else
  6682. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  6683. NewVD->setInvalidDecl();
  6684. return;
  6685. }
  6686. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  6687. NewVD->setType(FixedT);
  6688. NewVD->setTypeSourceInfo(FixedTInfo);
  6689. }
  6690. if (T->isVoidType()) {
  6691. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  6692. // of objects and functions.
  6693. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  6694. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  6695. << T;
  6696. NewVD->setInvalidDecl();
  6697. return;
  6698. }
  6699. }
  6700. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  6701. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  6702. NewVD->setInvalidDecl();
  6703. return;
  6704. }
  6705. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  6706. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  6707. NewVD->setInvalidDecl();
  6708. return;
  6709. }
  6710. if (NewVD->isConstexpr() && !T->isDependentType() &&
  6711. RequireLiteralType(NewVD->getLocation(), T,
  6712. diag::err_constexpr_var_non_literal)) {
  6713. NewVD->setInvalidDecl();
  6714. return;
  6715. }
  6716. }
  6717. /// Perform semantic checking on a newly-created variable
  6718. /// declaration.
  6719. ///
  6720. /// This routine performs all of the type-checking required for a
  6721. /// variable declaration once it has been built. It is used both to
  6722. /// check variables after they have been parsed and their declarators
  6723. /// have been translated into a declaration, and to check variables
  6724. /// that have been instantiated from a template.
  6725. ///
  6726. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  6727. ///
  6728. /// Returns true if the variable declaration is a redeclaration.
  6729. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  6730. CheckVariableDeclarationType(NewVD);
  6731. // If the decl is already known invalid, don't check it.
  6732. if (NewVD->isInvalidDecl())
  6733. return false;
  6734. // If we did not find anything by this name, look for a non-visible
  6735. // extern "C" declaration with the same name.
  6736. if (Previous.empty() &&
  6737. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  6738. Previous.setShadowed();
  6739. if (!Previous.empty()) {
  6740. MergeVarDecl(NewVD, Previous);
  6741. return true;
  6742. }
  6743. return false;
  6744. }
  6745. namespace {
  6746. struct FindOverriddenMethod {
  6747. Sema *S;
  6748. CXXMethodDecl *Method;
  6749. /// Member lookup function that determines whether a given C++
  6750. /// method overrides a method in a base class, to be used with
  6751. /// CXXRecordDecl::lookupInBases().
  6752. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6753. RecordDecl *BaseRecord =
  6754. Specifier->getType()->getAs<RecordType>()->getDecl();
  6755. DeclarationName Name = Method->getDeclName();
  6756. // FIXME: Do we care about other names here too?
  6757. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6758. // We really want to find the base class destructor here.
  6759. QualType T = S->Context.getTypeDeclType(BaseRecord);
  6760. CanQualType CT = S->Context.getCanonicalType(T);
  6761. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  6762. }
  6763. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6764. Path.Decls = Path.Decls.slice(1)) {
  6765. NamedDecl *D = Path.Decls.front();
  6766. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6767. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  6768. return true;
  6769. }
  6770. }
  6771. return false;
  6772. }
  6773. };
  6774. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  6775. } // end anonymous namespace
  6776. /// Report an error regarding overriding, along with any relevant
  6777. /// overridden methods.
  6778. ///
  6779. /// \param DiagID the primary error to report.
  6780. /// \param MD the overriding method.
  6781. /// \param OEK which overrides to include as notes.
  6782. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  6783. OverrideErrorKind OEK = OEK_All) {
  6784. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  6785. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  6786. // This check (& the OEK parameter) could be replaced by a predicate, but
  6787. // without lambdas that would be overkill. This is still nicer than writing
  6788. // out the diag loop 3 times.
  6789. if ((OEK == OEK_All) ||
  6790. (OEK == OEK_NonDeleted && !O->isDeleted()) ||
  6791. (OEK == OEK_Deleted && O->isDeleted()))
  6792. S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
  6793. }
  6794. }
  6795. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  6796. /// and if so, check that it's a valid override and remember it.
  6797. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  6798. // Look for methods in base classes that this method might override.
  6799. CXXBasePaths Paths;
  6800. FindOverriddenMethod FOM;
  6801. FOM.Method = MD;
  6802. FOM.S = this;
  6803. bool hasDeletedOverridenMethods = false;
  6804. bool hasNonDeletedOverridenMethods = false;
  6805. bool AddedAny = false;
  6806. if (DC->lookupInBases(FOM, Paths)) {
  6807. for (auto *I : Paths.found_decls()) {
  6808. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  6809. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  6810. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  6811. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  6812. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  6813. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  6814. hasDeletedOverridenMethods |= OldMD->isDeleted();
  6815. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  6816. AddedAny = true;
  6817. }
  6818. }
  6819. }
  6820. }
  6821. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  6822. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  6823. }
  6824. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  6825. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  6826. }
  6827. return AddedAny;
  6828. }
  6829. namespace {
  6830. // Struct for holding all of the extra arguments needed by
  6831. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  6832. struct ActOnFDArgs {
  6833. Scope *S;
  6834. Declarator &D;
  6835. MultiTemplateParamsArg TemplateParamLists;
  6836. bool AddToScope;
  6837. };
  6838. } // end anonymous namespace
  6839. namespace {
  6840. // Callback to only accept typo corrections that have a non-zero edit distance.
  6841. // Also only accept corrections that have the same parent decl.
  6842. class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
  6843. public:
  6844. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  6845. CXXRecordDecl *Parent)
  6846. : Context(Context), OriginalFD(TypoFD),
  6847. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  6848. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6849. if (candidate.getEditDistance() == 0)
  6850. return false;
  6851. SmallVector<unsigned, 1> MismatchedParams;
  6852. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  6853. CDeclEnd = candidate.end();
  6854. CDecl != CDeclEnd; ++CDecl) {
  6855. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6856. if (FD && !FD->hasBody() &&
  6857. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  6858. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  6859. CXXRecordDecl *Parent = MD->getParent();
  6860. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  6861. return true;
  6862. } else if (!ExpectedParent) {
  6863. return true;
  6864. }
  6865. }
  6866. }
  6867. return false;
  6868. }
  6869. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  6870. return llvm::make_unique<DifferentNameValidatorCCC>(*this);
  6871. }
  6872. private:
  6873. ASTContext &Context;
  6874. FunctionDecl *OriginalFD;
  6875. CXXRecordDecl *ExpectedParent;
  6876. };
  6877. } // end anonymous namespace
  6878. void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
  6879. TypoCorrectedFunctionDefinitions.insert(F);
  6880. }
  6881. /// Generate diagnostics for an invalid function redeclaration.
  6882. ///
  6883. /// This routine handles generating the diagnostic messages for an invalid
  6884. /// function redeclaration, including finding possible similar declarations
  6885. /// or performing typo correction if there are no previous declarations with
  6886. /// the same name.
  6887. ///
  6888. /// Returns a NamedDecl iff typo correction was performed and substituting in
  6889. /// the new declaration name does not cause new errors.
  6890. static NamedDecl *DiagnoseInvalidRedeclaration(
  6891. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  6892. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  6893. DeclarationName Name = NewFD->getDeclName();
  6894. DeclContext *NewDC = NewFD->getDeclContext();
  6895. SmallVector<unsigned, 1> MismatchedParams;
  6896. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  6897. TypoCorrection Correction;
  6898. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  6899. unsigned DiagMsg =
  6900. IsLocalFriend ? diag::err_no_matching_local_friend :
  6901. NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
  6902. diag::err_member_decl_does_not_match;
  6903. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  6904. IsLocalFriend ? Sema::LookupLocalFriendName
  6905. : Sema::LookupOrdinaryName,
  6906. Sema::ForVisibleRedeclaration);
  6907. NewFD->setInvalidDecl();
  6908. if (IsLocalFriend)
  6909. SemaRef.LookupName(Prev, S);
  6910. else
  6911. SemaRef.LookupQualifiedName(Prev, NewDC);
  6912. assert(!Prev.isAmbiguous() &&
  6913. "Cannot have an ambiguity in previous-declaration lookup");
  6914. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  6915. DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
  6916. MD ? MD->getParent() : nullptr);
  6917. if (!Prev.empty()) {
  6918. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  6919. Func != FuncEnd; ++Func) {
  6920. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  6921. if (FD &&
  6922. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6923. // Add 1 to the index so that 0 can mean the mismatch didn't
  6924. // involve a parameter
  6925. unsigned ParamNum =
  6926. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  6927. NearMatches.push_back(std::make_pair(FD, ParamNum));
  6928. }
  6929. }
  6930. // If the qualified name lookup yielded nothing, try typo correction
  6931. } else if ((Correction = SemaRef.CorrectTypo(
  6932. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  6933. &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
  6934. IsLocalFriend ? nullptr : NewDC))) {
  6935. // Set up everything for the call to ActOnFunctionDeclarator
  6936. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  6937. ExtraArgs.D.getIdentifierLoc());
  6938. Previous.clear();
  6939. Previous.setLookupName(Correction.getCorrection());
  6940. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  6941. CDeclEnd = Correction.end();
  6942. CDecl != CDeclEnd; ++CDecl) {
  6943. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6944. if (FD && !FD->hasBody() &&
  6945. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6946. Previous.addDecl(FD);
  6947. }
  6948. }
  6949. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  6950. NamedDecl *Result;
  6951. // Retry building the function declaration with the new previous
  6952. // declarations, and with errors suppressed.
  6953. {
  6954. // Trap errors.
  6955. Sema::SFINAETrap Trap(SemaRef);
  6956. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  6957. // pieces need to verify the typo-corrected C++ declaration and hopefully
  6958. // eliminate the need for the parameter pack ExtraArgs.
  6959. Result = SemaRef.ActOnFunctionDeclarator(
  6960. ExtraArgs.S, ExtraArgs.D,
  6961. Correction.getCorrectionDecl()->getDeclContext(),
  6962. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  6963. ExtraArgs.AddToScope);
  6964. if (Trap.hasErrorOccurred())
  6965. Result = nullptr;
  6966. }
  6967. if (Result) {
  6968. // Determine which correction we picked.
  6969. Decl *Canonical = Result->getCanonicalDecl();
  6970. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6971. I != E; ++I)
  6972. if ((*I)->getCanonicalDecl() == Canonical)
  6973. Correction.setCorrectionDecl(*I);
  6974. // Let Sema know about the correction.
  6975. SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
  6976. SemaRef.diagnoseTypo(
  6977. Correction,
  6978. SemaRef.PDiag(IsLocalFriend
  6979. ? diag::err_no_matching_local_friend_suggest
  6980. : diag::err_member_decl_does_not_match_suggest)
  6981. << Name << NewDC << IsDefinition);
  6982. return Result;
  6983. }
  6984. // Pretend the typo correction never occurred
  6985. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  6986. ExtraArgs.D.getIdentifierLoc());
  6987. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  6988. Previous.clear();
  6989. Previous.setLookupName(Name);
  6990. }
  6991. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  6992. << Name << NewDC << IsDefinition << NewFD->getLocation();
  6993. bool NewFDisConst = false;
  6994. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  6995. NewFDisConst = NewMD->isConst();
  6996. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  6997. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  6998. NearMatch != NearMatchEnd; ++NearMatch) {
  6999. FunctionDecl *FD = NearMatch->first;
  7000. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  7001. bool FDisConst = MD && MD->isConst();
  7002. bool IsMember = MD || !IsLocalFriend;
  7003. // FIXME: These notes are poorly worded for the local friend case.
  7004. if (unsigned Idx = NearMatch->second) {
  7005. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  7006. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  7007. if (Loc.isInvalid()) Loc = FD->getLocation();
  7008. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  7009. : diag::note_local_decl_close_param_match)
  7010. << Idx << FDParam->getType()
  7011. << NewFD->getParamDecl(Idx - 1)->getType();
  7012. } else if (FDisConst != NewFDisConst) {
  7013. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  7014. << NewFDisConst << FD->getSourceRange().getEnd();
  7015. } else
  7016. SemaRef.Diag(FD->getLocation(),
  7017. IsMember ? diag::note_member_def_close_match
  7018. : diag::note_local_decl_close_match);
  7019. }
  7020. return nullptr;
  7021. }
  7022. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  7023. switch (D.getDeclSpec().getStorageClassSpec()) {
  7024. default: llvm_unreachable("Unknown storage class!");
  7025. case DeclSpec::SCS_auto:
  7026. case DeclSpec::SCS_register:
  7027. case DeclSpec::SCS_mutable:
  7028. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7029. diag::err_typecheck_sclass_func);
  7030. D.getMutableDeclSpec().ClearStorageClassSpecs();
  7031. D.setInvalidType();
  7032. break;
  7033. case DeclSpec::SCS_unspecified: break;
  7034. case DeclSpec::SCS_extern:
  7035. if (D.getDeclSpec().isExternInLinkageSpec())
  7036. return SC_None;
  7037. return SC_Extern;
  7038. case DeclSpec::SCS_static: {
  7039. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  7040. // C99 6.7.1p5:
  7041. // The declaration of an identifier for a function that has
  7042. // block scope shall have no explicit storage-class specifier
  7043. // other than extern
  7044. // See also (C++ [dcl.stc]p4).
  7045. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7046. diag::err_static_block_func);
  7047. break;
  7048. } else
  7049. return SC_Static;
  7050. }
  7051. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  7052. }
  7053. // No explicit storage class has already been returned
  7054. return SC_None;
  7055. }
  7056. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  7057. DeclContext *DC, QualType &R,
  7058. TypeSourceInfo *TInfo,
  7059. StorageClass SC,
  7060. bool &IsVirtualOkay) {
  7061. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  7062. DeclarationName Name = NameInfo.getName();
  7063. FunctionDecl *NewFD = nullptr;
  7064. bool isInline = D.getDeclSpec().isInlineSpecified();
  7065. if (!SemaRef.getLangOpts().CPlusPlus) {
  7066. // Determine whether the function was written with a
  7067. // prototype. This true when:
  7068. // - there is a prototype in the declarator, or
  7069. // - the type R of the function is some kind of typedef or other non-
  7070. // attributed reference to a type name (which eventually refers to a
  7071. // function type).
  7072. bool HasPrototype =
  7073. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  7074. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  7075. NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7076. R, TInfo, SC, isInline, HasPrototype, false);
  7077. if (D.isInvalidType())
  7078. NewFD->setInvalidDecl();
  7079. return NewFD;
  7080. }
  7081. ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
  7082. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  7083. // Check that the return type is not an abstract class type.
  7084. // For record types, this is done by the AbstractClassUsageDiagnoser once
  7085. // the class has been completely parsed.
  7086. if (!DC->isRecord() &&
  7087. SemaRef.RequireNonAbstractType(
  7088. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  7089. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  7090. D.setInvalidType();
  7091. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  7092. // This is a C++ constructor declaration.
  7093. assert(DC->isRecord() &&
  7094. "Constructors can only be declared in a member context");
  7095. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  7096. return CXXConstructorDecl::Create(
  7097. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7098. TInfo, ExplicitSpecifier, isInline,
  7099. /*isImplicitlyDeclared=*/false, isConstexpr);
  7100. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7101. // This is a C++ destructor declaration.
  7102. if (DC->isRecord()) {
  7103. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  7104. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  7105. CXXDestructorDecl *NewDD =
  7106. CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
  7107. NameInfo, R, TInfo, isInline,
  7108. /*isImplicitlyDeclared=*/false);
  7109. // If the destructor needs an implicit exception specification, set it
  7110. // now. FIXME: It'd be nice to be able to create the right type to start
  7111. // with, but the type needs to reference the destructor declaration.
  7112. if (SemaRef.getLangOpts().CPlusPlus11)
  7113. SemaRef.AdjustDestructorExceptionSpec(NewDD);
  7114. IsVirtualOkay = true;
  7115. return NewDD;
  7116. } else {
  7117. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  7118. D.setInvalidType();
  7119. // Create a FunctionDecl to satisfy the function definition parsing
  7120. // code path.
  7121. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7122. D.getIdentifierLoc(), Name, R, TInfo, SC,
  7123. isInline,
  7124. /*hasPrototype=*/true, isConstexpr);
  7125. }
  7126. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  7127. if (!DC->isRecord()) {
  7128. SemaRef.Diag(D.getIdentifierLoc(),
  7129. diag::err_conv_function_not_member);
  7130. return nullptr;
  7131. }
  7132. SemaRef.CheckConversionDeclarator(D, R, SC);
  7133. IsVirtualOkay = true;
  7134. return CXXConversionDecl::Create(
  7135. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7136. TInfo, isInline, ExplicitSpecifier, isConstexpr, SourceLocation());
  7137. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  7138. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  7139. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7140. ExplicitSpecifier, NameInfo, R, TInfo,
  7141. D.getEndLoc());
  7142. } else if (DC->isRecord()) {
  7143. // If the name of the function is the same as the name of the record,
  7144. // then this must be an invalid constructor that has a return type.
  7145. // (The parser checks for a return type and makes the declarator a
  7146. // constructor if it has no return type).
  7147. if (Name.getAsIdentifierInfo() &&
  7148. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  7149. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  7150. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7151. << SourceRange(D.getIdentifierLoc());
  7152. return nullptr;
  7153. }
  7154. // This is a C++ method declaration.
  7155. CXXMethodDecl *Ret = CXXMethodDecl::Create(
  7156. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7157. TInfo, SC, isInline, isConstexpr, SourceLocation());
  7158. IsVirtualOkay = !Ret->isStatic();
  7159. return Ret;
  7160. } else {
  7161. bool isFriend =
  7162. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  7163. if (!isFriend && SemaRef.CurContext->isRecord())
  7164. return nullptr;
  7165. // Determine whether the function was written with a
  7166. // prototype. This true when:
  7167. // - we're in C++ (where every function has a prototype),
  7168. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7169. R, TInfo, SC, isInline, true /*HasPrototype*/,
  7170. isConstexpr);
  7171. }
  7172. }
  7173. enum OpenCLParamType {
  7174. ValidKernelParam,
  7175. PtrPtrKernelParam,
  7176. PtrKernelParam,
  7177. InvalidAddrSpacePtrKernelParam,
  7178. InvalidKernelParam,
  7179. RecordKernelParam
  7180. };
  7181. static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
  7182. // Size dependent types are just typedefs to normal integer types
  7183. // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
  7184. // integers other than by their names.
  7185. StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
  7186. // Remove typedefs one by one until we reach a typedef
  7187. // for a size dependent type.
  7188. QualType DesugaredTy = Ty;
  7189. do {
  7190. ArrayRef<StringRef> Names(SizeTypeNames);
  7191. auto Match = llvm::find(Names, DesugaredTy.getAsString());
  7192. if (Names.end() != Match)
  7193. return true;
  7194. Ty = DesugaredTy;
  7195. DesugaredTy = Ty.getSingleStepDesugaredType(C);
  7196. } while (DesugaredTy != Ty);
  7197. return false;
  7198. }
  7199. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  7200. if (PT->isPointerType()) {
  7201. QualType PointeeType = PT->getPointeeType();
  7202. if (PointeeType->isPointerType())
  7203. return PtrPtrKernelParam;
  7204. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  7205. PointeeType.getAddressSpace() == LangAS::opencl_private ||
  7206. PointeeType.getAddressSpace() == LangAS::Default)
  7207. return InvalidAddrSpacePtrKernelParam;
  7208. return PtrKernelParam;
  7209. }
  7210. // OpenCL v1.2 s6.9.k:
  7211. // Arguments to kernel functions in a program cannot be declared with the
  7212. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7213. // uintptr_t or a struct and/or union that contain fields declared to be one
  7214. // of these built-in scalar types.
  7215. if (isOpenCLSizeDependentType(S.getASTContext(), PT))
  7216. return InvalidKernelParam;
  7217. if (PT->isImageType())
  7218. return PtrKernelParam;
  7219. if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
  7220. return InvalidKernelParam;
  7221. // OpenCL extension spec v1.2 s9.5:
  7222. // This extension adds support for half scalar and vector types as built-in
  7223. // types that can be used for arithmetic operations, conversions etc.
  7224. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
  7225. return InvalidKernelParam;
  7226. if (PT->isRecordType())
  7227. return RecordKernelParam;
  7228. // Look into an array argument to check if it has a forbidden type.
  7229. if (PT->isArrayType()) {
  7230. const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
  7231. // Call ourself to check an underlying type of an array. Since the
  7232. // getPointeeOrArrayElementType returns an innermost type which is not an
  7233. // array, this recursive call only happens once.
  7234. return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
  7235. }
  7236. return ValidKernelParam;
  7237. }
  7238. static void checkIsValidOpenCLKernelParameter(
  7239. Sema &S,
  7240. Declarator &D,
  7241. ParmVarDecl *Param,
  7242. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  7243. QualType PT = Param->getType();
  7244. // Cache the valid types we encounter to avoid rechecking structs that are
  7245. // used again
  7246. if (ValidTypes.count(PT.getTypePtr()))
  7247. return;
  7248. switch (getOpenCLKernelParameterType(S, PT)) {
  7249. case PtrPtrKernelParam:
  7250. // OpenCL v1.2 s6.9.a:
  7251. // A kernel function argument cannot be declared as a
  7252. // pointer to a pointer type.
  7253. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  7254. D.setInvalidType();
  7255. return;
  7256. case InvalidAddrSpacePtrKernelParam:
  7257. // OpenCL v1.0 s6.5:
  7258. // __kernel function arguments declared to be a pointer of a type can point
  7259. // to one of the following address spaces only : __global, __local or
  7260. // __constant.
  7261. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  7262. D.setInvalidType();
  7263. return;
  7264. // OpenCL v1.2 s6.9.k:
  7265. // Arguments to kernel functions in a program cannot be declared with the
  7266. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7267. // uintptr_t or a struct and/or union that contain fields declared to be
  7268. // one of these built-in scalar types.
  7269. case InvalidKernelParam:
  7270. // OpenCL v1.2 s6.8 n:
  7271. // A kernel function argument cannot be declared
  7272. // of event_t type.
  7273. // Do not diagnose half type since it is diagnosed as invalid argument
  7274. // type for any function elsewhere.
  7275. if (!PT->isHalfType()) {
  7276. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7277. // Explain what typedefs are involved.
  7278. const TypedefType *Typedef = nullptr;
  7279. while ((Typedef = PT->getAs<TypedefType>())) {
  7280. SourceLocation Loc = Typedef->getDecl()->getLocation();
  7281. // SourceLocation may be invalid for a built-in type.
  7282. if (Loc.isValid())
  7283. S.Diag(Loc, diag::note_entity_declared_at) << PT;
  7284. PT = Typedef->desugar();
  7285. }
  7286. }
  7287. D.setInvalidType();
  7288. return;
  7289. case PtrKernelParam:
  7290. case ValidKernelParam:
  7291. ValidTypes.insert(PT.getTypePtr());
  7292. return;
  7293. case RecordKernelParam:
  7294. break;
  7295. }
  7296. // Track nested structs we will inspect
  7297. SmallVector<const Decl *, 4> VisitStack;
  7298. // Track where we are in the nested structs. Items will migrate from
  7299. // VisitStack to HistoryStack as we do the DFS for bad field.
  7300. SmallVector<const FieldDecl *, 4> HistoryStack;
  7301. HistoryStack.push_back(nullptr);
  7302. // At this point we already handled everything except of a RecordType or
  7303. // an ArrayType of a RecordType.
  7304. assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
  7305. const RecordType *RecTy =
  7306. PT->getPointeeOrArrayElementType()->getAs<RecordType>();
  7307. const RecordDecl *OrigRecDecl = RecTy->getDecl();
  7308. VisitStack.push_back(RecTy->getDecl());
  7309. assert(VisitStack.back() && "First decl null?");
  7310. do {
  7311. const Decl *Next = VisitStack.pop_back_val();
  7312. if (!Next) {
  7313. assert(!HistoryStack.empty());
  7314. // Found a marker, we have gone up a level
  7315. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  7316. ValidTypes.insert(Hist->getType().getTypePtr());
  7317. continue;
  7318. }
  7319. // Adds everything except the original parameter declaration (which is not a
  7320. // field itself) to the history stack.
  7321. const RecordDecl *RD;
  7322. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  7323. HistoryStack.push_back(Field);
  7324. QualType FieldTy = Field->getType();
  7325. // Other field types (known to be valid or invalid) are handled while we
  7326. // walk around RecordDecl::fields().
  7327. assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
  7328. "Unexpected type.");
  7329. const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
  7330. RD = FieldRecTy->castAs<RecordType>()->getDecl();
  7331. } else {
  7332. RD = cast<RecordDecl>(Next);
  7333. }
  7334. // Add a null marker so we know when we've gone back up a level
  7335. VisitStack.push_back(nullptr);
  7336. for (const auto *FD : RD->fields()) {
  7337. QualType QT = FD->getType();
  7338. if (ValidTypes.count(QT.getTypePtr()))
  7339. continue;
  7340. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  7341. if (ParamType == ValidKernelParam)
  7342. continue;
  7343. if (ParamType == RecordKernelParam) {
  7344. VisitStack.push_back(FD);
  7345. continue;
  7346. }
  7347. // OpenCL v1.2 s6.9.p:
  7348. // Arguments to kernel functions that are declared to be a struct or union
  7349. // do not allow OpenCL objects to be passed as elements of the struct or
  7350. // union.
  7351. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  7352. ParamType == InvalidAddrSpacePtrKernelParam) {
  7353. S.Diag(Param->getLocation(),
  7354. diag::err_record_with_pointers_kernel_param)
  7355. << PT->isUnionType()
  7356. << PT;
  7357. } else {
  7358. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7359. }
  7360. S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
  7361. << OrigRecDecl->getDeclName();
  7362. // We have an error, now let's go back up through history and show where
  7363. // the offending field came from
  7364. for (ArrayRef<const FieldDecl *>::const_iterator
  7365. I = HistoryStack.begin() + 1,
  7366. E = HistoryStack.end();
  7367. I != E; ++I) {
  7368. const FieldDecl *OuterField = *I;
  7369. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  7370. << OuterField->getType();
  7371. }
  7372. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  7373. << QT->isPointerType()
  7374. << QT;
  7375. D.setInvalidType();
  7376. return;
  7377. }
  7378. } while (!VisitStack.empty());
  7379. }
  7380. /// Find the DeclContext in which a tag is implicitly declared if we see an
  7381. /// elaborated type specifier in the specified context, and lookup finds
  7382. /// nothing.
  7383. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  7384. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  7385. DC = DC->getParent();
  7386. return DC;
  7387. }
  7388. /// Find the Scope in which a tag is implicitly declared if we see an
  7389. /// elaborated type specifier in the specified context, and lookup finds
  7390. /// nothing.
  7391. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  7392. while (S->isClassScope() ||
  7393. (LangOpts.CPlusPlus &&
  7394. S->isFunctionPrototypeScope()) ||
  7395. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7396. (S->getEntity() && S->getEntity()->isTransparentContext()))
  7397. S = S->getParent();
  7398. return S;
  7399. }
  7400. NamedDecl*
  7401. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  7402. TypeSourceInfo *TInfo, LookupResult &Previous,
  7403. MultiTemplateParamsArg TemplateParamLists,
  7404. bool &AddToScope) {
  7405. QualType R = TInfo->getType();
  7406. assert(R->isFunctionType());
  7407. // TODO: consider using NameInfo for diagnostic.
  7408. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  7409. DeclarationName Name = NameInfo.getName();
  7410. StorageClass SC = getFunctionStorageClass(*this, D);
  7411. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  7412. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  7413. diag::err_invalid_thread)
  7414. << DeclSpec::getSpecifierName(TSCS);
  7415. if (D.isFirstDeclarationOfMember())
  7416. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  7417. D.getIdentifierLoc());
  7418. bool isFriend = false;
  7419. FunctionTemplateDecl *FunctionTemplate = nullptr;
  7420. bool isMemberSpecialization = false;
  7421. bool isFunctionTemplateSpecialization = false;
  7422. bool isDependentClassScopeExplicitSpecialization = false;
  7423. bool HasExplicitTemplateArgs = false;
  7424. TemplateArgumentListInfo TemplateArgs;
  7425. bool isVirtualOkay = false;
  7426. DeclContext *OriginalDC = DC;
  7427. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  7428. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  7429. isVirtualOkay);
  7430. if (!NewFD) return nullptr;
  7431. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  7432. NewFD->setTopLevelDeclInObjCContainer();
  7433. // Set the lexical context. If this is a function-scope declaration, or has a
  7434. // C++ scope specifier, or is the object of a friend declaration, the lexical
  7435. // context will be different from the semantic context.
  7436. NewFD->setLexicalDeclContext(CurContext);
  7437. if (IsLocalExternDecl)
  7438. NewFD->setLocalExternDecl();
  7439. if (getLangOpts().CPlusPlus) {
  7440. bool isInline = D.getDeclSpec().isInlineSpecified();
  7441. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7442. bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
  7443. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  7444. isFriend = D.getDeclSpec().isFriendSpecified();
  7445. if (isFriend && !isInline && D.isFunctionDefinition()) {
  7446. // C++ [class.friend]p5
  7447. // A function can be defined in a friend declaration of a
  7448. // class . . . . Such a function is implicitly inline.
  7449. NewFD->setImplicitlyInline();
  7450. }
  7451. // If this is a method defined in an __interface, and is not a constructor
  7452. // or an overloaded operator, then set the pure flag (isVirtual will already
  7453. // return true).
  7454. if (const CXXRecordDecl *Parent =
  7455. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  7456. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  7457. NewFD->setPure(true);
  7458. // C++ [class.union]p2
  7459. // A union can have member functions, but not virtual functions.
  7460. if (isVirtual && Parent->isUnion())
  7461. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  7462. }
  7463. SetNestedNameSpecifier(*this, NewFD, D);
  7464. isMemberSpecialization = false;
  7465. isFunctionTemplateSpecialization = false;
  7466. if (D.isInvalidType())
  7467. NewFD->setInvalidDecl();
  7468. // Match up the template parameter lists with the scope specifier, then
  7469. // determine whether we have a template or a template specialization.
  7470. bool Invalid = false;
  7471. if (TemplateParameterList *TemplateParams =
  7472. MatchTemplateParametersToScopeSpecifier(
  7473. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  7474. D.getCXXScopeSpec(),
  7475. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  7476. ? D.getName().TemplateId
  7477. : nullptr,
  7478. TemplateParamLists, isFriend, isMemberSpecialization,
  7479. Invalid)) {
  7480. if (TemplateParams->size() > 0) {
  7481. // This is a function template
  7482. // Check that we can declare a template here.
  7483. if (CheckTemplateDeclScope(S, TemplateParams))
  7484. NewFD->setInvalidDecl();
  7485. // A destructor cannot be a template.
  7486. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7487. Diag(NewFD->getLocation(), diag::err_destructor_template);
  7488. NewFD->setInvalidDecl();
  7489. }
  7490. // If we're adding a template to a dependent context, we may need to
  7491. // rebuilding some of the types used within the template parameter list,
  7492. // now that we know what the current instantiation is.
  7493. if (DC->isDependentContext()) {
  7494. ContextRAII SavedContext(*this, DC);
  7495. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  7496. Invalid = true;
  7497. }
  7498. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  7499. NewFD->getLocation(),
  7500. Name, TemplateParams,
  7501. NewFD);
  7502. FunctionTemplate->setLexicalDeclContext(CurContext);
  7503. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  7504. // For source fidelity, store the other template param lists.
  7505. if (TemplateParamLists.size() > 1) {
  7506. NewFD->setTemplateParameterListsInfo(Context,
  7507. TemplateParamLists.drop_back(1));
  7508. }
  7509. } else {
  7510. // This is a function template specialization.
  7511. isFunctionTemplateSpecialization = true;
  7512. // For source fidelity, store all the template param lists.
  7513. if (TemplateParamLists.size() > 0)
  7514. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7515. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  7516. if (isFriend) {
  7517. // We want to remove the "template<>", found here.
  7518. SourceRange RemoveRange = TemplateParams->getSourceRange();
  7519. // If we remove the template<> and the name is not a
  7520. // template-id, we're actually silently creating a problem:
  7521. // the friend declaration will refer to an untemplated decl,
  7522. // and clearly the user wants a template specialization. So
  7523. // we need to insert '<>' after the name.
  7524. SourceLocation InsertLoc;
  7525. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  7526. InsertLoc = D.getName().getSourceRange().getEnd();
  7527. InsertLoc = getLocForEndOfToken(InsertLoc);
  7528. }
  7529. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  7530. << Name << RemoveRange
  7531. << FixItHint::CreateRemoval(RemoveRange)
  7532. << FixItHint::CreateInsertion(InsertLoc, "<>");
  7533. }
  7534. }
  7535. } else {
  7536. // All template param lists were matched against the scope specifier:
  7537. // this is NOT (an explicit specialization of) a template.
  7538. if (TemplateParamLists.size() > 0)
  7539. // For source fidelity, store all the template param lists.
  7540. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7541. }
  7542. if (Invalid) {
  7543. NewFD->setInvalidDecl();
  7544. if (FunctionTemplate)
  7545. FunctionTemplate->setInvalidDecl();
  7546. }
  7547. // C++ [dcl.fct.spec]p5:
  7548. // The virtual specifier shall only be used in declarations of
  7549. // nonstatic class member functions that appear within a
  7550. // member-specification of a class declaration; see 10.3.
  7551. //
  7552. if (isVirtual && !NewFD->isInvalidDecl()) {
  7553. if (!isVirtualOkay) {
  7554. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7555. diag::err_virtual_non_function);
  7556. } else if (!CurContext->isRecord()) {
  7557. // 'virtual' was specified outside of the class.
  7558. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7559. diag::err_virtual_out_of_class)
  7560. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7561. } else if (NewFD->getDescribedFunctionTemplate()) {
  7562. // C++ [temp.mem]p3:
  7563. // A member function template shall not be virtual.
  7564. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7565. diag::err_virtual_member_function_template)
  7566. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7567. } else {
  7568. // Okay: Add virtual to the method.
  7569. NewFD->setVirtualAsWritten(true);
  7570. }
  7571. if (getLangOpts().CPlusPlus14 &&
  7572. NewFD->getReturnType()->isUndeducedType())
  7573. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  7574. }
  7575. if (getLangOpts().CPlusPlus14 &&
  7576. (NewFD->isDependentContext() ||
  7577. (isFriend && CurContext->isDependentContext())) &&
  7578. NewFD->getReturnType()->isUndeducedType()) {
  7579. // If the function template is referenced directly (for instance, as a
  7580. // member of the current instantiation), pretend it has a dependent type.
  7581. // This is not really justified by the standard, but is the only sane
  7582. // thing to do.
  7583. // FIXME: For a friend function, we have not marked the function as being
  7584. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  7585. const FunctionProtoType *FPT =
  7586. NewFD->getType()->castAs<FunctionProtoType>();
  7587. QualType Result =
  7588. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  7589. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  7590. FPT->getExtProtoInfo()));
  7591. }
  7592. // C++ [dcl.fct.spec]p3:
  7593. // The inline specifier shall not appear on a block scope function
  7594. // declaration.
  7595. if (isInline && !NewFD->isInvalidDecl()) {
  7596. if (CurContext->isFunctionOrMethod()) {
  7597. // 'inline' is not allowed on block scope function declaration.
  7598. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7599. diag::err_inline_declaration_block_scope) << Name
  7600. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7601. }
  7602. }
  7603. // C++ [dcl.fct.spec]p6:
  7604. // The explicit specifier shall be used only in the declaration of a
  7605. // constructor or conversion function within its class definition;
  7606. // see 12.3.1 and 12.3.2.
  7607. if (hasExplicit && !NewFD->isInvalidDecl() &&
  7608. !isa<CXXDeductionGuideDecl>(NewFD)) {
  7609. if (!CurContext->isRecord()) {
  7610. // 'explicit' was specified outside of the class.
  7611. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7612. diag::err_explicit_out_of_class)
  7613. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  7614. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  7615. !isa<CXXConversionDecl>(NewFD)) {
  7616. // 'explicit' was specified on a function that wasn't a constructor
  7617. // or conversion function.
  7618. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7619. diag::err_explicit_non_ctor_or_conv_function)
  7620. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  7621. }
  7622. }
  7623. if (isConstexpr) {
  7624. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  7625. // are implicitly inline.
  7626. NewFD->setImplicitlyInline();
  7627. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  7628. // be either constructors or to return a literal type. Therefore,
  7629. // destructors cannot be declared constexpr.
  7630. if (isa<CXXDestructorDecl>(NewFD))
  7631. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  7632. }
  7633. // If __module_private__ was specified, mark the function accordingly.
  7634. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7635. if (isFunctionTemplateSpecialization) {
  7636. SourceLocation ModulePrivateLoc
  7637. = D.getDeclSpec().getModulePrivateSpecLoc();
  7638. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  7639. << 0
  7640. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7641. } else {
  7642. NewFD->setModulePrivate();
  7643. if (FunctionTemplate)
  7644. FunctionTemplate->setModulePrivate();
  7645. }
  7646. }
  7647. if (isFriend) {
  7648. if (FunctionTemplate) {
  7649. FunctionTemplate->setObjectOfFriendDecl();
  7650. FunctionTemplate->setAccess(AS_public);
  7651. }
  7652. NewFD->setObjectOfFriendDecl();
  7653. NewFD->setAccess(AS_public);
  7654. }
  7655. // If a function is defined as defaulted or deleted, mark it as such now.
  7656. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  7657. // definition kind to FDK_Definition.
  7658. switch (D.getFunctionDefinitionKind()) {
  7659. case FDK_Declaration:
  7660. case FDK_Definition:
  7661. break;
  7662. case FDK_Defaulted:
  7663. NewFD->setDefaulted();
  7664. break;
  7665. case FDK_Deleted:
  7666. NewFD->setDeletedAsWritten();
  7667. break;
  7668. }
  7669. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  7670. D.isFunctionDefinition()) {
  7671. // C++ [class.mfct]p2:
  7672. // A member function may be defined (8.4) in its class definition, in
  7673. // which case it is an inline member function (7.1.2)
  7674. NewFD->setImplicitlyInline();
  7675. }
  7676. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  7677. !CurContext->isRecord()) {
  7678. // C++ [class.static]p1:
  7679. // A data or function member of a class may be declared static
  7680. // in a class definition, in which case it is a static member of
  7681. // the class.
  7682. // Complain about the 'static' specifier if it's on an out-of-line
  7683. // member function definition.
  7684. // MSVC permits the use of a 'static' storage specifier on an out-of-line
  7685. // member function template declaration and class member template
  7686. // declaration (MSVC versions before 2015), warn about this.
  7687. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7688. ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  7689. cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
  7690. (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
  7691. ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
  7692. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7693. }
  7694. // C++11 [except.spec]p15:
  7695. // A deallocation function with no exception-specification is treated
  7696. // as if it were specified with noexcept(true).
  7697. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  7698. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  7699. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  7700. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  7701. NewFD->setType(Context.getFunctionType(
  7702. FPT->getReturnType(), FPT->getParamTypes(),
  7703. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  7704. }
  7705. // Filter out previous declarations that don't match the scope.
  7706. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  7707. D.getCXXScopeSpec().isNotEmpty() ||
  7708. isMemberSpecialization ||
  7709. isFunctionTemplateSpecialization);
  7710. // Handle GNU asm-label extension (encoded as an attribute).
  7711. if (Expr *E = (Expr*) D.getAsmLabel()) {
  7712. // The parser guarantees this is a string.
  7713. StringLiteral *SE = cast<StringLiteral>(E);
  7714. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  7715. SE->getString(), 0));
  7716. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7717. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7718. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  7719. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7720. if (isDeclExternC(NewFD)) {
  7721. NewFD->addAttr(I->second);
  7722. ExtnameUndeclaredIdentifiers.erase(I);
  7723. } else
  7724. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  7725. << /*Variable*/0 << NewFD;
  7726. }
  7727. }
  7728. // Copy the parameter declarations from the declarator D to the function
  7729. // declaration NewFD, if they are available. First scavenge them into Params.
  7730. SmallVector<ParmVarDecl*, 16> Params;
  7731. unsigned FTIIdx;
  7732. if (D.isFunctionDeclarator(FTIIdx)) {
  7733. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  7734. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  7735. // function that takes no arguments, not a function that takes a
  7736. // single void argument.
  7737. // We let through "const void" here because Sema::GetTypeForDeclarator
  7738. // already checks for that case.
  7739. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  7740. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  7741. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  7742. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  7743. Param->setDeclContext(NewFD);
  7744. Params.push_back(Param);
  7745. if (Param->isInvalidDecl())
  7746. NewFD->setInvalidDecl();
  7747. }
  7748. }
  7749. if (!getLangOpts().CPlusPlus) {
  7750. // In C, find all the tag declarations from the prototype and move them
  7751. // into the function DeclContext. Remove them from the surrounding tag
  7752. // injection context of the function, which is typically but not always
  7753. // the TU.
  7754. DeclContext *PrototypeTagContext =
  7755. getTagInjectionContext(NewFD->getLexicalDeclContext());
  7756. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  7757. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  7758. // We don't want to reparent enumerators. Look at their parent enum
  7759. // instead.
  7760. if (!TD) {
  7761. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  7762. TD = cast<EnumDecl>(ECD->getDeclContext());
  7763. }
  7764. if (!TD)
  7765. continue;
  7766. DeclContext *TagDC = TD->getLexicalDeclContext();
  7767. if (!TagDC->containsDecl(TD))
  7768. continue;
  7769. TagDC->removeDecl(TD);
  7770. TD->setDeclContext(NewFD);
  7771. NewFD->addDecl(TD);
  7772. // Preserve the lexical DeclContext if it is not the surrounding tag
  7773. // injection context of the FD. In this example, the semantic context of
  7774. // E will be f and the lexical context will be S, while both the
  7775. // semantic and lexical contexts of S will be f:
  7776. // void f(struct S { enum E { a } f; } s);
  7777. if (TagDC != PrototypeTagContext)
  7778. TD->setLexicalDeclContext(TagDC);
  7779. }
  7780. }
  7781. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  7782. // When we're declaring a function with a typedef, typeof, etc as in the
  7783. // following example, we'll need to synthesize (unnamed)
  7784. // parameters for use in the declaration.
  7785. //
  7786. // @code
  7787. // typedef void fn(int);
  7788. // fn f;
  7789. // @endcode
  7790. // Synthesize a parameter for each argument type.
  7791. for (const auto &AI : FT->param_types()) {
  7792. ParmVarDecl *Param =
  7793. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  7794. Param->setScopeInfo(0, Params.size());
  7795. Params.push_back(Param);
  7796. }
  7797. } else {
  7798. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  7799. "Should not need args for typedef of non-prototype fn");
  7800. }
  7801. // Finally, we know we have the right number of parameters, install them.
  7802. NewFD->setParams(Params);
  7803. if (D.getDeclSpec().isNoreturnSpecified())
  7804. NewFD->addAttr(
  7805. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  7806. Context, 0));
  7807. // Functions returning a variably modified type violate C99 6.7.5.2p2
  7808. // because all functions have linkage.
  7809. if (!NewFD->isInvalidDecl() &&
  7810. NewFD->getReturnType()->isVariablyModifiedType()) {
  7811. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  7812. NewFD->setInvalidDecl();
  7813. }
  7814. // Apply an implicit SectionAttr if '#pragma clang section text' is active
  7815. if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
  7816. !NewFD->hasAttr<SectionAttr>()) {
  7817. NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
  7818. PragmaClangTextSection.SectionName,
  7819. PragmaClangTextSection.PragmaLocation));
  7820. }
  7821. // Apply an implicit SectionAttr if #pragma code_seg is active.
  7822. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  7823. !NewFD->hasAttr<SectionAttr>()) {
  7824. NewFD->addAttr(
  7825. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  7826. CodeSegStack.CurrentValue->getString(),
  7827. CodeSegStack.CurrentPragmaLocation));
  7828. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  7829. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  7830. ASTContext::PSF_Read,
  7831. NewFD))
  7832. NewFD->dropAttr<SectionAttr>();
  7833. }
  7834. // Apply an implicit CodeSegAttr from class declspec or
  7835. // apply an implicit SectionAttr from #pragma code_seg if active.
  7836. if (!NewFD->hasAttr<CodeSegAttr>()) {
  7837. if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
  7838. D.isFunctionDefinition())) {
  7839. NewFD->addAttr(SAttr);
  7840. }
  7841. }
  7842. // Handle attributes.
  7843. ProcessDeclAttributes(S, NewFD, D);
  7844. if (getLangOpts().OpenCL) {
  7845. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  7846. // type declaration will generate a compilation error.
  7847. LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
  7848. if (AddressSpace != LangAS::Default) {
  7849. Diag(NewFD->getLocation(),
  7850. diag::err_opencl_return_value_with_address_space);
  7851. NewFD->setInvalidDecl();
  7852. }
  7853. }
  7854. if (!getLangOpts().CPlusPlus) {
  7855. // Perform semantic checking on the function declaration.
  7856. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7857. CheckMain(NewFD, D.getDeclSpec());
  7858. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7859. CheckMSVCRTEntryPoint(NewFD);
  7860. if (!NewFD->isInvalidDecl())
  7861. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7862. isMemberSpecialization));
  7863. else if (!Previous.empty())
  7864. // Recover gracefully from an invalid redeclaration.
  7865. D.setRedeclaration(true);
  7866. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7867. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7868. "previous declaration set still overloaded");
  7869. // Diagnose no-prototype function declarations with calling conventions that
  7870. // don't support variadic calls. Only do this in C and do it after merging
  7871. // possibly prototyped redeclarations.
  7872. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  7873. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  7874. CallingConv CC = FT->getExtInfo().getCC();
  7875. if (!supportsVariadicCall(CC)) {
  7876. // Windows system headers sometimes accidentally use stdcall without
  7877. // (void) parameters, so we relax this to a warning.
  7878. int DiagID =
  7879. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  7880. Diag(NewFD->getLocation(), DiagID)
  7881. << FunctionType::getNameForCallConv(CC);
  7882. }
  7883. }
  7884. } else {
  7885. // C++11 [replacement.functions]p3:
  7886. // The program's definitions shall not be specified as inline.
  7887. //
  7888. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  7889. //
  7890. // Suppress the diagnostic if the function is __attribute__((used)), since
  7891. // that forces an external definition to be emitted.
  7892. if (D.getDeclSpec().isInlineSpecified() &&
  7893. NewFD->isReplaceableGlobalAllocationFunction() &&
  7894. !NewFD->hasAttr<UsedAttr>())
  7895. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7896. diag::ext_operator_new_delete_declared_inline)
  7897. << NewFD->getDeclName();
  7898. // If the declarator is a template-id, translate the parser's template
  7899. // argument list into our AST format.
  7900. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  7901. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  7902. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  7903. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  7904. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  7905. TemplateId->NumArgs);
  7906. translateTemplateArguments(TemplateArgsPtr,
  7907. TemplateArgs);
  7908. HasExplicitTemplateArgs = true;
  7909. if (NewFD->isInvalidDecl()) {
  7910. HasExplicitTemplateArgs = false;
  7911. } else if (FunctionTemplate) {
  7912. // Function template with explicit template arguments.
  7913. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  7914. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  7915. HasExplicitTemplateArgs = false;
  7916. } else {
  7917. assert((isFunctionTemplateSpecialization ||
  7918. D.getDeclSpec().isFriendSpecified()) &&
  7919. "should have a 'template<>' for this decl");
  7920. // "friend void foo<>(int);" is an implicit specialization decl.
  7921. isFunctionTemplateSpecialization = true;
  7922. }
  7923. } else if (isFriend && isFunctionTemplateSpecialization) {
  7924. // This combination is only possible in a recovery case; the user
  7925. // wrote something like:
  7926. // template <> friend void foo(int);
  7927. // which we're recovering from as if the user had written:
  7928. // friend void foo<>(int);
  7929. // Go ahead and fake up a template id.
  7930. HasExplicitTemplateArgs = true;
  7931. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  7932. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  7933. }
  7934. // We do not add HD attributes to specializations here because
  7935. // they may have different constexpr-ness compared to their
  7936. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  7937. // may end up with different effective targets. Instead, a
  7938. // specialization inherits its target attributes from its template
  7939. // in the CheckFunctionTemplateSpecialization() call below.
  7940. if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
  7941. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  7942. // If it's a friend (and only if it's a friend), it's possible
  7943. // that either the specialized function type or the specialized
  7944. // template is dependent, and therefore matching will fail. In
  7945. // this case, don't check the specialization yet.
  7946. bool InstantiationDependent = false;
  7947. if (isFunctionTemplateSpecialization && isFriend &&
  7948. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  7949. TemplateSpecializationType::anyDependentTemplateArguments(
  7950. TemplateArgs,
  7951. InstantiationDependent))) {
  7952. assert(HasExplicitTemplateArgs &&
  7953. "friend function specialization without template args");
  7954. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  7955. Previous))
  7956. NewFD->setInvalidDecl();
  7957. } else if (isFunctionTemplateSpecialization) {
  7958. if (CurContext->isDependentContext() && CurContext->isRecord()
  7959. && !isFriend) {
  7960. isDependentClassScopeExplicitSpecialization = true;
  7961. } else if (!NewFD->isInvalidDecl() &&
  7962. CheckFunctionTemplateSpecialization(
  7963. NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
  7964. Previous))
  7965. NewFD->setInvalidDecl();
  7966. // C++ [dcl.stc]p1:
  7967. // A storage-class-specifier shall not be specified in an explicit
  7968. // specialization (14.7.3)
  7969. FunctionTemplateSpecializationInfo *Info =
  7970. NewFD->getTemplateSpecializationInfo();
  7971. if (Info && SC != SC_None) {
  7972. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  7973. Diag(NewFD->getLocation(),
  7974. diag::err_explicit_specialization_inconsistent_storage_class)
  7975. << SC
  7976. << FixItHint::CreateRemoval(
  7977. D.getDeclSpec().getStorageClassSpecLoc());
  7978. else
  7979. Diag(NewFD->getLocation(),
  7980. diag::ext_explicit_specialization_storage_class)
  7981. << FixItHint::CreateRemoval(
  7982. D.getDeclSpec().getStorageClassSpecLoc());
  7983. }
  7984. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  7985. if (CheckMemberSpecialization(NewFD, Previous))
  7986. NewFD->setInvalidDecl();
  7987. }
  7988. // Perform semantic checking on the function declaration.
  7989. if (!isDependentClassScopeExplicitSpecialization) {
  7990. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7991. CheckMain(NewFD, D.getDeclSpec());
  7992. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7993. CheckMSVCRTEntryPoint(NewFD);
  7994. if (!NewFD->isInvalidDecl())
  7995. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7996. isMemberSpecialization));
  7997. else if (!Previous.empty())
  7998. // Recover gracefully from an invalid redeclaration.
  7999. D.setRedeclaration(true);
  8000. }
  8001. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  8002. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  8003. "previous declaration set still overloaded");
  8004. NamedDecl *PrincipalDecl = (FunctionTemplate
  8005. ? cast<NamedDecl>(FunctionTemplate)
  8006. : NewFD);
  8007. if (isFriend && NewFD->getPreviousDecl()) {
  8008. AccessSpecifier Access = AS_public;
  8009. if (!NewFD->isInvalidDecl())
  8010. Access = NewFD->getPreviousDecl()->getAccess();
  8011. NewFD->setAccess(Access);
  8012. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  8013. }
  8014. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  8015. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  8016. PrincipalDecl->setNonMemberOperator();
  8017. // If we have a function template, check the template parameter
  8018. // list. This will check and merge default template arguments.
  8019. if (FunctionTemplate) {
  8020. FunctionTemplateDecl *PrevTemplate =
  8021. FunctionTemplate->getPreviousDecl();
  8022. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  8023. PrevTemplate ? PrevTemplate->getTemplateParameters()
  8024. : nullptr,
  8025. D.getDeclSpec().isFriendSpecified()
  8026. ? (D.isFunctionDefinition()
  8027. ? TPC_FriendFunctionTemplateDefinition
  8028. : TPC_FriendFunctionTemplate)
  8029. : (D.getCXXScopeSpec().isSet() &&
  8030. DC && DC->isRecord() &&
  8031. DC->isDependentContext())
  8032. ? TPC_ClassTemplateMember
  8033. : TPC_FunctionTemplate);
  8034. }
  8035. if (NewFD->isInvalidDecl()) {
  8036. // Ignore all the rest of this.
  8037. } else if (!D.isRedeclaration()) {
  8038. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  8039. AddToScope };
  8040. // Fake up an access specifier if it's supposed to be a class member.
  8041. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  8042. NewFD->setAccess(AS_public);
  8043. // Qualified decls generally require a previous declaration.
  8044. if (D.getCXXScopeSpec().isSet()) {
  8045. // ...with the major exception of templated-scope or
  8046. // dependent-scope friend declarations.
  8047. // TODO: we currently also suppress this check in dependent
  8048. // contexts because (1) the parameter depth will be off when
  8049. // matching friend templates and (2) we might actually be
  8050. // selecting a friend based on a dependent factor. But there
  8051. // are situations where these conditions don't apply and we
  8052. // can actually do this check immediately.
  8053. //
  8054. // Unless the scope is dependent, it's always an error if qualified
  8055. // redeclaration lookup found nothing at all. Diagnose that now;
  8056. // nothing will diagnose that error later.
  8057. if (isFriend &&
  8058. (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  8059. (!Previous.empty() && CurContext->isDependentContext()))) {
  8060. // ignore these
  8061. } else {
  8062. // The user tried to provide an out-of-line definition for a
  8063. // function that is a member of a class or namespace, but there
  8064. // was no such member function declared (C++ [class.mfct]p2,
  8065. // C++ [namespace.memdef]p2). For example:
  8066. //
  8067. // class X {
  8068. // void f() const;
  8069. // };
  8070. //
  8071. // void X::f() { } // ill-formed
  8072. //
  8073. // Complain about this problem, and attempt to suggest close
  8074. // matches (e.g., those that differ only in cv-qualifiers and
  8075. // whether the parameter types are references).
  8076. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8077. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  8078. AddToScope = ExtraArgs.AddToScope;
  8079. return Result;
  8080. }
  8081. }
  8082. // Unqualified local friend declarations are required to resolve
  8083. // to something.
  8084. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  8085. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8086. *this, Previous, NewFD, ExtraArgs, true, S)) {
  8087. AddToScope = ExtraArgs.AddToScope;
  8088. return Result;
  8089. }
  8090. }
  8091. } else if (!D.isFunctionDefinition() &&
  8092. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  8093. !isFriend && !isFunctionTemplateSpecialization &&
  8094. !isMemberSpecialization) {
  8095. // An out-of-line member function declaration must also be a
  8096. // definition (C++ [class.mfct]p2).
  8097. // Note that this is not the case for explicit specializations of
  8098. // function templates or member functions of class templates, per
  8099. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  8100. // extension for compatibility with old SWIG code which likes to
  8101. // generate them.
  8102. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  8103. << D.getCXXScopeSpec().getRange();
  8104. }
  8105. }
  8106. ProcessPragmaWeak(S, NewFD);
  8107. checkAttributesAfterMerging(*this, *NewFD);
  8108. AddKnownFunctionAttributes(NewFD);
  8109. if (NewFD->hasAttr<OverloadableAttr>() &&
  8110. !NewFD->getType()->getAs<FunctionProtoType>()) {
  8111. Diag(NewFD->getLocation(),
  8112. diag::err_attribute_overloadable_no_prototype)
  8113. << NewFD;
  8114. // Turn this into a variadic function with no parameters.
  8115. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  8116. FunctionProtoType::ExtProtoInfo EPI(
  8117. Context.getDefaultCallingConvention(true, false));
  8118. EPI.Variadic = true;
  8119. EPI.ExtInfo = FT->getExtInfo();
  8120. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  8121. NewFD->setType(R);
  8122. }
  8123. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8124. // member, set the visibility of this function.
  8125. if (!DC->isRecord() && NewFD->isExternallyVisible())
  8126. AddPushedVisibilityAttribute(NewFD);
  8127. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  8128. // marking the function.
  8129. AddCFAuditedAttribute(NewFD);
  8130. // If this is a function definition, check if we have to apply optnone due to
  8131. // a pragma.
  8132. if(D.isFunctionDefinition())
  8133. AddRangeBasedOptnone(NewFD);
  8134. // If this is the first declaration of an extern C variable, update
  8135. // the map of such variables.
  8136. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  8137. isIncompleteDeclExternC(*this, NewFD))
  8138. RegisterLocallyScopedExternCDecl(NewFD, S);
  8139. // Set this FunctionDecl's range up to the right paren.
  8140. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  8141. if (D.isRedeclaration() && !Previous.empty()) {
  8142. NamedDecl *Prev = Previous.getRepresentativeDecl();
  8143. checkDLLAttributeRedeclaration(*this, Prev, NewFD,
  8144. isMemberSpecialization ||
  8145. isFunctionTemplateSpecialization,
  8146. D.isFunctionDefinition());
  8147. }
  8148. if (getLangOpts().CUDA) {
  8149. IdentifierInfo *II = NewFD->getIdentifier();
  8150. if (II && II->isStr(getCudaConfigureFuncName()) &&
  8151. !NewFD->isInvalidDecl() &&
  8152. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  8153. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  8154. Diag(NewFD->getLocation(), diag::err_config_scalar_return)
  8155. << getCudaConfigureFuncName();
  8156. Context.setcudaConfigureCallDecl(NewFD);
  8157. }
  8158. // Variadic functions, other than a *declaration* of printf, are not allowed
  8159. // in device-side CUDA code, unless someone passed
  8160. // -fcuda-allow-variadic-functions.
  8161. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  8162. (NewFD->hasAttr<CUDADeviceAttr>() ||
  8163. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  8164. !(II && II->isStr("printf") && NewFD->isExternC() &&
  8165. !D.isFunctionDefinition())) {
  8166. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  8167. }
  8168. }
  8169. MarkUnusedFileScopedDecl(NewFD);
  8170. if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
  8171. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  8172. if ((getLangOpts().OpenCLVersion >= 120)
  8173. && (SC == SC_Static)) {
  8174. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  8175. D.setInvalidType();
  8176. }
  8177. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  8178. if (!NewFD->getReturnType()->isVoidType()) {
  8179. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  8180. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  8181. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  8182. : FixItHint());
  8183. D.setInvalidType();
  8184. }
  8185. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  8186. for (auto Param : NewFD->parameters())
  8187. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  8188. if (getLangOpts().OpenCLCPlusPlus) {
  8189. if (DC->isRecord()) {
  8190. Diag(D.getIdentifierLoc(), diag::err_method_kernel);
  8191. D.setInvalidType();
  8192. }
  8193. if (FunctionTemplate) {
  8194. Diag(D.getIdentifierLoc(), diag::err_template_kernel);
  8195. D.setInvalidType();
  8196. }
  8197. }
  8198. }
  8199. if (getLangOpts().CPlusPlus) {
  8200. if (FunctionTemplate) {
  8201. if (NewFD->isInvalidDecl())
  8202. FunctionTemplate->setInvalidDecl();
  8203. return FunctionTemplate;
  8204. }
  8205. if (isMemberSpecialization && !NewFD->isInvalidDecl())
  8206. CompleteMemberSpecialization(NewFD, Previous);
  8207. }
  8208. for (const ParmVarDecl *Param : NewFD->parameters()) {
  8209. QualType PT = Param->getType();
  8210. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  8211. // types.
  8212. if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
  8213. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  8214. QualType ElemTy = PipeTy->getElementType();
  8215. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  8216. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  8217. D.setInvalidType();
  8218. }
  8219. }
  8220. }
  8221. }
  8222. // Here we have an function template explicit specialization at class scope.
  8223. // The actual specialization will be postponed to template instatiation
  8224. // time via the ClassScopeFunctionSpecializationDecl node.
  8225. if (isDependentClassScopeExplicitSpecialization) {
  8226. ClassScopeFunctionSpecializationDecl *NewSpec =
  8227. ClassScopeFunctionSpecializationDecl::Create(
  8228. Context, CurContext, NewFD->getLocation(),
  8229. cast<CXXMethodDecl>(NewFD),
  8230. HasExplicitTemplateArgs, TemplateArgs);
  8231. CurContext->addDecl(NewSpec);
  8232. AddToScope = false;
  8233. }
  8234. // Diagnose availability attributes. Availability cannot be used on functions
  8235. // that are run during load/unload.
  8236. if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
  8237. if (NewFD->hasAttr<ConstructorAttr>()) {
  8238. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8239. << 1;
  8240. NewFD->dropAttr<AvailabilityAttr>();
  8241. }
  8242. if (NewFD->hasAttr<DestructorAttr>()) {
  8243. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8244. << 2;
  8245. NewFD->dropAttr<AvailabilityAttr>();
  8246. }
  8247. }
  8248. return NewFD;
  8249. }
  8250. /// Return a CodeSegAttr from a containing class. The Microsoft docs say
  8251. /// when __declspec(code_seg) "is applied to a class, all member functions of
  8252. /// the class and nested classes -- this includes compiler-generated special
  8253. /// member functions -- are put in the specified segment."
  8254. /// The actual behavior is a little more complicated. The Microsoft compiler
  8255. /// won't check outer classes if there is an active value from #pragma code_seg.
  8256. /// The CodeSeg is always applied from the direct parent but only from outer
  8257. /// classes when the #pragma code_seg stack is empty. See:
  8258. /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
  8259. /// available since MS has removed the page.
  8260. static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
  8261. const auto *Method = dyn_cast<CXXMethodDecl>(FD);
  8262. if (!Method)
  8263. return nullptr;
  8264. const CXXRecordDecl *Parent = Method->getParent();
  8265. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8266. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8267. NewAttr->setImplicit(true);
  8268. return NewAttr;
  8269. }
  8270. // The Microsoft compiler won't check outer classes for the CodeSeg
  8271. // when the #pragma code_seg stack is active.
  8272. if (S.CodeSegStack.CurrentValue)
  8273. return nullptr;
  8274. while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
  8275. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8276. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8277. NewAttr->setImplicit(true);
  8278. return NewAttr;
  8279. }
  8280. }
  8281. return nullptr;
  8282. }
  8283. /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
  8284. /// containing class. Otherwise it will return implicit SectionAttr if the
  8285. /// function is a definition and there is an active value on CodeSegStack
  8286. /// (from the current #pragma code-seg value).
  8287. ///
  8288. /// \param FD Function being declared.
  8289. /// \param IsDefinition Whether it is a definition or just a declarartion.
  8290. /// \returns A CodeSegAttr or SectionAttr to apply to the function or
  8291. /// nullptr if no attribute should be added.
  8292. Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
  8293. bool IsDefinition) {
  8294. if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
  8295. return A;
  8296. if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
  8297. CodeSegStack.CurrentValue) {
  8298. return SectionAttr::CreateImplicit(getASTContext(),
  8299. SectionAttr::Declspec_allocate,
  8300. CodeSegStack.CurrentValue->getString(),
  8301. CodeSegStack.CurrentPragmaLocation);
  8302. }
  8303. return nullptr;
  8304. }
  8305. /// Determines if we can perform a correct type check for \p D as a
  8306. /// redeclaration of \p PrevDecl. If not, we can generally still perform a
  8307. /// best-effort check.
  8308. ///
  8309. /// \param NewD The new declaration.
  8310. /// \param OldD The old declaration.
  8311. /// \param NewT The portion of the type of the new declaration to check.
  8312. /// \param OldT The portion of the type of the old declaration to check.
  8313. bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
  8314. QualType NewT, QualType OldT) {
  8315. if (!NewD->getLexicalDeclContext()->isDependentContext())
  8316. return true;
  8317. // For dependently-typed local extern declarations and friends, we can't
  8318. // perform a correct type check in general until instantiation:
  8319. //
  8320. // int f();
  8321. // template<typename T> void g() { T f(); }
  8322. //
  8323. // (valid if g() is only instantiated with T = int).
  8324. if (NewT->isDependentType() &&
  8325. (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
  8326. return false;
  8327. // Similarly, if the previous declaration was a dependent local extern
  8328. // declaration, we don't really know its type yet.
  8329. if (OldT->isDependentType() && OldD->isLocalExternDecl())
  8330. return false;
  8331. return true;
  8332. }
  8333. /// Checks if the new declaration declared in dependent context must be
  8334. /// put in the same redeclaration chain as the specified declaration.
  8335. ///
  8336. /// \param D Declaration that is checked.
  8337. /// \param PrevDecl Previous declaration found with proper lookup method for the
  8338. /// same declaration name.
  8339. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  8340. /// belongs to.
  8341. ///
  8342. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  8343. if (!D->getLexicalDeclContext()->isDependentContext())
  8344. return true;
  8345. // Don't chain dependent friend function definitions until instantiation, to
  8346. // permit cases like
  8347. //
  8348. // void func();
  8349. // template<typename T> class C1 { friend void func() {} };
  8350. // template<typename T> class C2 { friend void func() {} };
  8351. //
  8352. // ... which is valid if only one of C1 and C2 is ever instantiated.
  8353. //
  8354. // FIXME: This need only apply to function definitions. For now, we proxy
  8355. // this by checking for a file-scope function. We do not want this to apply
  8356. // to friend declarations nominating member functions, because that gets in
  8357. // the way of access checks.
  8358. if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
  8359. return false;
  8360. auto *VD = dyn_cast<ValueDecl>(D);
  8361. auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
  8362. return !VD || !PrevVD ||
  8363. canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
  8364. PrevVD->getType());
  8365. }
  8366. /// Check the target attribute of the function for MultiVersion
  8367. /// validity.
  8368. ///
  8369. /// Returns true if there was an error, false otherwise.
  8370. static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
  8371. const auto *TA = FD->getAttr<TargetAttr>();
  8372. assert(TA && "MultiVersion Candidate requires a target attribute");
  8373. TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
  8374. const TargetInfo &TargetInfo = S.Context.getTargetInfo();
  8375. enum ErrType { Feature = 0, Architecture = 1 };
  8376. if (!ParseInfo.Architecture.empty() &&
  8377. !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
  8378. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8379. << Architecture << ParseInfo.Architecture;
  8380. return true;
  8381. }
  8382. for (const auto &Feat : ParseInfo.Features) {
  8383. auto BareFeat = StringRef{Feat}.substr(1);
  8384. if (Feat[0] == '-') {
  8385. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8386. << Feature << ("no-" + BareFeat).str();
  8387. return true;
  8388. }
  8389. if (!TargetInfo.validateCpuSupports(BareFeat) ||
  8390. !TargetInfo.isValidFeatureName(BareFeat)) {
  8391. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8392. << Feature << BareFeat;
  8393. return true;
  8394. }
  8395. }
  8396. return false;
  8397. }
  8398. static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
  8399. MultiVersionKind MVType) {
  8400. for (const Attr *A : FD->attrs()) {
  8401. switch (A->getKind()) {
  8402. case attr::CPUDispatch:
  8403. case attr::CPUSpecific:
  8404. if (MVType != MultiVersionKind::CPUDispatch &&
  8405. MVType != MultiVersionKind::CPUSpecific)
  8406. return true;
  8407. break;
  8408. case attr::Target:
  8409. if (MVType != MultiVersionKind::Target)
  8410. return true;
  8411. break;
  8412. default:
  8413. return true;
  8414. }
  8415. }
  8416. return false;
  8417. }
  8418. static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
  8419. const FunctionDecl *NewFD,
  8420. bool CausesMV,
  8421. MultiVersionKind MVType) {
  8422. enum DoesntSupport {
  8423. FuncTemplates = 0,
  8424. VirtFuncs = 1,
  8425. DeducedReturn = 2,
  8426. Constructors = 3,
  8427. Destructors = 4,
  8428. DeletedFuncs = 5,
  8429. DefaultedFuncs = 6,
  8430. ConstexprFuncs = 7,
  8431. };
  8432. enum Different {
  8433. CallingConv = 0,
  8434. ReturnType = 1,
  8435. ConstexprSpec = 2,
  8436. InlineSpec = 3,
  8437. StorageClass = 4,
  8438. Linkage = 5
  8439. };
  8440. bool IsCPUSpecificCPUDispatchMVType =
  8441. MVType == MultiVersionKind::CPUDispatch ||
  8442. MVType == MultiVersionKind::CPUSpecific;
  8443. if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
  8444. S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
  8445. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8446. return true;
  8447. }
  8448. if (!NewFD->getType()->getAs<FunctionProtoType>())
  8449. return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
  8450. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8451. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8452. if (OldFD)
  8453. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8454. return true;
  8455. }
  8456. // For now, disallow all other attributes. These should be opt-in, but
  8457. // an analysis of all of them is a future FIXME.
  8458. if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
  8459. S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8460. << IsCPUSpecificCPUDispatchMVType;
  8461. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8462. return true;
  8463. }
  8464. if (HasNonMultiVersionAttributes(NewFD, MVType))
  8465. return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8466. << IsCPUSpecificCPUDispatchMVType;
  8467. if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  8468. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8469. << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
  8470. if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
  8471. if (NewCXXFD->isVirtual())
  8472. return S.Diag(NewCXXFD->getLocation(),
  8473. diag::err_multiversion_doesnt_support)
  8474. << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
  8475. if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
  8476. return S.Diag(NewCXXCtor->getLocation(),
  8477. diag::err_multiversion_doesnt_support)
  8478. << IsCPUSpecificCPUDispatchMVType << Constructors;
  8479. if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
  8480. return S.Diag(NewCXXDtor->getLocation(),
  8481. diag::err_multiversion_doesnt_support)
  8482. << IsCPUSpecificCPUDispatchMVType << Destructors;
  8483. }
  8484. if (NewFD->isDeleted())
  8485. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8486. << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
  8487. if (NewFD->isDefaulted())
  8488. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8489. << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
  8490. if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
  8491. MVType == MultiVersionKind::CPUSpecific))
  8492. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8493. << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
  8494. QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
  8495. const auto *NewType = cast<FunctionType>(NewQType);
  8496. QualType NewReturnType = NewType->getReturnType();
  8497. if (NewReturnType->isUndeducedType())
  8498. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8499. << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
  8500. // Only allow transition to MultiVersion if it hasn't been used.
  8501. if (OldFD && CausesMV && OldFD->isUsed(false))
  8502. return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
  8503. // Ensure the return type is identical.
  8504. if (OldFD) {
  8505. QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
  8506. const auto *OldType = cast<FunctionType>(OldQType);
  8507. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  8508. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  8509. if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
  8510. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8511. << CallingConv;
  8512. QualType OldReturnType = OldType->getReturnType();
  8513. if (OldReturnType != NewReturnType)
  8514. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8515. << ReturnType;
  8516. if (OldFD->isConstexpr() != NewFD->isConstexpr())
  8517. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8518. << ConstexprSpec;
  8519. if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
  8520. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8521. << InlineSpec;
  8522. if (OldFD->getStorageClass() != NewFD->getStorageClass())
  8523. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8524. << StorageClass;
  8525. if (OldFD->isExternC() != NewFD->isExternC())
  8526. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8527. << Linkage;
  8528. if (S.CheckEquivalentExceptionSpec(
  8529. OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
  8530. NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
  8531. return true;
  8532. }
  8533. return false;
  8534. }
  8535. /// Check the validity of a multiversion function declaration that is the
  8536. /// first of its kind. Also sets the multiversion'ness' of the function itself.
  8537. ///
  8538. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8539. ///
  8540. /// Returns true if there was an error, false otherwise.
  8541. static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
  8542. MultiVersionKind MVType,
  8543. const TargetAttr *TA) {
  8544. assert(MVType != MultiVersionKind::None &&
  8545. "Function lacks multiversion attribute");
  8546. // Target only causes MV if it is default, otherwise this is a normal
  8547. // function.
  8548. if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
  8549. return false;
  8550. if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
  8551. FD->setInvalidDecl();
  8552. return true;
  8553. }
  8554. if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
  8555. FD->setInvalidDecl();
  8556. return true;
  8557. }
  8558. FD->setIsMultiVersion();
  8559. return false;
  8560. }
  8561. static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
  8562. for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
  8563. if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
  8564. return true;
  8565. }
  8566. return false;
  8567. }
  8568. static bool CheckTargetCausesMultiVersioning(
  8569. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
  8570. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8571. LookupResult &Previous) {
  8572. const auto *OldTA = OldFD->getAttr<TargetAttr>();
  8573. TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
  8574. // Sort order doesn't matter, it just needs to be consistent.
  8575. llvm::sort(NewParsed.Features);
  8576. // If the old decl is NOT MultiVersioned yet, and we don't cause that
  8577. // to change, this is a simple redeclaration.
  8578. if (!NewTA->isDefaultVersion() &&
  8579. (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
  8580. return false;
  8581. // Otherwise, this decl causes MultiVersioning.
  8582. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8583. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8584. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8585. NewFD->setInvalidDecl();
  8586. return true;
  8587. }
  8588. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
  8589. MultiVersionKind::Target)) {
  8590. NewFD->setInvalidDecl();
  8591. return true;
  8592. }
  8593. if (CheckMultiVersionValue(S, NewFD)) {
  8594. NewFD->setInvalidDecl();
  8595. return true;
  8596. }
  8597. // If this is 'default', permit the forward declaration.
  8598. if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
  8599. Redeclaration = true;
  8600. OldDecl = OldFD;
  8601. OldFD->setIsMultiVersion();
  8602. NewFD->setIsMultiVersion();
  8603. return false;
  8604. }
  8605. if (CheckMultiVersionValue(S, OldFD)) {
  8606. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8607. NewFD->setInvalidDecl();
  8608. return true;
  8609. }
  8610. TargetAttr::ParsedTargetAttr OldParsed =
  8611. OldTA->parse(std::less<std::string>());
  8612. if (OldParsed == NewParsed) {
  8613. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8614. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8615. NewFD->setInvalidDecl();
  8616. return true;
  8617. }
  8618. for (const auto *FD : OldFD->redecls()) {
  8619. const auto *CurTA = FD->getAttr<TargetAttr>();
  8620. // We allow forward declarations before ANY multiversioning attributes, but
  8621. // nothing after the fact.
  8622. if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
  8623. (!CurTA || CurTA->isInherited())) {
  8624. S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
  8625. << 0;
  8626. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8627. NewFD->setInvalidDecl();
  8628. return true;
  8629. }
  8630. }
  8631. OldFD->setIsMultiVersion();
  8632. NewFD->setIsMultiVersion();
  8633. Redeclaration = false;
  8634. MergeTypeWithPrevious = false;
  8635. OldDecl = nullptr;
  8636. Previous.clear();
  8637. return false;
  8638. }
  8639. /// Check the validity of a new function declaration being added to an existing
  8640. /// multiversioned declaration collection.
  8641. static bool CheckMultiVersionAdditionalDecl(
  8642. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
  8643. MultiVersionKind NewMVType, const TargetAttr *NewTA,
  8644. const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
  8645. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8646. LookupResult &Previous) {
  8647. MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
  8648. // Disallow mixing of multiversioning types.
  8649. if ((OldMVType == MultiVersionKind::Target &&
  8650. NewMVType != MultiVersionKind::Target) ||
  8651. (NewMVType == MultiVersionKind::Target &&
  8652. OldMVType != MultiVersionKind::Target)) {
  8653. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8654. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8655. NewFD->setInvalidDecl();
  8656. return true;
  8657. }
  8658. TargetAttr::ParsedTargetAttr NewParsed;
  8659. if (NewTA) {
  8660. NewParsed = NewTA->parse();
  8661. llvm::sort(NewParsed.Features);
  8662. }
  8663. bool UseMemberUsingDeclRules =
  8664. S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
  8665. // Next, check ALL non-overloads to see if this is a redeclaration of a
  8666. // previous member of the MultiVersion set.
  8667. for (NamedDecl *ND : Previous) {
  8668. FunctionDecl *CurFD = ND->getAsFunction();
  8669. if (!CurFD)
  8670. continue;
  8671. if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
  8672. continue;
  8673. if (NewMVType == MultiVersionKind::Target) {
  8674. const auto *CurTA = CurFD->getAttr<TargetAttr>();
  8675. if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
  8676. NewFD->setIsMultiVersion();
  8677. Redeclaration = true;
  8678. OldDecl = ND;
  8679. return false;
  8680. }
  8681. TargetAttr::ParsedTargetAttr CurParsed =
  8682. CurTA->parse(std::less<std::string>());
  8683. if (CurParsed == NewParsed) {
  8684. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8685. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8686. NewFD->setInvalidDecl();
  8687. return true;
  8688. }
  8689. } else {
  8690. const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
  8691. const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
  8692. // Handle CPUDispatch/CPUSpecific versions.
  8693. // Only 1 CPUDispatch function is allowed, this will make it go through
  8694. // the redeclaration errors.
  8695. if (NewMVType == MultiVersionKind::CPUDispatch &&
  8696. CurFD->hasAttr<CPUDispatchAttr>()) {
  8697. if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
  8698. std::equal(
  8699. CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
  8700. NewCPUDisp->cpus_begin(),
  8701. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8702. return Cur->getName() == New->getName();
  8703. })) {
  8704. NewFD->setIsMultiVersion();
  8705. Redeclaration = true;
  8706. OldDecl = ND;
  8707. return false;
  8708. }
  8709. // If the declarations don't match, this is an error condition.
  8710. S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
  8711. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8712. NewFD->setInvalidDecl();
  8713. return true;
  8714. }
  8715. if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
  8716. if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
  8717. std::equal(
  8718. CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
  8719. NewCPUSpec->cpus_begin(),
  8720. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8721. return Cur->getName() == New->getName();
  8722. })) {
  8723. NewFD->setIsMultiVersion();
  8724. Redeclaration = true;
  8725. OldDecl = ND;
  8726. return false;
  8727. }
  8728. // Only 1 version of CPUSpecific is allowed for each CPU.
  8729. for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
  8730. for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
  8731. if (CurII == NewII) {
  8732. S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
  8733. << NewII;
  8734. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8735. NewFD->setInvalidDecl();
  8736. return true;
  8737. }
  8738. }
  8739. }
  8740. }
  8741. // If the two decls aren't the same MVType, there is no possible error
  8742. // condition.
  8743. }
  8744. }
  8745. // Else, this is simply a non-redecl case. Checking the 'value' is only
  8746. // necessary in the Target case, since The CPUSpecific/Dispatch cases are
  8747. // handled in the attribute adding step.
  8748. if (NewMVType == MultiVersionKind::Target &&
  8749. CheckMultiVersionValue(S, NewFD)) {
  8750. NewFD->setInvalidDecl();
  8751. return true;
  8752. }
  8753. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
  8754. !OldFD->isMultiVersion(), NewMVType)) {
  8755. NewFD->setInvalidDecl();
  8756. return true;
  8757. }
  8758. // Permit forward declarations in the case where these two are compatible.
  8759. if (!OldFD->isMultiVersion()) {
  8760. OldFD->setIsMultiVersion();
  8761. NewFD->setIsMultiVersion();
  8762. Redeclaration = true;
  8763. OldDecl = OldFD;
  8764. return false;
  8765. }
  8766. NewFD->setIsMultiVersion();
  8767. Redeclaration = false;
  8768. MergeTypeWithPrevious = false;
  8769. OldDecl = nullptr;
  8770. Previous.clear();
  8771. return false;
  8772. }
  8773. /// Check the validity of a mulitversion function declaration.
  8774. /// Also sets the multiversion'ness' of the function itself.
  8775. ///
  8776. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8777. ///
  8778. /// Returns true if there was an error, false otherwise.
  8779. static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
  8780. bool &Redeclaration, NamedDecl *&OldDecl,
  8781. bool &MergeTypeWithPrevious,
  8782. LookupResult &Previous) {
  8783. const auto *NewTA = NewFD->getAttr<TargetAttr>();
  8784. const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
  8785. const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
  8786. // Mixing Multiversioning types is prohibited.
  8787. if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
  8788. (NewCPUDisp && NewCPUSpec)) {
  8789. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8790. NewFD->setInvalidDecl();
  8791. return true;
  8792. }
  8793. MultiVersionKind MVType = NewFD->getMultiVersionKind();
  8794. // Main isn't allowed to become a multiversion function, however it IS
  8795. // permitted to have 'main' be marked with the 'target' optimization hint.
  8796. if (NewFD->isMain()) {
  8797. if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
  8798. MVType == MultiVersionKind::CPUDispatch ||
  8799. MVType == MultiVersionKind::CPUSpecific) {
  8800. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
  8801. NewFD->setInvalidDecl();
  8802. return true;
  8803. }
  8804. return false;
  8805. }
  8806. if (!OldDecl || !OldDecl->getAsFunction() ||
  8807. OldDecl->getDeclContext()->getRedeclContext() !=
  8808. NewFD->getDeclContext()->getRedeclContext()) {
  8809. // If there's no previous declaration, AND this isn't attempting to cause
  8810. // multiversioning, this isn't an error condition.
  8811. if (MVType == MultiVersionKind::None)
  8812. return false;
  8813. return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
  8814. }
  8815. FunctionDecl *OldFD = OldDecl->getAsFunction();
  8816. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
  8817. return false;
  8818. if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
  8819. S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
  8820. << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
  8821. NewFD->setInvalidDecl();
  8822. return true;
  8823. }
  8824. // Handle the target potentially causes multiversioning case.
  8825. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
  8826. return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
  8827. Redeclaration, OldDecl,
  8828. MergeTypeWithPrevious, Previous);
  8829. // At this point, we have a multiversion function decl (in OldFD) AND an
  8830. // appropriate attribute in the current function decl. Resolve that these are
  8831. // still compatible with previous declarations.
  8832. return CheckMultiVersionAdditionalDecl(
  8833. S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
  8834. OldDecl, MergeTypeWithPrevious, Previous);
  8835. }
  8836. /// Perform semantic checking of a new function declaration.
  8837. ///
  8838. /// Performs semantic analysis of the new function declaration
  8839. /// NewFD. This routine performs all semantic checking that does not
  8840. /// require the actual declarator involved in the declaration, and is
  8841. /// used both for the declaration of functions as they are parsed
  8842. /// (called via ActOnDeclarator) and for the declaration of functions
  8843. /// that have been instantiated via C++ template instantiation (called
  8844. /// via InstantiateDecl).
  8845. ///
  8846. /// \param IsMemberSpecialization whether this new function declaration is
  8847. /// a member specialization (that replaces any definition provided by the
  8848. /// previous declaration).
  8849. ///
  8850. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8851. ///
  8852. /// \returns true if the function declaration is a redeclaration.
  8853. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  8854. LookupResult &Previous,
  8855. bool IsMemberSpecialization) {
  8856. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  8857. "Variably modified return types are not handled here");
  8858. // Determine whether the type of this function should be merged with
  8859. // a previous visible declaration. This never happens for functions in C++,
  8860. // and always happens in C if the previous declaration was visible.
  8861. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  8862. !Previous.isShadowed();
  8863. bool Redeclaration = false;
  8864. NamedDecl *OldDecl = nullptr;
  8865. bool MayNeedOverloadableChecks = false;
  8866. // Merge or overload the declaration with an existing declaration of
  8867. // the same name, if appropriate.
  8868. if (!Previous.empty()) {
  8869. // Determine whether NewFD is an overload of PrevDecl or
  8870. // a declaration that requires merging. If it's an overload,
  8871. // there's no more work to do here; we'll just add the new
  8872. // function to the scope.
  8873. if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
  8874. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  8875. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  8876. Redeclaration = true;
  8877. OldDecl = Candidate;
  8878. }
  8879. } else {
  8880. MayNeedOverloadableChecks = true;
  8881. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  8882. /*NewIsUsingDecl*/ false)) {
  8883. case Ovl_Match:
  8884. Redeclaration = true;
  8885. break;
  8886. case Ovl_NonFunction:
  8887. Redeclaration = true;
  8888. break;
  8889. case Ovl_Overload:
  8890. Redeclaration = false;
  8891. break;
  8892. }
  8893. }
  8894. }
  8895. // Check for a previous extern "C" declaration with this name.
  8896. if (!Redeclaration &&
  8897. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  8898. if (!Previous.empty()) {
  8899. // This is an extern "C" declaration with the same name as a previous
  8900. // declaration, and thus redeclares that entity...
  8901. Redeclaration = true;
  8902. OldDecl = Previous.getFoundDecl();
  8903. MergeTypeWithPrevious = false;
  8904. // ... except in the presence of __attribute__((overloadable)).
  8905. if (OldDecl->hasAttr<OverloadableAttr>() ||
  8906. NewFD->hasAttr<OverloadableAttr>()) {
  8907. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  8908. MayNeedOverloadableChecks = true;
  8909. Redeclaration = false;
  8910. OldDecl = nullptr;
  8911. }
  8912. }
  8913. }
  8914. }
  8915. if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
  8916. MergeTypeWithPrevious, Previous))
  8917. return Redeclaration;
  8918. // C++11 [dcl.constexpr]p8:
  8919. // A constexpr specifier for a non-static member function that is not
  8920. // a constructor declares that member function to be const.
  8921. //
  8922. // This needs to be delayed until we know whether this is an out-of-line
  8923. // definition of a static member function.
  8924. //
  8925. // This rule is not present in C++1y, so we produce a backwards
  8926. // compatibility warning whenever it happens in C++11.
  8927. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  8928. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  8929. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  8930. !MD->getMethodQualifiers().hasConst()) {
  8931. CXXMethodDecl *OldMD = nullptr;
  8932. if (OldDecl)
  8933. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  8934. if (!OldMD || !OldMD->isStatic()) {
  8935. const FunctionProtoType *FPT =
  8936. MD->getType()->castAs<FunctionProtoType>();
  8937. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  8938. EPI.TypeQuals.addConst();
  8939. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  8940. FPT->getParamTypes(), EPI));
  8941. // Warn that we did this, if we're not performing template instantiation.
  8942. // In that case, we'll have warned already when the template was defined.
  8943. if (!inTemplateInstantiation()) {
  8944. SourceLocation AddConstLoc;
  8945. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  8946. .IgnoreParens().getAs<FunctionTypeLoc>())
  8947. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  8948. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  8949. << FixItHint::CreateInsertion(AddConstLoc, " const");
  8950. }
  8951. }
  8952. }
  8953. if (Redeclaration) {
  8954. // NewFD and OldDecl represent declarations that need to be
  8955. // merged.
  8956. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  8957. NewFD->setInvalidDecl();
  8958. return Redeclaration;
  8959. }
  8960. Previous.clear();
  8961. Previous.addDecl(OldDecl);
  8962. if (FunctionTemplateDecl *OldTemplateDecl =
  8963. dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  8964. auto *OldFD = OldTemplateDecl->getTemplatedDecl();
  8965. FunctionTemplateDecl *NewTemplateDecl
  8966. = NewFD->getDescribedFunctionTemplate();
  8967. assert(NewTemplateDecl && "Template/non-template mismatch");
  8968. // The call to MergeFunctionDecl above may have created some state in
  8969. // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
  8970. // can add it as a redeclaration.
  8971. NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
  8972. NewFD->setPreviousDeclaration(OldFD);
  8973. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  8974. if (NewFD->isCXXClassMember()) {
  8975. NewFD->setAccess(OldTemplateDecl->getAccess());
  8976. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  8977. }
  8978. // If this is an explicit specialization of a member that is a function
  8979. // template, mark it as a member specialization.
  8980. if (IsMemberSpecialization &&
  8981. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  8982. NewTemplateDecl->setMemberSpecialization();
  8983. assert(OldTemplateDecl->isMemberSpecialization());
  8984. // Explicit specializations of a member template do not inherit deleted
  8985. // status from the parent member template that they are specializing.
  8986. if (OldFD->isDeleted()) {
  8987. // FIXME: This assert will not hold in the presence of modules.
  8988. assert(OldFD->getCanonicalDecl() == OldFD);
  8989. // FIXME: We need an update record for this AST mutation.
  8990. OldFD->setDeletedAsWritten(false);
  8991. }
  8992. }
  8993. } else {
  8994. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  8995. auto *OldFD = cast<FunctionDecl>(OldDecl);
  8996. // This needs to happen first so that 'inline' propagates.
  8997. NewFD->setPreviousDeclaration(OldFD);
  8998. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  8999. if (NewFD->isCXXClassMember())
  9000. NewFD->setAccess(OldFD->getAccess());
  9001. }
  9002. }
  9003. } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
  9004. !NewFD->getAttr<OverloadableAttr>()) {
  9005. assert((Previous.empty() ||
  9006. llvm::any_of(Previous,
  9007. [](const NamedDecl *ND) {
  9008. return ND->hasAttr<OverloadableAttr>();
  9009. })) &&
  9010. "Non-redecls shouldn't happen without overloadable present");
  9011. auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
  9012. const auto *FD = dyn_cast<FunctionDecl>(ND);
  9013. return FD && !FD->hasAttr<OverloadableAttr>();
  9014. });
  9015. if (OtherUnmarkedIter != Previous.end()) {
  9016. Diag(NewFD->getLocation(),
  9017. diag::err_attribute_overloadable_multiple_unmarked_overloads);
  9018. Diag((*OtherUnmarkedIter)->getLocation(),
  9019. diag::note_attribute_overloadable_prev_overload)
  9020. << false;
  9021. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  9022. }
  9023. }
  9024. // Semantic checking for this function declaration (in isolation).
  9025. if (getLangOpts().CPlusPlus) {
  9026. // C++-specific checks.
  9027. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  9028. CheckConstructor(Constructor);
  9029. } else if (CXXDestructorDecl *Destructor =
  9030. dyn_cast<CXXDestructorDecl>(NewFD)) {
  9031. CXXRecordDecl *Record = Destructor->getParent();
  9032. QualType ClassType = Context.getTypeDeclType(Record);
  9033. // FIXME: Shouldn't we be able to perform this check even when the class
  9034. // type is dependent? Both gcc and edg can handle that.
  9035. if (!ClassType->isDependentType()) {
  9036. DeclarationName Name
  9037. = Context.DeclarationNames.getCXXDestructorName(
  9038. Context.getCanonicalType(ClassType));
  9039. if (NewFD->getDeclName() != Name) {
  9040. Diag(NewFD->getLocation(), diag::err_destructor_name);
  9041. NewFD->setInvalidDecl();
  9042. return Redeclaration;
  9043. }
  9044. }
  9045. } else if (CXXConversionDecl *Conversion
  9046. = dyn_cast<CXXConversionDecl>(NewFD)) {
  9047. ActOnConversionDeclarator(Conversion);
  9048. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  9049. if (auto *TD = Guide->getDescribedFunctionTemplate())
  9050. CheckDeductionGuideTemplate(TD);
  9051. // A deduction guide is not on the list of entities that can be
  9052. // explicitly specialized.
  9053. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  9054. Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
  9055. << /*explicit specialization*/ 1;
  9056. }
  9057. // Find any virtual functions that this function overrides.
  9058. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  9059. if (!Method->isFunctionTemplateSpecialization() &&
  9060. !Method->getDescribedFunctionTemplate() &&
  9061. Method->isCanonicalDecl()) {
  9062. if (AddOverriddenMethods(Method->getParent(), Method)) {
  9063. // If the function was marked as "static", we have a problem.
  9064. if (NewFD->getStorageClass() == SC_Static) {
  9065. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  9066. }
  9067. }
  9068. }
  9069. if (Method->isStatic())
  9070. checkThisInStaticMemberFunctionType(Method);
  9071. }
  9072. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  9073. if (NewFD->isOverloadedOperator() &&
  9074. CheckOverloadedOperatorDeclaration(NewFD)) {
  9075. NewFD->setInvalidDecl();
  9076. return Redeclaration;
  9077. }
  9078. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  9079. if (NewFD->getLiteralIdentifier() &&
  9080. CheckLiteralOperatorDeclaration(NewFD)) {
  9081. NewFD->setInvalidDecl();
  9082. return Redeclaration;
  9083. }
  9084. // In C++, check default arguments now that we have merged decls. Unless
  9085. // the lexical context is the class, because in this case this is done
  9086. // during delayed parsing anyway.
  9087. if (!CurContext->isRecord())
  9088. CheckCXXDefaultArguments(NewFD);
  9089. // If this function declares a builtin function, check the type of this
  9090. // declaration against the expected type for the builtin.
  9091. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  9092. ASTContext::GetBuiltinTypeError Error;
  9093. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  9094. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  9095. // If the type of the builtin differs only in its exception
  9096. // specification, that's OK.
  9097. // FIXME: If the types do differ in this way, it would be better to
  9098. // retain the 'noexcept' form of the type.
  9099. if (!T.isNull() &&
  9100. !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
  9101. NewFD->getType()))
  9102. // The type of this function differs from the type of the builtin,
  9103. // so forget about the builtin entirely.
  9104. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  9105. }
  9106. // If this function is declared as being extern "C", then check to see if
  9107. // the function returns a UDT (class, struct, or union type) that is not C
  9108. // compatible, and if it does, warn the user.
  9109. // But, issue any diagnostic on the first declaration only.
  9110. if (Previous.empty() && NewFD->isExternC()) {
  9111. QualType R = NewFD->getReturnType();
  9112. if (R->isIncompleteType() && !R->isVoidType())
  9113. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  9114. << NewFD << R;
  9115. else if (!R.isPODType(Context) && !R->isVoidType() &&
  9116. !R->isObjCObjectPointerType())
  9117. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  9118. }
  9119. // C++1z [dcl.fct]p6:
  9120. // [...] whether the function has a non-throwing exception-specification
  9121. // [is] part of the function type
  9122. //
  9123. // This results in an ABI break between C++14 and C++17 for functions whose
  9124. // declared type includes an exception-specification in a parameter or
  9125. // return type. (Exception specifications on the function itself are OK in
  9126. // most cases, and exception specifications are not permitted in most other
  9127. // contexts where they could make it into a mangling.)
  9128. if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
  9129. auto HasNoexcept = [&](QualType T) -> bool {
  9130. // Strip off declarator chunks that could be between us and a function
  9131. // type. We don't need to look far, exception specifications are very
  9132. // restricted prior to C++17.
  9133. if (auto *RT = T->getAs<ReferenceType>())
  9134. T = RT->getPointeeType();
  9135. else if (T->isAnyPointerType())
  9136. T = T->getPointeeType();
  9137. else if (auto *MPT = T->getAs<MemberPointerType>())
  9138. T = MPT->getPointeeType();
  9139. if (auto *FPT = T->getAs<FunctionProtoType>())
  9140. if (FPT->isNothrow())
  9141. return true;
  9142. return false;
  9143. };
  9144. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  9145. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  9146. for (QualType T : FPT->param_types())
  9147. AnyNoexcept |= HasNoexcept(T);
  9148. if (AnyNoexcept)
  9149. Diag(NewFD->getLocation(),
  9150. diag::warn_cxx17_compat_exception_spec_in_signature)
  9151. << NewFD;
  9152. }
  9153. if (!Redeclaration && LangOpts.CUDA)
  9154. checkCUDATargetOverload(NewFD, Previous);
  9155. }
  9156. return Redeclaration;
  9157. }
  9158. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  9159. // C++11 [basic.start.main]p3:
  9160. // A program that [...] declares main to be inline, static or
  9161. // constexpr is ill-formed.
  9162. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  9163. // appear in a declaration of main.
  9164. // static main is not an error under C99, but we should warn about it.
  9165. // We accept _Noreturn main as an extension.
  9166. if (FD->getStorageClass() == SC_Static)
  9167. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  9168. ? diag::err_static_main : diag::warn_static_main)
  9169. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  9170. if (FD->isInlineSpecified())
  9171. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  9172. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  9173. if (DS.isNoreturnSpecified()) {
  9174. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  9175. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  9176. Diag(NoreturnLoc, diag::ext_noreturn_main);
  9177. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  9178. << FixItHint::CreateRemoval(NoreturnRange);
  9179. }
  9180. if (FD->isConstexpr()) {
  9181. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  9182. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  9183. FD->setConstexpr(false);
  9184. }
  9185. if (getLangOpts().OpenCL) {
  9186. Diag(FD->getLocation(), diag::err_opencl_no_main)
  9187. << FD->hasAttr<OpenCLKernelAttr>();
  9188. FD->setInvalidDecl();
  9189. return;
  9190. }
  9191. QualType T = FD->getType();
  9192. assert(T->isFunctionType() && "function decl is not of function type");
  9193. const FunctionType* FT = T->castAs<FunctionType>();
  9194. // Set default calling convention for main()
  9195. if (FT->getCallConv() != CC_C) {
  9196. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
  9197. FD->setType(QualType(FT, 0));
  9198. T = Context.getCanonicalType(FD->getType());
  9199. }
  9200. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  9201. // In C with GNU extensions we allow main() to have non-integer return
  9202. // type, but we should warn about the extension, and we disable the
  9203. // implicit-return-zero rule.
  9204. // GCC in C mode accepts qualified 'int'.
  9205. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  9206. FD->setHasImplicitReturnZero(true);
  9207. else {
  9208. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  9209. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9210. if (RTRange.isValid())
  9211. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  9212. << FixItHint::CreateReplacement(RTRange, "int");
  9213. }
  9214. } else {
  9215. // In C and C++, main magically returns 0 if you fall off the end;
  9216. // set the flag which tells us that.
  9217. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  9218. // All the standards say that main() should return 'int'.
  9219. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  9220. FD->setHasImplicitReturnZero(true);
  9221. else {
  9222. // Otherwise, this is just a flat-out error.
  9223. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9224. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  9225. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  9226. : FixItHint());
  9227. FD->setInvalidDecl(true);
  9228. }
  9229. }
  9230. // Treat protoless main() as nullary.
  9231. if (isa<FunctionNoProtoType>(FT)) return;
  9232. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  9233. unsigned nparams = FTP->getNumParams();
  9234. assert(FD->getNumParams() == nparams);
  9235. bool HasExtraParameters = (nparams > 3);
  9236. if (FTP->isVariadic()) {
  9237. Diag(FD->getLocation(), diag::ext_variadic_main);
  9238. // FIXME: if we had information about the location of the ellipsis, we
  9239. // could add a FixIt hint to remove it as a parameter.
  9240. }
  9241. // Darwin passes an undocumented fourth argument of type char**. If
  9242. // other platforms start sprouting these, the logic below will start
  9243. // getting shifty.
  9244. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  9245. HasExtraParameters = false;
  9246. if (HasExtraParameters) {
  9247. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  9248. FD->setInvalidDecl(true);
  9249. nparams = 3;
  9250. }
  9251. // FIXME: a lot of the following diagnostics would be improved
  9252. // if we had some location information about types.
  9253. QualType CharPP =
  9254. Context.getPointerType(Context.getPointerType(Context.CharTy));
  9255. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  9256. for (unsigned i = 0; i < nparams; ++i) {
  9257. QualType AT = FTP->getParamType(i);
  9258. bool mismatch = true;
  9259. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  9260. mismatch = false;
  9261. else if (Expected[i] == CharPP) {
  9262. // As an extension, the following forms are okay:
  9263. // char const **
  9264. // char const * const *
  9265. // char * const *
  9266. QualifierCollector qs;
  9267. const PointerType* PT;
  9268. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  9269. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  9270. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  9271. Context.CharTy)) {
  9272. qs.removeConst();
  9273. mismatch = !qs.empty();
  9274. }
  9275. }
  9276. if (mismatch) {
  9277. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  9278. // TODO: suggest replacing given type with expected type
  9279. FD->setInvalidDecl(true);
  9280. }
  9281. }
  9282. if (nparams == 1 && !FD->isInvalidDecl()) {
  9283. Diag(FD->getLocation(), diag::warn_main_one_arg);
  9284. }
  9285. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9286. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9287. FD->setInvalidDecl();
  9288. }
  9289. }
  9290. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  9291. QualType T = FD->getType();
  9292. assert(T->isFunctionType() && "function decl is not of function type");
  9293. const FunctionType *FT = T->castAs<FunctionType>();
  9294. // Set an implicit return of 'zero' if the function can return some integral,
  9295. // enumeration, pointer or nullptr type.
  9296. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  9297. FT->getReturnType()->isAnyPointerType() ||
  9298. FT->getReturnType()->isNullPtrType())
  9299. // DllMain is exempt because a return value of zero means it failed.
  9300. if (FD->getName() != "DllMain")
  9301. FD->setHasImplicitReturnZero(true);
  9302. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9303. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9304. FD->setInvalidDecl();
  9305. }
  9306. }
  9307. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  9308. // FIXME: Need strict checking. In C89, we need to check for
  9309. // any assignment, increment, decrement, function-calls, or
  9310. // commas outside of a sizeof. In C99, it's the same list,
  9311. // except that the aforementioned are allowed in unevaluated
  9312. // expressions. Everything else falls under the
  9313. // "may accept other forms of constant expressions" exception.
  9314. // (We never end up here for C++, so the constant expression
  9315. // rules there don't matter.)
  9316. const Expr *Culprit;
  9317. if (Init->isConstantInitializer(Context, false, &Culprit))
  9318. return false;
  9319. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  9320. << Culprit->getSourceRange();
  9321. return true;
  9322. }
  9323. namespace {
  9324. // Visits an initialization expression to see if OrigDecl is evaluated in
  9325. // its own initialization and throws a warning if it does.
  9326. class SelfReferenceChecker
  9327. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  9328. Sema &S;
  9329. Decl *OrigDecl;
  9330. bool isRecordType;
  9331. bool isPODType;
  9332. bool isReferenceType;
  9333. bool isInitList;
  9334. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  9335. public:
  9336. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  9337. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  9338. S(S), OrigDecl(OrigDecl) {
  9339. isPODType = false;
  9340. isRecordType = false;
  9341. isReferenceType = false;
  9342. isInitList = false;
  9343. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  9344. isPODType = VD->getType().isPODType(S.Context);
  9345. isRecordType = VD->getType()->isRecordType();
  9346. isReferenceType = VD->getType()->isReferenceType();
  9347. }
  9348. }
  9349. // For most expressions, just call the visitor. For initializer lists,
  9350. // track the index of the field being initialized since fields are
  9351. // initialized in order allowing use of previously initialized fields.
  9352. void CheckExpr(Expr *E) {
  9353. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  9354. if (!InitList) {
  9355. Visit(E);
  9356. return;
  9357. }
  9358. // Track and increment the index here.
  9359. isInitList = true;
  9360. InitFieldIndex.push_back(0);
  9361. for (auto Child : InitList->children()) {
  9362. CheckExpr(cast<Expr>(Child));
  9363. ++InitFieldIndex.back();
  9364. }
  9365. InitFieldIndex.pop_back();
  9366. }
  9367. // Returns true if MemberExpr is checked and no further checking is needed.
  9368. // Returns false if additional checking is required.
  9369. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  9370. llvm::SmallVector<FieldDecl*, 4> Fields;
  9371. Expr *Base = E;
  9372. bool ReferenceField = false;
  9373. // Get the field members used.
  9374. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9375. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  9376. if (!FD)
  9377. return false;
  9378. Fields.push_back(FD);
  9379. if (FD->getType()->isReferenceType())
  9380. ReferenceField = true;
  9381. Base = ME->getBase()->IgnoreParenImpCasts();
  9382. }
  9383. // Keep checking only if the base Decl is the same.
  9384. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  9385. if (!DRE || DRE->getDecl() != OrigDecl)
  9386. return false;
  9387. // A reference field can be bound to an unininitialized field.
  9388. if (CheckReference && !ReferenceField)
  9389. return true;
  9390. // Convert FieldDecls to their index number.
  9391. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  9392. for (const FieldDecl *I : llvm::reverse(Fields))
  9393. UsedFieldIndex.push_back(I->getFieldIndex());
  9394. // See if a warning is needed by checking the first difference in index
  9395. // numbers. If field being used has index less than the field being
  9396. // initialized, then the use is safe.
  9397. for (auto UsedIter = UsedFieldIndex.begin(),
  9398. UsedEnd = UsedFieldIndex.end(),
  9399. OrigIter = InitFieldIndex.begin(),
  9400. OrigEnd = InitFieldIndex.end();
  9401. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  9402. if (*UsedIter < *OrigIter)
  9403. return true;
  9404. if (*UsedIter > *OrigIter)
  9405. break;
  9406. }
  9407. // TODO: Add a different warning which will print the field names.
  9408. HandleDeclRefExpr(DRE);
  9409. return true;
  9410. }
  9411. // For most expressions, the cast is directly above the DeclRefExpr.
  9412. // For conditional operators, the cast can be outside the conditional
  9413. // operator if both expressions are DeclRefExpr's.
  9414. void HandleValue(Expr *E) {
  9415. E = E->IgnoreParens();
  9416. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  9417. HandleDeclRefExpr(DRE);
  9418. return;
  9419. }
  9420. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  9421. Visit(CO->getCond());
  9422. HandleValue(CO->getTrueExpr());
  9423. HandleValue(CO->getFalseExpr());
  9424. return;
  9425. }
  9426. if (BinaryConditionalOperator *BCO =
  9427. dyn_cast<BinaryConditionalOperator>(E)) {
  9428. Visit(BCO->getCond());
  9429. HandleValue(BCO->getFalseExpr());
  9430. return;
  9431. }
  9432. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  9433. HandleValue(OVE->getSourceExpr());
  9434. return;
  9435. }
  9436. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9437. if (BO->getOpcode() == BO_Comma) {
  9438. Visit(BO->getLHS());
  9439. HandleValue(BO->getRHS());
  9440. return;
  9441. }
  9442. }
  9443. if (isa<MemberExpr>(E)) {
  9444. if (isInitList) {
  9445. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  9446. false /*CheckReference*/))
  9447. return;
  9448. }
  9449. Expr *Base = E->IgnoreParenImpCasts();
  9450. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9451. // Check for static member variables and don't warn on them.
  9452. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9453. return;
  9454. Base = ME->getBase()->IgnoreParenImpCasts();
  9455. }
  9456. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  9457. HandleDeclRefExpr(DRE);
  9458. return;
  9459. }
  9460. Visit(E);
  9461. }
  9462. // Reference types not handled in HandleValue are handled here since all
  9463. // uses of references are bad, not just r-value uses.
  9464. void VisitDeclRefExpr(DeclRefExpr *E) {
  9465. if (isReferenceType)
  9466. HandleDeclRefExpr(E);
  9467. }
  9468. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  9469. if (E->getCastKind() == CK_LValueToRValue) {
  9470. HandleValue(E->getSubExpr());
  9471. return;
  9472. }
  9473. Inherited::VisitImplicitCastExpr(E);
  9474. }
  9475. void VisitMemberExpr(MemberExpr *E) {
  9476. if (isInitList) {
  9477. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  9478. return;
  9479. }
  9480. // Don't warn on arrays since they can be treated as pointers.
  9481. if (E->getType()->canDecayToPointerType()) return;
  9482. // Warn when a non-static method call is followed by non-static member
  9483. // field accesses, which is followed by a DeclRefExpr.
  9484. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  9485. bool Warn = (MD && !MD->isStatic());
  9486. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  9487. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9488. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9489. Warn = false;
  9490. Base = ME->getBase()->IgnoreParenImpCasts();
  9491. }
  9492. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  9493. if (Warn)
  9494. HandleDeclRefExpr(DRE);
  9495. return;
  9496. }
  9497. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  9498. // Visit that expression.
  9499. Visit(Base);
  9500. }
  9501. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  9502. Expr *Callee = E->getCallee();
  9503. if (isa<UnresolvedLookupExpr>(Callee))
  9504. return Inherited::VisitCXXOperatorCallExpr(E);
  9505. Visit(Callee);
  9506. for (auto Arg: E->arguments())
  9507. HandleValue(Arg->IgnoreParenImpCasts());
  9508. }
  9509. void VisitUnaryOperator(UnaryOperator *E) {
  9510. // For POD record types, addresses of its own members are well-defined.
  9511. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  9512. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  9513. if (!isPODType)
  9514. HandleValue(E->getSubExpr());
  9515. return;
  9516. }
  9517. if (E->isIncrementDecrementOp()) {
  9518. HandleValue(E->getSubExpr());
  9519. return;
  9520. }
  9521. Inherited::VisitUnaryOperator(E);
  9522. }
  9523. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  9524. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  9525. if (E->getConstructor()->isCopyConstructor()) {
  9526. Expr *ArgExpr = E->getArg(0);
  9527. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  9528. if (ILE->getNumInits() == 1)
  9529. ArgExpr = ILE->getInit(0);
  9530. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  9531. if (ICE->getCastKind() == CK_NoOp)
  9532. ArgExpr = ICE->getSubExpr();
  9533. HandleValue(ArgExpr);
  9534. return;
  9535. }
  9536. Inherited::VisitCXXConstructExpr(E);
  9537. }
  9538. void VisitCallExpr(CallExpr *E) {
  9539. // Treat std::move as a use.
  9540. if (E->isCallToStdMove()) {
  9541. HandleValue(E->getArg(0));
  9542. return;
  9543. }
  9544. Inherited::VisitCallExpr(E);
  9545. }
  9546. void VisitBinaryOperator(BinaryOperator *E) {
  9547. if (E->isCompoundAssignmentOp()) {
  9548. HandleValue(E->getLHS());
  9549. Visit(E->getRHS());
  9550. return;
  9551. }
  9552. Inherited::VisitBinaryOperator(E);
  9553. }
  9554. // A custom visitor for BinaryConditionalOperator is needed because the
  9555. // regular visitor would check the condition and true expression separately
  9556. // but both point to the same place giving duplicate diagnostics.
  9557. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  9558. Visit(E->getCond());
  9559. Visit(E->getFalseExpr());
  9560. }
  9561. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  9562. Decl* ReferenceDecl = DRE->getDecl();
  9563. if (OrigDecl != ReferenceDecl) return;
  9564. unsigned diag;
  9565. if (isReferenceType) {
  9566. diag = diag::warn_uninit_self_reference_in_reference_init;
  9567. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  9568. diag = diag::warn_static_self_reference_in_init;
  9569. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  9570. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  9571. DRE->getDecl()->getType()->isRecordType()) {
  9572. diag = diag::warn_uninit_self_reference_in_init;
  9573. } else {
  9574. // Local variables will be handled by the CFG analysis.
  9575. return;
  9576. }
  9577. S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
  9578. S.PDiag(diag)
  9579. << DRE->getDecl() << OrigDecl->getLocation()
  9580. << DRE->getSourceRange());
  9581. }
  9582. };
  9583. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  9584. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  9585. bool DirectInit) {
  9586. // Parameters arguments are occassionially constructed with itself,
  9587. // for instance, in recursive functions. Skip them.
  9588. if (isa<ParmVarDecl>(OrigDecl))
  9589. return;
  9590. E = E->IgnoreParens();
  9591. // Skip checking T a = a where T is not a record or reference type.
  9592. // Doing so is a way to silence uninitialized warnings.
  9593. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  9594. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  9595. if (ICE->getCastKind() == CK_LValueToRValue)
  9596. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  9597. if (DRE->getDecl() == OrigDecl)
  9598. return;
  9599. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  9600. }
  9601. } // end anonymous namespace
  9602. namespace {
  9603. // Simple wrapper to add the name of a variable or (if no variable is
  9604. // available) a DeclarationName into a diagnostic.
  9605. struct VarDeclOrName {
  9606. VarDecl *VDecl;
  9607. DeclarationName Name;
  9608. friend const Sema::SemaDiagnosticBuilder &
  9609. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  9610. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  9611. }
  9612. };
  9613. } // end anonymous namespace
  9614. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  9615. DeclarationName Name, QualType Type,
  9616. TypeSourceInfo *TSI,
  9617. SourceRange Range, bool DirectInit,
  9618. Expr *Init) {
  9619. bool IsInitCapture = !VDecl;
  9620. assert((!VDecl || !VDecl->isInitCapture()) &&
  9621. "init captures are expected to be deduced prior to initialization");
  9622. VarDeclOrName VN{VDecl, Name};
  9623. DeducedType *Deduced = Type->getContainedDeducedType();
  9624. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  9625. // C++11 [dcl.spec.auto]p3
  9626. if (!Init) {
  9627. assert(VDecl && "no init for init capture deduction?");
  9628. // Except for class argument deduction, and then for an initializing
  9629. // declaration only, i.e. no static at class scope or extern.
  9630. if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
  9631. VDecl->hasExternalStorage() ||
  9632. VDecl->isStaticDataMember()) {
  9633. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  9634. << VDecl->getDeclName() << Type;
  9635. return QualType();
  9636. }
  9637. }
  9638. ArrayRef<Expr*> DeduceInits;
  9639. if (Init)
  9640. DeduceInits = Init;
  9641. if (DirectInit) {
  9642. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  9643. DeduceInits = PL->exprs();
  9644. }
  9645. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  9646. assert(VDecl && "non-auto type for init capture deduction?");
  9647. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9648. InitializationKind Kind = InitializationKind::CreateForInit(
  9649. VDecl->getLocation(), DirectInit, Init);
  9650. // FIXME: Initialization should not be taking a mutable list of inits.
  9651. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  9652. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  9653. InitsCopy);
  9654. }
  9655. if (DirectInit) {
  9656. if (auto *IL = dyn_cast<InitListExpr>(Init))
  9657. DeduceInits = IL->inits();
  9658. }
  9659. // Deduction only works if we have exactly one source expression.
  9660. if (DeduceInits.empty()) {
  9661. // It isn't possible to write this directly, but it is possible to
  9662. // end up in this situation with "auto x(some_pack...);"
  9663. Diag(Init->getBeginLoc(), IsInitCapture
  9664. ? diag::err_init_capture_no_expression
  9665. : diag::err_auto_var_init_no_expression)
  9666. << VN << Type << Range;
  9667. return QualType();
  9668. }
  9669. if (DeduceInits.size() > 1) {
  9670. Diag(DeduceInits[1]->getBeginLoc(),
  9671. IsInitCapture ? diag::err_init_capture_multiple_expressions
  9672. : diag::err_auto_var_init_multiple_expressions)
  9673. << VN << Type << Range;
  9674. return QualType();
  9675. }
  9676. Expr *DeduceInit = DeduceInits[0];
  9677. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  9678. Diag(Init->getBeginLoc(), IsInitCapture
  9679. ? diag::err_init_capture_paren_braces
  9680. : diag::err_auto_var_init_paren_braces)
  9681. << isa<InitListExpr>(Init) << VN << Type << Range;
  9682. return QualType();
  9683. }
  9684. // Expressions default to 'id' when we're in a debugger.
  9685. bool DefaultedAnyToId = false;
  9686. if (getLangOpts().DebuggerCastResultToId &&
  9687. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  9688. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9689. if (Result.isInvalid()) {
  9690. return QualType();
  9691. }
  9692. Init = Result.get();
  9693. DefaultedAnyToId = true;
  9694. }
  9695. // C++ [dcl.decomp]p1:
  9696. // If the assignment-expression [...] has array type A and no ref-qualifier
  9697. // is present, e has type cv A
  9698. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  9699. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  9700. DeduceInit->getType()->isConstantArrayType())
  9701. return Context.getQualifiedType(DeduceInit->getType(),
  9702. Type.getQualifiers());
  9703. QualType DeducedType;
  9704. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  9705. if (!IsInitCapture)
  9706. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  9707. else if (isa<InitListExpr>(Init))
  9708. Diag(Range.getBegin(),
  9709. diag::err_init_capture_deduction_failure_from_init_list)
  9710. << VN
  9711. << (DeduceInit->getType().isNull() ? TSI->getType()
  9712. : DeduceInit->getType())
  9713. << DeduceInit->getSourceRange();
  9714. else
  9715. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  9716. << VN << TSI->getType()
  9717. << (DeduceInit->getType().isNull() ? TSI->getType()
  9718. : DeduceInit->getType())
  9719. << DeduceInit->getSourceRange();
  9720. }
  9721. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  9722. // 'id' instead of a specific object type prevents most of our usual
  9723. // checks.
  9724. // We only want to warn outside of template instantiations, though:
  9725. // inside a template, the 'id' could have come from a parameter.
  9726. if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
  9727. !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  9728. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  9729. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  9730. }
  9731. return DeducedType;
  9732. }
  9733. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  9734. Expr *Init) {
  9735. QualType DeducedType = deduceVarTypeFromInitializer(
  9736. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  9737. VDecl->getSourceRange(), DirectInit, Init);
  9738. if (DeducedType.isNull()) {
  9739. VDecl->setInvalidDecl();
  9740. return true;
  9741. }
  9742. VDecl->setType(DeducedType);
  9743. assert(VDecl->isLinkageValid());
  9744. // In ARC, infer lifetime.
  9745. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  9746. VDecl->setInvalidDecl();
  9747. // If this is a redeclaration, check that the type we just deduced matches
  9748. // the previously declared type.
  9749. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  9750. // We never need to merge the type, because we cannot form an incomplete
  9751. // array of auto, nor deduce such a type.
  9752. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  9753. }
  9754. // Check the deduced type is valid for a variable declaration.
  9755. CheckVariableDeclarationType(VDecl);
  9756. return VDecl->isInvalidDecl();
  9757. }
  9758. /// AddInitializerToDecl - Adds the initializer Init to the
  9759. /// declaration dcl. If DirectInit is true, this is C++ direct
  9760. /// initialization rather than copy initialization.
  9761. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  9762. // If there is no declaration, there was an error parsing it. Just ignore
  9763. // the initializer.
  9764. if (!RealDecl || RealDecl->isInvalidDecl()) {
  9765. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  9766. return;
  9767. }
  9768. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  9769. // Pure-specifiers are handled in ActOnPureSpecifier.
  9770. Diag(Method->getLocation(), diag::err_member_function_initialization)
  9771. << Method->getDeclName() << Init->getSourceRange();
  9772. Method->setInvalidDecl();
  9773. return;
  9774. }
  9775. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  9776. if (!VDecl) {
  9777. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  9778. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  9779. RealDecl->setInvalidDecl();
  9780. return;
  9781. }
  9782. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  9783. if (VDecl->getType()->isUndeducedType()) {
  9784. // Attempt typo correction early so that the type of the init expression can
  9785. // be deduced based on the chosen correction if the original init contains a
  9786. // TypoExpr.
  9787. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  9788. if (!Res.isUsable()) {
  9789. RealDecl->setInvalidDecl();
  9790. return;
  9791. }
  9792. Init = Res.get();
  9793. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  9794. return;
  9795. }
  9796. // dllimport cannot be used on variable definitions.
  9797. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  9798. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  9799. VDecl->setInvalidDecl();
  9800. return;
  9801. }
  9802. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  9803. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  9804. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  9805. VDecl->setInvalidDecl();
  9806. return;
  9807. }
  9808. if (!VDecl->getType()->isDependentType()) {
  9809. // A definition must end up with a complete type, which means it must be
  9810. // complete with the restriction that an array type might be completed by
  9811. // the initializer; note that later code assumes this restriction.
  9812. QualType BaseDeclType = VDecl->getType();
  9813. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  9814. BaseDeclType = Array->getElementType();
  9815. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  9816. diag::err_typecheck_decl_incomplete_type)) {
  9817. RealDecl->setInvalidDecl();
  9818. return;
  9819. }
  9820. // The variable can not have an abstract class type.
  9821. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  9822. diag::err_abstract_type_in_decl,
  9823. AbstractVariableType))
  9824. VDecl->setInvalidDecl();
  9825. }
  9826. // If adding the initializer will turn this declaration into a definition,
  9827. // and we already have a definition for this variable, diagnose or otherwise
  9828. // handle the situation.
  9829. VarDecl *Def;
  9830. if ((Def = VDecl->getDefinition()) && Def != VDecl &&
  9831. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  9832. !VDecl->isThisDeclarationADemotedDefinition() &&
  9833. checkVarDeclRedefinition(Def, VDecl))
  9834. return;
  9835. if (getLangOpts().CPlusPlus) {
  9836. // C++ [class.static.data]p4
  9837. // If a static data member is of const integral or const
  9838. // enumeration type, its declaration in the class definition can
  9839. // specify a constant-initializer which shall be an integral
  9840. // constant expression (5.19). In that case, the member can appear
  9841. // in integral constant expressions. The member shall still be
  9842. // defined in a namespace scope if it is used in the program and the
  9843. // namespace scope definition shall not contain an initializer.
  9844. //
  9845. // We already performed a redefinition check above, but for static
  9846. // data members we also need to check whether there was an in-class
  9847. // declaration with an initializer.
  9848. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  9849. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  9850. << VDecl->getDeclName();
  9851. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  9852. diag::note_previous_initializer)
  9853. << 0;
  9854. return;
  9855. }
  9856. if (VDecl->hasLocalStorage())
  9857. setFunctionHasBranchProtectedScope();
  9858. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  9859. VDecl->setInvalidDecl();
  9860. return;
  9861. }
  9862. }
  9863. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  9864. // a kernel function cannot be initialized."
  9865. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  9866. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  9867. VDecl->setInvalidDecl();
  9868. return;
  9869. }
  9870. // Get the decls type and save a reference for later, since
  9871. // CheckInitializerTypes may change it.
  9872. QualType DclT = VDecl->getType(), SavT = DclT;
  9873. // Expressions default to 'id' when we're in a debugger
  9874. // and we are assigning it to a variable of Objective-C pointer type.
  9875. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  9876. Init->getType() == Context.UnknownAnyTy) {
  9877. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9878. if (Result.isInvalid()) {
  9879. VDecl->setInvalidDecl();
  9880. return;
  9881. }
  9882. Init = Result.get();
  9883. }
  9884. // Perform the initialization.
  9885. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  9886. if (!VDecl->isInvalidDecl()) {
  9887. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9888. InitializationKind Kind = InitializationKind::CreateForInit(
  9889. VDecl->getLocation(), DirectInit, Init);
  9890. MultiExprArg Args = Init;
  9891. if (CXXDirectInit)
  9892. Args = MultiExprArg(CXXDirectInit->getExprs(),
  9893. CXXDirectInit->getNumExprs());
  9894. // Try to correct any TypoExprs in the initialization arguments.
  9895. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  9896. ExprResult Res = CorrectDelayedTyposInExpr(
  9897. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  9898. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  9899. return Init.Failed() ? ExprError() : E;
  9900. });
  9901. if (Res.isInvalid()) {
  9902. VDecl->setInvalidDecl();
  9903. } else if (Res.get() != Args[Idx]) {
  9904. Args[Idx] = Res.get();
  9905. }
  9906. }
  9907. if (VDecl->isInvalidDecl())
  9908. return;
  9909. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  9910. /*TopLevelOfInitList=*/false,
  9911. /*TreatUnavailableAsInvalid=*/false);
  9912. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  9913. if (Result.isInvalid()) {
  9914. VDecl->setInvalidDecl();
  9915. return;
  9916. }
  9917. Init = Result.getAs<Expr>();
  9918. }
  9919. // Check for self-references within variable initializers.
  9920. // Variables declared within a function/method body (except for references)
  9921. // are handled by a dataflow analysis.
  9922. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  9923. VDecl->getType()->isReferenceType()) {
  9924. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  9925. }
  9926. // If the type changed, it means we had an incomplete type that was
  9927. // completed by the initializer. For example:
  9928. // int ary[] = { 1, 3, 5 };
  9929. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  9930. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  9931. VDecl->setType(DclT);
  9932. if (!VDecl->isInvalidDecl()) {
  9933. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  9934. if (VDecl->hasAttr<BlocksAttr>())
  9935. checkRetainCycles(VDecl, Init);
  9936. // It is safe to assign a weak reference into a strong variable.
  9937. // Although this code can still have problems:
  9938. // id x = self.weakProp;
  9939. // id y = self.weakProp;
  9940. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  9941. // paths through the function. This should be revisited if
  9942. // -Wrepeated-use-of-weak is made flow-sensitive.
  9943. if (FunctionScopeInfo *FSI = getCurFunction())
  9944. if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
  9945. VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
  9946. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  9947. Init->getBeginLoc()))
  9948. FSI->markSafeWeakUse(Init);
  9949. }
  9950. // The initialization is usually a full-expression.
  9951. //
  9952. // FIXME: If this is a braced initialization of an aggregate, it is not
  9953. // an expression, and each individual field initializer is a separate
  9954. // full-expression. For instance, in:
  9955. //
  9956. // struct Temp { ~Temp(); };
  9957. // struct S { S(Temp); };
  9958. // struct T { S a, b; } t = { Temp(), Temp() }
  9959. //
  9960. // we should destroy the first Temp before constructing the second.
  9961. ExprResult Result =
  9962. ActOnFinishFullExpr(Init, VDecl->getLocation(),
  9963. /*DiscardedValue*/ false, VDecl->isConstexpr());
  9964. if (Result.isInvalid()) {
  9965. VDecl->setInvalidDecl();
  9966. return;
  9967. }
  9968. Init = Result.get();
  9969. // Attach the initializer to the decl.
  9970. VDecl->setInit(Init);
  9971. if (VDecl->isLocalVarDecl()) {
  9972. // Don't check the initializer if the declaration is malformed.
  9973. if (VDecl->isInvalidDecl()) {
  9974. // do nothing
  9975. // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
  9976. // This is true even in OpenCL C++.
  9977. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
  9978. CheckForConstantInitializer(Init, DclT);
  9979. // Otherwise, C++ does not restrict the initializer.
  9980. } else if (getLangOpts().CPlusPlus) {
  9981. // do nothing
  9982. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  9983. // static storage duration shall be constant expressions or string literals.
  9984. } else if (VDecl->getStorageClass() == SC_Static) {
  9985. CheckForConstantInitializer(Init, DclT);
  9986. // C89 is stricter than C99 for aggregate initializers.
  9987. // C89 6.5.7p3: All the expressions [...] in an initializer list
  9988. // for an object that has aggregate or union type shall be
  9989. // constant expressions.
  9990. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  9991. isa<InitListExpr>(Init)) {
  9992. const Expr *Culprit;
  9993. if (!Init->isConstantInitializer(Context, false, &Culprit)) {
  9994. Diag(Culprit->getExprLoc(),
  9995. diag::ext_aggregate_init_not_constant)
  9996. << Culprit->getSourceRange();
  9997. }
  9998. }
  9999. if (auto *E = dyn_cast<ExprWithCleanups>(Init))
  10000. if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
  10001. if (VDecl->hasLocalStorage())
  10002. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  10003. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  10004. VDecl->getLexicalDeclContext()->isRecord()) {
  10005. // This is an in-class initialization for a static data member, e.g.,
  10006. //
  10007. // struct S {
  10008. // static const int value = 17;
  10009. // };
  10010. // C++ [class.mem]p4:
  10011. // A member-declarator can contain a constant-initializer only
  10012. // if it declares a static member (9.4) of const integral or
  10013. // const enumeration type, see 9.4.2.
  10014. //
  10015. // C++11 [class.static.data]p3:
  10016. // If a non-volatile non-inline const static data member is of integral
  10017. // or enumeration type, its declaration in the class definition can
  10018. // specify a brace-or-equal-initializer in which every initializer-clause
  10019. // that is an assignment-expression is a constant expression. A static
  10020. // data member of literal type can be declared in the class definition
  10021. // with the constexpr specifier; if so, its declaration shall specify a
  10022. // brace-or-equal-initializer in which every initializer-clause that is
  10023. // an assignment-expression is a constant expression.
  10024. // Do nothing on dependent types.
  10025. if (DclT->isDependentType()) {
  10026. // Allow any 'static constexpr' members, whether or not they are of literal
  10027. // type. We separately check that every constexpr variable is of literal
  10028. // type.
  10029. } else if (VDecl->isConstexpr()) {
  10030. // Require constness.
  10031. } else if (!DclT.isConstQualified()) {
  10032. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  10033. << Init->getSourceRange();
  10034. VDecl->setInvalidDecl();
  10035. // We allow integer constant expressions in all cases.
  10036. } else if (DclT->isIntegralOrEnumerationType()) {
  10037. // Check whether the expression is a constant expression.
  10038. SourceLocation Loc;
  10039. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  10040. // In C++11, a non-constexpr const static data member with an
  10041. // in-class initializer cannot be volatile.
  10042. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  10043. else if (Init->isValueDependent())
  10044. ; // Nothing to check.
  10045. else if (Init->isIntegerConstantExpr(Context, &Loc))
  10046. ; // Ok, it's an ICE!
  10047. else if (Init->getType()->isScopedEnumeralType() &&
  10048. Init->isCXX11ConstantExpr(Context))
  10049. ; // Ok, it is a scoped-enum constant expression.
  10050. else if (Init->isEvaluatable(Context)) {
  10051. // If we can constant fold the initializer through heroics, accept it,
  10052. // but report this as a use of an extension for -pedantic.
  10053. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  10054. << Init->getSourceRange();
  10055. } else {
  10056. // Otherwise, this is some crazy unknown case. Report the issue at the
  10057. // location provided by the isIntegerConstantExpr failed check.
  10058. Diag(Loc, diag::err_in_class_initializer_non_constant)
  10059. << Init->getSourceRange();
  10060. VDecl->setInvalidDecl();
  10061. }
  10062. // We allow foldable floating-point constants as an extension.
  10063. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  10064. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  10065. // it anyway and provide a fixit to add the 'constexpr'.
  10066. if (getLangOpts().CPlusPlus11) {
  10067. Diag(VDecl->getLocation(),
  10068. diag::ext_in_class_initializer_float_type_cxx11)
  10069. << DclT << Init->getSourceRange();
  10070. Diag(VDecl->getBeginLoc(),
  10071. diag::note_in_class_initializer_float_type_cxx11)
  10072. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10073. } else {
  10074. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  10075. << DclT << Init->getSourceRange();
  10076. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  10077. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  10078. << Init->getSourceRange();
  10079. VDecl->setInvalidDecl();
  10080. }
  10081. }
  10082. // Suggest adding 'constexpr' in C++11 for literal types.
  10083. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  10084. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  10085. << DclT << Init->getSourceRange()
  10086. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10087. VDecl->setConstexpr(true);
  10088. } else {
  10089. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  10090. << DclT << Init->getSourceRange();
  10091. VDecl->setInvalidDecl();
  10092. }
  10093. } else if (VDecl->isFileVarDecl()) {
  10094. // In C, extern is typically used to avoid tentative definitions when
  10095. // declaring variables in headers, but adding an intializer makes it a
  10096. // definition. This is somewhat confusing, so GCC and Clang both warn on it.
  10097. // In C++, extern is often used to give implictly static const variables
  10098. // external linkage, so don't warn in that case. If selectany is present,
  10099. // this might be header code intended for C and C++ inclusion, so apply the
  10100. // C++ rules.
  10101. if (VDecl->getStorageClass() == SC_Extern &&
  10102. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  10103. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  10104. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  10105. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  10106. Diag(VDecl->getLocation(), diag::warn_extern_init);
  10107. // In Microsoft C++ mode, a const variable defined in namespace scope has
  10108. // external linkage by default if the variable is declared with
  10109. // __declspec(dllexport).
  10110. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  10111. getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
  10112. VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
  10113. VDecl->setStorageClass(SC_Extern);
  10114. // C99 6.7.8p4. All file scoped initializers need to be constant.
  10115. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  10116. CheckForConstantInitializer(Init, DclT);
  10117. }
  10118. // We will represent direct-initialization similarly to copy-initialization:
  10119. // int x(1); -as-> int x = 1;
  10120. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  10121. //
  10122. // Clients that want to distinguish between the two forms, can check for
  10123. // direct initializer using VarDecl::getInitStyle().
  10124. // A major benefit is that clients that don't particularly care about which
  10125. // exactly form was it (like the CodeGen) can handle both cases without
  10126. // special case code.
  10127. // C++ 8.5p11:
  10128. // The form of initialization (using parentheses or '=') is generally
  10129. // insignificant, but does matter when the entity being initialized has a
  10130. // class type.
  10131. if (CXXDirectInit) {
  10132. assert(DirectInit && "Call-style initializer must be direct init.");
  10133. VDecl->setInitStyle(VarDecl::CallInit);
  10134. } else if (DirectInit) {
  10135. // This must be list-initialization. No other way is direct-initialization.
  10136. VDecl->setInitStyle(VarDecl::ListInit);
  10137. }
  10138. CheckCompleteVariableDeclaration(VDecl);
  10139. }
  10140. /// ActOnInitializerError - Given that there was an error parsing an
  10141. /// initializer for the given declaration, try to return to some form
  10142. /// of sanity.
  10143. void Sema::ActOnInitializerError(Decl *D) {
  10144. // Our main concern here is re-establishing invariants like "a
  10145. // variable's type is either dependent or complete".
  10146. if (!D || D->isInvalidDecl()) return;
  10147. VarDecl *VD = dyn_cast<VarDecl>(D);
  10148. if (!VD) return;
  10149. // Bindings are not usable if we can't make sense of the initializer.
  10150. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  10151. for (auto *BD : DD->bindings())
  10152. BD->setInvalidDecl();
  10153. // Auto types are meaningless if we can't make sense of the initializer.
  10154. if (ParsingInitForAutoVars.count(D)) {
  10155. D->setInvalidDecl();
  10156. return;
  10157. }
  10158. QualType Ty = VD->getType();
  10159. if (Ty->isDependentType()) return;
  10160. // Require a complete type.
  10161. if (RequireCompleteType(VD->getLocation(),
  10162. Context.getBaseElementType(Ty),
  10163. diag::err_typecheck_decl_incomplete_type)) {
  10164. VD->setInvalidDecl();
  10165. return;
  10166. }
  10167. // Require a non-abstract type.
  10168. if (RequireNonAbstractType(VD->getLocation(), Ty,
  10169. diag::err_abstract_type_in_decl,
  10170. AbstractVariableType)) {
  10171. VD->setInvalidDecl();
  10172. return;
  10173. }
  10174. // Don't bother complaining about constructors or destructors,
  10175. // though.
  10176. }
  10177. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  10178. // If there is no declaration, there was an error parsing it. Just ignore it.
  10179. if (!RealDecl)
  10180. return;
  10181. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  10182. QualType Type = Var->getType();
  10183. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  10184. if (isa<DecompositionDecl>(RealDecl)) {
  10185. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  10186. Var->setInvalidDecl();
  10187. return;
  10188. }
  10189. if (Type->isUndeducedType() &&
  10190. DeduceVariableDeclarationType(Var, false, nullptr))
  10191. return;
  10192. // C++11 [class.static.data]p3: A static data member can be declared with
  10193. // the constexpr specifier; if so, its declaration shall specify
  10194. // a brace-or-equal-initializer.
  10195. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  10196. // the definition of a variable [...] or the declaration of a static data
  10197. // member.
  10198. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  10199. !Var->isThisDeclarationADemotedDefinition()) {
  10200. if (Var->isStaticDataMember()) {
  10201. // C++1z removes the relevant rule; the in-class declaration is always
  10202. // a definition there.
  10203. if (!getLangOpts().CPlusPlus17) {
  10204. Diag(Var->getLocation(),
  10205. diag::err_constexpr_static_mem_var_requires_init)
  10206. << Var->getDeclName();
  10207. Var->setInvalidDecl();
  10208. return;
  10209. }
  10210. } else {
  10211. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  10212. Var->setInvalidDecl();
  10213. return;
  10214. }
  10215. }
  10216. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  10217. // be initialized.
  10218. if (!Var->isInvalidDecl() &&
  10219. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  10220. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  10221. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  10222. Var->setInvalidDecl();
  10223. return;
  10224. }
  10225. switch (Var->isThisDeclarationADefinition()) {
  10226. case VarDecl::Definition:
  10227. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  10228. break;
  10229. // We have an out-of-line definition of a static data member
  10230. // that has an in-class initializer, so we type-check this like
  10231. // a declaration.
  10232. //
  10233. LLVM_FALLTHROUGH;
  10234. case VarDecl::DeclarationOnly:
  10235. // It's only a declaration.
  10236. // Block scope. C99 6.7p7: If an identifier for an object is
  10237. // declared with no linkage (C99 6.2.2p6), the type for the
  10238. // object shall be complete.
  10239. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  10240. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  10241. RequireCompleteType(Var->getLocation(), Type,
  10242. diag::err_typecheck_decl_incomplete_type))
  10243. Var->setInvalidDecl();
  10244. // Make sure that the type is not abstract.
  10245. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10246. RequireNonAbstractType(Var->getLocation(), Type,
  10247. diag::err_abstract_type_in_decl,
  10248. AbstractVariableType))
  10249. Var->setInvalidDecl();
  10250. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10251. Var->getStorageClass() == SC_PrivateExtern) {
  10252. Diag(Var->getLocation(), diag::warn_private_extern);
  10253. Diag(Var->getLocation(), diag::note_private_extern);
  10254. }
  10255. return;
  10256. case VarDecl::TentativeDefinition:
  10257. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  10258. // object that has file scope without an initializer, and without a
  10259. // storage-class specifier or with the storage-class specifier "static",
  10260. // constitutes a tentative definition. Note: A tentative definition with
  10261. // external linkage is valid (C99 6.2.2p5).
  10262. if (!Var->isInvalidDecl()) {
  10263. if (const IncompleteArrayType *ArrayT
  10264. = Context.getAsIncompleteArrayType(Type)) {
  10265. if (RequireCompleteType(Var->getLocation(),
  10266. ArrayT->getElementType(),
  10267. diag::err_illegal_decl_array_incomplete_type))
  10268. Var->setInvalidDecl();
  10269. } else if (Var->getStorageClass() == SC_Static) {
  10270. // C99 6.9.2p3: If the declaration of an identifier for an object is
  10271. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  10272. // declared type shall not be an incomplete type.
  10273. // NOTE: code such as the following
  10274. // static struct s;
  10275. // struct s { int a; };
  10276. // is accepted by gcc. Hence here we issue a warning instead of
  10277. // an error and we do not invalidate the static declaration.
  10278. // NOTE: to avoid multiple warnings, only check the first declaration.
  10279. if (Var->isFirstDecl())
  10280. RequireCompleteType(Var->getLocation(), Type,
  10281. diag::ext_typecheck_decl_incomplete_type);
  10282. }
  10283. }
  10284. // Record the tentative definition; we're done.
  10285. if (!Var->isInvalidDecl())
  10286. TentativeDefinitions.push_back(Var);
  10287. return;
  10288. }
  10289. // Provide a specific diagnostic for uninitialized variable
  10290. // definitions with incomplete array type.
  10291. if (Type->isIncompleteArrayType()) {
  10292. Diag(Var->getLocation(),
  10293. diag::err_typecheck_incomplete_array_needs_initializer);
  10294. Var->setInvalidDecl();
  10295. return;
  10296. }
  10297. // Provide a specific diagnostic for uninitialized variable
  10298. // definitions with reference type.
  10299. if (Type->isReferenceType()) {
  10300. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  10301. << Var->getDeclName()
  10302. << SourceRange(Var->getLocation(), Var->getLocation());
  10303. Var->setInvalidDecl();
  10304. return;
  10305. }
  10306. // Do not attempt to type-check the default initializer for a
  10307. // variable with dependent type.
  10308. if (Type->isDependentType())
  10309. return;
  10310. if (Var->isInvalidDecl())
  10311. return;
  10312. if (!Var->hasAttr<AliasAttr>()) {
  10313. if (RequireCompleteType(Var->getLocation(),
  10314. Context.getBaseElementType(Type),
  10315. diag::err_typecheck_decl_incomplete_type)) {
  10316. Var->setInvalidDecl();
  10317. return;
  10318. }
  10319. } else {
  10320. return;
  10321. }
  10322. // The variable can not have an abstract class type.
  10323. if (RequireNonAbstractType(Var->getLocation(), Type,
  10324. diag::err_abstract_type_in_decl,
  10325. AbstractVariableType)) {
  10326. Var->setInvalidDecl();
  10327. return;
  10328. }
  10329. // Check for jumps past the implicit initializer. C++0x
  10330. // clarifies that this applies to a "variable with automatic
  10331. // storage duration", not a "local variable".
  10332. // C++11 [stmt.dcl]p3
  10333. // A program that jumps from a point where a variable with automatic
  10334. // storage duration is not in scope to a point where it is in scope is
  10335. // ill-formed unless the variable has scalar type, class type with a
  10336. // trivial default constructor and a trivial destructor, a cv-qualified
  10337. // version of one of these types, or an array of one of the preceding
  10338. // types and is declared without an initializer.
  10339. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  10340. if (const RecordType *Record
  10341. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  10342. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  10343. // Mark the function (if we're in one) for further checking even if the
  10344. // looser rules of C++11 do not require such checks, so that we can
  10345. // diagnose incompatibilities with C++98.
  10346. if (!CXXRecord->isPOD())
  10347. setFunctionHasBranchProtectedScope();
  10348. }
  10349. }
  10350. // In OpenCL, we can't initialize objects in the __local address space,
  10351. // even implicitly, so don't synthesize an implicit initializer.
  10352. if (getLangOpts().OpenCL &&
  10353. Var->getType().getAddressSpace() == LangAS::opencl_local)
  10354. return;
  10355. // C++03 [dcl.init]p9:
  10356. // If no initializer is specified for an object, and the
  10357. // object is of (possibly cv-qualified) non-POD class type (or
  10358. // array thereof), the object shall be default-initialized; if
  10359. // the object is of const-qualified type, the underlying class
  10360. // type shall have a user-declared default
  10361. // constructor. Otherwise, if no initializer is specified for
  10362. // a non- static object, the object and its subobjects, if
  10363. // any, have an indeterminate initial value); if the object
  10364. // or any of its subobjects are of const-qualified type, the
  10365. // program is ill-formed.
  10366. // C++0x [dcl.init]p11:
  10367. // If no initializer is specified for an object, the object is
  10368. // default-initialized; [...].
  10369. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  10370. InitializationKind Kind
  10371. = InitializationKind::CreateDefault(Var->getLocation());
  10372. InitializationSequence InitSeq(*this, Entity, Kind, None);
  10373. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  10374. if (Init.isInvalid())
  10375. Var->setInvalidDecl();
  10376. else if (Init.get()) {
  10377. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  10378. // This is important for template substitution.
  10379. Var->setInitStyle(VarDecl::CallInit);
  10380. }
  10381. CheckCompleteVariableDeclaration(Var);
  10382. }
  10383. }
  10384. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  10385. // If there is no declaration, there was an error parsing it. Ignore it.
  10386. if (!D)
  10387. return;
  10388. VarDecl *VD = dyn_cast<VarDecl>(D);
  10389. if (!VD) {
  10390. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  10391. D->setInvalidDecl();
  10392. return;
  10393. }
  10394. VD->setCXXForRangeDecl(true);
  10395. // for-range-declaration cannot be given a storage class specifier.
  10396. int Error = -1;
  10397. switch (VD->getStorageClass()) {
  10398. case SC_None:
  10399. break;
  10400. case SC_Extern:
  10401. Error = 0;
  10402. break;
  10403. case SC_Static:
  10404. Error = 1;
  10405. break;
  10406. case SC_PrivateExtern:
  10407. Error = 2;
  10408. break;
  10409. case SC_Auto:
  10410. Error = 3;
  10411. break;
  10412. case SC_Register:
  10413. Error = 4;
  10414. break;
  10415. }
  10416. if (Error != -1) {
  10417. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  10418. << VD->getDeclName() << Error;
  10419. D->setInvalidDecl();
  10420. }
  10421. }
  10422. StmtResult
  10423. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  10424. IdentifierInfo *Ident,
  10425. ParsedAttributes &Attrs,
  10426. SourceLocation AttrEnd) {
  10427. // C++1y [stmt.iter]p1:
  10428. // A range-based for statement of the form
  10429. // for ( for-range-identifier : for-range-initializer ) statement
  10430. // is equivalent to
  10431. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  10432. DeclSpec DS(Attrs.getPool().getFactory());
  10433. const char *PrevSpec;
  10434. unsigned DiagID;
  10435. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  10436. getPrintingPolicy());
  10437. Declarator D(DS, DeclaratorContext::ForContext);
  10438. D.SetIdentifier(Ident, IdentLoc);
  10439. D.takeAttributes(Attrs, AttrEnd);
  10440. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
  10441. IdentLoc);
  10442. Decl *Var = ActOnDeclarator(S, D);
  10443. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  10444. FinalizeDeclaration(Var);
  10445. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  10446. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  10447. }
  10448. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  10449. if (var->isInvalidDecl()) return;
  10450. if (getLangOpts().OpenCL) {
  10451. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  10452. // initialiser
  10453. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  10454. !var->hasInit()) {
  10455. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  10456. << 1 /*Init*/;
  10457. var->setInvalidDecl();
  10458. return;
  10459. }
  10460. }
  10461. // In Objective-C, don't allow jumps past the implicit initialization of a
  10462. // local retaining variable.
  10463. if (getLangOpts().ObjC &&
  10464. var->hasLocalStorage()) {
  10465. switch (var->getType().getObjCLifetime()) {
  10466. case Qualifiers::OCL_None:
  10467. case Qualifiers::OCL_ExplicitNone:
  10468. case Qualifiers::OCL_Autoreleasing:
  10469. break;
  10470. case Qualifiers::OCL_Weak:
  10471. case Qualifiers::OCL_Strong:
  10472. setFunctionHasBranchProtectedScope();
  10473. break;
  10474. }
  10475. }
  10476. if (var->hasLocalStorage() &&
  10477. var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  10478. setFunctionHasBranchProtectedScope();
  10479. // Warn about externally-visible variables being defined without a
  10480. // prior declaration. We only want to do this for global
  10481. // declarations, but we also specifically need to avoid doing it for
  10482. // class members because the linkage of an anonymous class can
  10483. // change if it's later given a typedef name.
  10484. if (var->isThisDeclarationADefinition() &&
  10485. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  10486. var->isExternallyVisible() && var->hasLinkage() &&
  10487. !var->isInline() && !var->getDescribedVarTemplate() &&
  10488. !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
  10489. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  10490. var->getLocation())) {
  10491. // Find a previous declaration that's not a definition.
  10492. VarDecl *prev = var->getPreviousDecl();
  10493. while (prev && prev->isThisDeclarationADefinition())
  10494. prev = prev->getPreviousDecl();
  10495. if (!prev)
  10496. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  10497. }
  10498. // Cache the result of checking for constant initialization.
  10499. Optional<bool> CacheHasConstInit;
  10500. const Expr *CacheCulprit;
  10501. auto checkConstInit = [&]() mutable {
  10502. if (!CacheHasConstInit)
  10503. CacheHasConstInit = var->getInit()->isConstantInitializer(
  10504. Context, var->getType()->isReferenceType(), &CacheCulprit);
  10505. return *CacheHasConstInit;
  10506. };
  10507. if (var->getTLSKind() == VarDecl::TLS_Static) {
  10508. if (var->getType().isDestructedType()) {
  10509. // GNU C++98 edits for __thread, [basic.start.term]p3:
  10510. // The type of an object with thread storage duration shall not
  10511. // have a non-trivial destructor.
  10512. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  10513. if (getLangOpts().CPlusPlus11)
  10514. Diag(var->getLocation(), diag::note_use_thread_local);
  10515. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  10516. if (!checkConstInit()) {
  10517. // GNU C++98 edits for __thread, [basic.start.init]p4:
  10518. // An object of thread storage duration shall not require dynamic
  10519. // initialization.
  10520. // FIXME: Need strict checking here.
  10521. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  10522. << CacheCulprit->getSourceRange();
  10523. if (getLangOpts().CPlusPlus11)
  10524. Diag(var->getLocation(), diag::note_use_thread_local);
  10525. }
  10526. }
  10527. }
  10528. // Apply section attributes and pragmas to global variables.
  10529. bool GlobalStorage = var->hasGlobalStorage();
  10530. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  10531. !inTemplateInstantiation()) {
  10532. PragmaStack<StringLiteral *> *Stack = nullptr;
  10533. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  10534. if (var->getType().isConstQualified())
  10535. Stack = &ConstSegStack;
  10536. else if (!var->getInit()) {
  10537. Stack = &BSSSegStack;
  10538. SectionFlags |= ASTContext::PSF_Write;
  10539. } else {
  10540. Stack = &DataSegStack;
  10541. SectionFlags |= ASTContext::PSF_Write;
  10542. }
  10543. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  10544. var->addAttr(SectionAttr::CreateImplicit(
  10545. Context, SectionAttr::Declspec_allocate,
  10546. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  10547. }
  10548. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  10549. if (UnifySection(SA->getName(), SectionFlags, var))
  10550. var->dropAttr<SectionAttr>();
  10551. // Apply the init_seg attribute if this has an initializer. If the
  10552. // initializer turns out to not be dynamic, we'll end up ignoring this
  10553. // attribute.
  10554. if (CurInitSeg && var->getInit())
  10555. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  10556. CurInitSegLoc));
  10557. }
  10558. // All the following checks are C++ only.
  10559. if (!getLangOpts().CPlusPlus) {
  10560. // If this variable must be emitted, add it as an initializer for the
  10561. // current module.
  10562. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10563. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10564. return;
  10565. }
  10566. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  10567. CheckCompleteDecompositionDeclaration(DD);
  10568. QualType type = var->getType();
  10569. if (type->isDependentType()) return;
  10570. if (var->hasAttr<BlocksAttr>())
  10571. getCurFunction()->addByrefBlockVar(var);
  10572. Expr *Init = var->getInit();
  10573. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  10574. QualType baseType = Context.getBaseElementType(type);
  10575. if (Init && !Init->isValueDependent()) {
  10576. if (var->isConstexpr()) {
  10577. SmallVector<PartialDiagnosticAt, 8> Notes;
  10578. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  10579. SourceLocation DiagLoc = var->getLocation();
  10580. // If the note doesn't add any useful information other than a source
  10581. // location, fold it into the primary diagnostic.
  10582. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10583. diag::note_invalid_subexpr_in_const_expr) {
  10584. DiagLoc = Notes[0].first;
  10585. Notes.clear();
  10586. }
  10587. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  10588. << var << Init->getSourceRange();
  10589. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10590. Diag(Notes[I].first, Notes[I].second);
  10591. }
  10592. } else if (var->mightBeUsableInConstantExpressions(Context)) {
  10593. // Check whether the initializer of a const variable of integral or
  10594. // enumeration type is an ICE now, since we can't tell whether it was
  10595. // initialized by a constant expression if we check later.
  10596. var->checkInitIsICE();
  10597. }
  10598. // Don't emit further diagnostics about constexpr globals since they
  10599. // were just diagnosed.
  10600. if (!var->isConstexpr() && GlobalStorage &&
  10601. var->hasAttr<RequireConstantInitAttr>()) {
  10602. // FIXME: Need strict checking in C++03 here.
  10603. bool DiagErr = getLangOpts().CPlusPlus11
  10604. ? !var->checkInitIsICE() : !checkConstInit();
  10605. if (DiagErr) {
  10606. auto attr = var->getAttr<RequireConstantInitAttr>();
  10607. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  10608. << Init->getSourceRange();
  10609. Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
  10610. << attr->getRange();
  10611. if (getLangOpts().CPlusPlus11) {
  10612. APValue Value;
  10613. SmallVector<PartialDiagnosticAt, 8> Notes;
  10614. Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
  10615. for (auto &it : Notes)
  10616. Diag(it.first, it.second);
  10617. } else {
  10618. Diag(CacheCulprit->getExprLoc(),
  10619. diag::note_invalid_subexpr_in_const_expr)
  10620. << CacheCulprit->getSourceRange();
  10621. }
  10622. }
  10623. }
  10624. else if (!var->isConstexpr() && IsGlobal &&
  10625. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  10626. var->getLocation())) {
  10627. // Warn about globals which don't have a constant initializer. Don't
  10628. // warn about globals with a non-trivial destructor because we already
  10629. // warned about them.
  10630. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  10631. if (!(RD && !RD->hasTrivialDestructor())) {
  10632. if (!checkConstInit())
  10633. Diag(var->getLocation(), diag::warn_global_constructor)
  10634. << Init->getSourceRange();
  10635. }
  10636. }
  10637. }
  10638. // Require the destructor.
  10639. if (const RecordType *recordType = baseType->getAs<RecordType>())
  10640. FinalizeVarWithDestructor(var, recordType);
  10641. // If this variable must be emitted, add it as an initializer for the current
  10642. // module.
  10643. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10644. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10645. }
  10646. /// Determines if a variable's alignment is dependent.
  10647. static bool hasDependentAlignment(VarDecl *VD) {
  10648. if (VD->getType()->isDependentType())
  10649. return true;
  10650. for (auto *I : VD->specific_attrs<AlignedAttr>())
  10651. if (I->isAlignmentDependent())
  10652. return true;
  10653. return false;
  10654. }
  10655. /// Check if VD needs to be dllexport/dllimport due to being in a
  10656. /// dllexport/import function.
  10657. void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
  10658. assert(VD->isStaticLocal());
  10659. auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  10660. // Find outermost function when VD is in lambda function.
  10661. while (FD && !getDLLAttr(FD) &&
  10662. !FD->hasAttr<DLLExportStaticLocalAttr>() &&
  10663. !FD->hasAttr<DLLImportStaticLocalAttr>()) {
  10664. FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
  10665. }
  10666. if (!FD)
  10667. return;
  10668. // Static locals inherit dll attributes from their function.
  10669. if (Attr *A = getDLLAttr(FD)) {
  10670. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  10671. NewAttr->setInherited(true);
  10672. VD->addAttr(NewAttr);
  10673. } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
  10674. auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
  10675. getASTContext(),
  10676. A->getSpellingListIndex());
  10677. NewAttr->setInherited(true);
  10678. VD->addAttr(NewAttr);
  10679. // Export this function to enforce exporting this static variable even
  10680. // if it is not used in this compilation unit.
  10681. if (!FD->hasAttr<DLLExportAttr>())
  10682. FD->addAttr(NewAttr);
  10683. } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
  10684. auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
  10685. getASTContext(),
  10686. A->getSpellingListIndex());
  10687. NewAttr->setInherited(true);
  10688. VD->addAttr(NewAttr);
  10689. }
  10690. }
  10691. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  10692. /// any semantic actions necessary after any initializer has been attached.
  10693. void Sema::FinalizeDeclaration(Decl *ThisDecl) {
  10694. // Note that we are no longer parsing the initializer for this declaration.
  10695. ParsingInitForAutoVars.erase(ThisDecl);
  10696. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  10697. if (!VD)
  10698. return;
  10699. // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
  10700. if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
  10701. !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
  10702. if (PragmaClangBSSSection.Valid)
  10703. VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
  10704. PragmaClangBSSSection.SectionName,
  10705. PragmaClangBSSSection.PragmaLocation));
  10706. if (PragmaClangDataSection.Valid)
  10707. VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
  10708. PragmaClangDataSection.SectionName,
  10709. PragmaClangDataSection.PragmaLocation));
  10710. if (PragmaClangRodataSection.Valid)
  10711. VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
  10712. PragmaClangRodataSection.SectionName,
  10713. PragmaClangRodataSection.PragmaLocation));
  10714. }
  10715. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  10716. for (auto *BD : DD->bindings()) {
  10717. FinalizeDeclaration(BD);
  10718. }
  10719. }
  10720. checkAttributesAfterMerging(*this, *VD);
  10721. // Perform TLS alignment check here after attributes attached to the variable
  10722. // which may affect the alignment have been processed. Only perform the check
  10723. // if the target has a maximum TLS alignment (zero means no constraints).
  10724. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  10725. // Protect the check so that it's not performed on dependent types and
  10726. // dependent alignments (we can't determine the alignment in that case).
  10727. if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
  10728. !VD->isInvalidDecl()) {
  10729. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  10730. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  10731. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  10732. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  10733. << (unsigned)MaxAlignChars.getQuantity();
  10734. }
  10735. }
  10736. }
  10737. if (VD->isStaticLocal()) {
  10738. CheckStaticLocalForDllExport(VD);
  10739. if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  10740. // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
  10741. // function, only __shared__ variables or variables without any device
  10742. // memory qualifiers may be declared with static storage class.
  10743. // Note: It is unclear how a function-scope non-const static variable
  10744. // without device memory qualifier is implemented, therefore only static
  10745. // const variable without device memory qualifier is allowed.
  10746. [&]() {
  10747. if (!getLangOpts().CUDA)
  10748. return;
  10749. if (VD->hasAttr<CUDASharedAttr>())
  10750. return;
  10751. if (VD->getType().isConstQualified() &&
  10752. !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  10753. return;
  10754. if (CUDADiagIfDeviceCode(VD->getLocation(),
  10755. diag::err_device_static_local_var)
  10756. << CurrentCUDATarget())
  10757. VD->setInvalidDecl();
  10758. }();
  10759. }
  10760. }
  10761. // Perform check for initializers of device-side global variables.
  10762. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  10763. // 7.5). We must also apply the same checks to all __shared__
  10764. // variables whether they are local or not. CUDA also allows
  10765. // constant initializers for __constant__ and __device__ variables.
  10766. if (getLangOpts().CUDA)
  10767. checkAllowedCUDAInitializer(VD);
  10768. // Grab the dllimport or dllexport attribute off of the VarDecl.
  10769. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  10770. // Imported static data members cannot be defined out-of-line.
  10771. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  10772. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  10773. VD->isThisDeclarationADefinition()) {
  10774. // We allow definitions of dllimport class template static data members
  10775. // with a warning.
  10776. CXXRecordDecl *Context =
  10777. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  10778. bool IsClassTemplateMember =
  10779. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  10780. Context->getDescribedClassTemplate();
  10781. Diag(VD->getLocation(),
  10782. IsClassTemplateMember
  10783. ? diag::warn_attribute_dllimport_static_field_definition
  10784. : diag::err_attribute_dllimport_static_field_definition);
  10785. Diag(IA->getLocation(), diag::note_attribute);
  10786. if (!IsClassTemplateMember)
  10787. VD->setInvalidDecl();
  10788. }
  10789. }
  10790. // dllimport/dllexport variables cannot be thread local, their TLS index
  10791. // isn't exported with the variable.
  10792. if (DLLAttr && VD->getTLSKind()) {
  10793. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  10794. if (F && getDLLAttr(F)) {
  10795. assert(VD->isStaticLocal());
  10796. // But if this is a static local in a dlimport/dllexport function, the
  10797. // function will never be inlined, which means the var would never be
  10798. // imported, so having it marked import/export is safe.
  10799. } else {
  10800. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  10801. << DLLAttr;
  10802. VD->setInvalidDecl();
  10803. }
  10804. }
  10805. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  10806. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  10807. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  10808. VD->dropAttr<UsedAttr>();
  10809. }
  10810. }
  10811. const DeclContext *DC = VD->getDeclContext();
  10812. // If there's a #pragma GCC visibility in scope, and this isn't a class
  10813. // member, set the visibility of this variable.
  10814. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  10815. AddPushedVisibilityAttribute(VD);
  10816. // FIXME: Warn on unused var template partial specializations.
  10817. if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
  10818. MarkUnusedFileScopedDecl(VD);
  10819. // Now we have parsed the initializer and can update the table of magic
  10820. // tag values.
  10821. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  10822. !VD->getType()->isIntegralOrEnumerationType())
  10823. return;
  10824. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  10825. const Expr *MagicValueExpr = VD->getInit();
  10826. if (!MagicValueExpr) {
  10827. continue;
  10828. }
  10829. llvm::APSInt MagicValueInt;
  10830. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  10831. Diag(I->getRange().getBegin(),
  10832. diag::err_type_tag_for_datatype_not_ice)
  10833. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  10834. continue;
  10835. }
  10836. if (MagicValueInt.getActiveBits() > 64) {
  10837. Diag(I->getRange().getBegin(),
  10838. diag::err_type_tag_for_datatype_too_large)
  10839. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  10840. continue;
  10841. }
  10842. uint64_t MagicValue = MagicValueInt.getZExtValue();
  10843. RegisterTypeTagForDatatype(I->getArgumentKind(),
  10844. MagicValue,
  10845. I->getMatchingCType(),
  10846. I->getLayoutCompatible(),
  10847. I->getMustBeNull());
  10848. }
  10849. }
  10850. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  10851. auto *VD = dyn_cast<VarDecl>(DD);
  10852. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  10853. }
  10854. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  10855. ArrayRef<Decl *> Group) {
  10856. SmallVector<Decl*, 8> Decls;
  10857. if (DS.isTypeSpecOwned())
  10858. Decls.push_back(DS.getRepAsDecl());
  10859. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  10860. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  10861. bool DiagnosedMultipleDecomps = false;
  10862. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  10863. bool DiagnosedNonDeducedAuto = false;
  10864. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  10865. if (Decl *D = Group[i]) {
  10866. // For declarators, there are some additional syntactic-ish checks we need
  10867. // to perform.
  10868. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  10869. if (!FirstDeclaratorInGroup)
  10870. FirstDeclaratorInGroup = DD;
  10871. if (!FirstDecompDeclaratorInGroup)
  10872. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  10873. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  10874. !hasDeducedAuto(DD))
  10875. FirstNonDeducedAutoInGroup = DD;
  10876. if (FirstDeclaratorInGroup != DD) {
  10877. // A decomposition declaration cannot be combined with any other
  10878. // declaration in the same group.
  10879. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  10880. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  10881. diag::err_decomp_decl_not_alone)
  10882. << FirstDeclaratorInGroup->getSourceRange()
  10883. << DD->getSourceRange();
  10884. DiagnosedMultipleDecomps = true;
  10885. }
  10886. // A declarator that uses 'auto' in any way other than to declare a
  10887. // variable with a deduced type cannot be combined with any other
  10888. // declarator in the same group.
  10889. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  10890. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  10891. diag::err_auto_non_deduced_not_alone)
  10892. << FirstNonDeducedAutoInGroup->getType()
  10893. ->hasAutoForTrailingReturnType()
  10894. << FirstDeclaratorInGroup->getSourceRange()
  10895. << DD->getSourceRange();
  10896. DiagnosedNonDeducedAuto = true;
  10897. }
  10898. }
  10899. }
  10900. Decls.push_back(D);
  10901. }
  10902. }
  10903. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  10904. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  10905. handleTagNumbering(Tag, S);
  10906. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  10907. getLangOpts().CPlusPlus)
  10908. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  10909. }
  10910. }
  10911. return BuildDeclaratorGroup(Decls);
  10912. }
  10913. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  10914. /// group, performing any necessary semantic checking.
  10915. Sema::DeclGroupPtrTy
  10916. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  10917. // C++14 [dcl.spec.auto]p7: (DR1347)
  10918. // If the type that replaces the placeholder type is not the same in each
  10919. // deduction, the program is ill-formed.
  10920. if (Group.size() > 1) {
  10921. QualType Deduced;
  10922. VarDecl *DeducedDecl = nullptr;
  10923. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  10924. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  10925. if (!D || D->isInvalidDecl())
  10926. break;
  10927. DeducedType *DT = D->getType()->getContainedDeducedType();
  10928. if (!DT || DT->getDeducedType().isNull())
  10929. continue;
  10930. if (Deduced.isNull()) {
  10931. Deduced = DT->getDeducedType();
  10932. DeducedDecl = D;
  10933. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  10934. auto *AT = dyn_cast<AutoType>(DT);
  10935. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  10936. diag::err_auto_different_deductions)
  10937. << (AT ? (unsigned)AT->getKeyword() : 3)
  10938. << Deduced << DeducedDecl->getDeclName()
  10939. << DT->getDeducedType() << D->getDeclName()
  10940. << DeducedDecl->getInit()->getSourceRange()
  10941. << D->getInit()->getSourceRange();
  10942. D->setInvalidDecl();
  10943. break;
  10944. }
  10945. }
  10946. }
  10947. ActOnDocumentableDecls(Group);
  10948. return DeclGroupPtrTy::make(
  10949. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  10950. }
  10951. void Sema::ActOnDocumentableDecl(Decl *D) {
  10952. ActOnDocumentableDecls(D);
  10953. }
  10954. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  10955. // Don't parse the comment if Doxygen diagnostics are ignored.
  10956. if (Group.empty() || !Group[0])
  10957. return;
  10958. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  10959. Group[0]->getLocation()) &&
  10960. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  10961. Group[0]->getLocation()))
  10962. return;
  10963. if (Group.size() >= 2) {
  10964. // This is a decl group. Normally it will contain only declarations
  10965. // produced from declarator list. But in case we have any definitions or
  10966. // additional declaration references:
  10967. // 'typedef struct S {} S;'
  10968. // 'typedef struct S *S;'
  10969. // 'struct S *pS;'
  10970. // FinalizeDeclaratorGroup adds these as separate declarations.
  10971. Decl *MaybeTagDecl = Group[0];
  10972. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  10973. Group = Group.slice(1);
  10974. }
  10975. }
  10976. // See if there are any new comments that are not attached to a decl.
  10977. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  10978. if (!Comments.empty() &&
  10979. !Comments.back()->isAttached()) {
  10980. // There is at least one comment that not attached to a decl.
  10981. // Maybe it should be attached to one of these decls?
  10982. //
  10983. // Note that this way we pick up not only comments that precede the
  10984. // declaration, but also comments that *follow* the declaration -- thanks to
  10985. // the lookahead in the lexer: we've consumed the semicolon and looked
  10986. // ahead through comments.
  10987. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  10988. Context.getCommentForDecl(Group[i], &PP);
  10989. }
  10990. }
  10991. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  10992. /// to introduce parameters into function prototype scope.
  10993. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  10994. const DeclSpec &DS = D.getDeclSpec();
  10995. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  10996. // C++03 [dcl.stc]p2 also permits 'auto'.
  10997. StorageClass SC = SC_None;
  10998. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  10999. SC = SC_Register;
  11000. // In C++11, the 'register' storage class specifier is deprecated.
  11001. // In C++17, it is not allowed, but we tolerate it as an extension.
  11002. if (getLangOpts().CPlusPlus11) {
  11003. Diag(DS.getStorageClassSpecLoc(),
  11004. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  11005. : diag::warn_deprecated_register)
  11006. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  11007. }
  11008. } else if (getLangOpts().CPlusPlus &&
  11009. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  11010. SC = SC_Auto;
  11011. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  11012. Diag(DS.getStorageClassSpecLoc(),
  11013. diag::err_invalid_storage_class_in_func_decl);
  11014. D.getMutableDeclSpec().ClearStorageClassSpecs();
  11015. }
  11016. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  11017. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  11018. << DeclSpec::getSpecifierName(TSCS);
  11019. if (DS.isInlineSpecified())
  11020. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  11021. << getLangOpts().CPlusPlus17;
  11022. if (DS.isConstexprSpecified())
  11023. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  11024. << 0;
  11025. DiagnoseFunctionSpecifiers(DS);
  11026. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11027. QualType parmDeclType = TInfo->getType();
  11028. if (getLangOpts().CPlusPlus) {
  11029. // Check that there are no default arguments inside the type of this
  11030. // parameter.
  11031. CheckExtraCXXDefaultArguments(D);
  11032. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  11033. if (D.getCXXScopeSpec().isSet()) {
  11034. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  11035. << D.getCXXScopeSpec().getRange();
  11036. D.getCXXScopeSpec().clear();
  11037. }
  11038. }
  11039. // Ensure we have a valid name
  11040. IdentifierInfo *II = nullptr;
  11041. if (D.hasName()) {
  11042. II = D.getIdentifier();
  11043. if (!II) {
  11044. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  11045. << GetNameForDeclarator(D).getName();
  11046. D.setInvalidType(true);
  11047. }
  11048. }
  11049. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  11050. if (II) {
  11051. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  11052. ForVisibleRedeclaration);
  11053. LookupName(R, S);
  11054. if (R.isSingleResult()) {
  11055. NamedDecl *PrevDecl = R.getFoundDecl();
  11056. if (PrevDecl->isTemplateParameter()) {
  11057. // Maybe we will complain about the shadowed template parameter.
  11058. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11059. // Just pretend that we didn't see the previous declaration.
  11060. PrevDecl = nullptr;
  11061. } else if (S->isDeclScope(PrevDecl)) {
  11062. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  11063. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  11064. // Recover by removing the name
  11065. II = nullptr;
  11066. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  11067. D.setInvalidType(true);
  11068. }
  11069. }
  11070. }
  11071. // Temporarily put parameter variables in the translation unit, not
  11072. // the enclosing context. This prevents them from accidentally
  11073. // looking like class members in C++.
  11074. ParmVarDecl *New =
  11075. CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
  11076. D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
  11077. if (D.isInvalidType())
  11078. New->setInvalidDecl();
  11079. assert(S->isFunctionPrototypeScope());
  11080. assert(S->getFunctionPrototypeDepth() >= 1);
  11081. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  11082. S->getNextFunctionPrototypeIndex());
  11083. // Add the parameter declaration into this scope.
  11084. S->AddDecl(New);
  11085. if (II)
  11086. IdResolver.AddDecl(New);
  11087. ProcessDeclAttributes(S, New, D);
  11088. if (D.getDeclSpec().isModulePrivateSpecified())
  11089. Diag(New->getLocation(), diag::err_module_private_local)
  11090. << 1 << New->getDeclName()
  11091. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  11092. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  11093. if (New->hasAttr<BlocksAttr>()) {
  11094. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  11095. }
  11096. return New;
  11097. }
  11098. /// Synthesizes a variable for a parameter arising from a
  11099. /// typedef.
  11100. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  11101. SourceLocation Loc,
  11102. QualType T) {
  11103. /* FIXME: setting StartLoc == Loc.
  11104. Would it be worth to modify callers so as to provide proper source
  11105. location for the unnamed parameters, embedding the parameter's type? */
  11106. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  11107. T, Context.getTrivialTypeSourceInfo(T, Loc),
  11108. SC_None, nullptr);
  11109. Param->setImplicit();
  11110. return Param;
  11111. }
  11112. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  11113. // Don't diagnose unused-parameter errors in template instantiations; we
  11114. // will already have done so in the template itself.
  11115. if (inTemplateInstantiation())
  11116. return;
  11117. for (const ParmVarDecl *Parameter : Parameters) {
  11118. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  11119. !Parameter->hasAttr<UnusedAttr>()) {
  11120. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  11121. << Parameter->getDeclName();
  11122. }
  11123. }
  11124. }
  11125. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  11126. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  11127. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  11128. return;
  11129. // Warn if the return value is pass-by-value and larger than the specified
  11130. // threshold.
  11131. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  11132. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  11133. if (Size > LangOpts.NumLargeByValueCopy)
  11134. Diag(D->getLocation(), diag::warn_return_value_size)
  11135. << D->getDeclName() << Size;
  11136. }
  11137. // Warn if any parameter is pass-by-value and larger than the specified
  11138. // threshold.
  11139. for (const ParmVarDecl *Parameter : Parameters) {
  11140. QualType T = Parameter->getType();
  11141. if (T->isDependentType() || !T.isPODType(Context))
  11142. continue;
  11143. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  11144. if (Size > LangOpts.NumLargeByValueCopy)
  11145. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  11146. << Parameter->getDeclName() << Size;
  11147. }
  11148. }
  11149. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  11150. SourceLocation NameLoc, IdentifierInfo *Name,
  11151. QualType T, TypeSourceInfo *TSInfo,
  11152. StorageClass SC) {
  11153. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  11154. if (getLangOpts().ObjCAutoRefCount &&
  11155. T.getObjCLifetime() == Qualifiers::OCL_None &&
  11156. T->isObjCLifetimeType()) {
  11157. Qualifiers::ObjCLifetime lifetime;
  11158. // Special cases for arrays:
  11159. // - if it's const, use __unsafe_unretained
  11160. // - otherwise, it's an error
  11161. if (T->isArrayType()) {
  11162. if (!T.isConstQualified()) {
  11163. if (DelayedDiagnostics.shouldDelayDiagnostics())
  11164. DelayedDiagnostics.add(
  11165. sema::DelayedDiagnostic::makeForbiddenType(
  11166. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  11167. else
  11168. Diag(NameLoc, diag::err_arc_array_param_no_ownership)
  11169. << TSInfo->getTypeLoc().getSourceRange();
  11170. }
  11171. lifetime = Qualifiers::OCL_ExplicitNone;
  11172. } else {
  11173. lifetime = T->getObjCARCImplicitLifetime();
  11174. }
  11175. T = Context.getLifetimeQualifiedType(T, lifetime);
  11176. }
  11177. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  11178. Context.getAdjustedParameterType(T),
  11179. TSInfo, SC, nullptr);
  11180. // Parameters can not be abstract class types.
  11181. // For record types, this is done by the AbstractClassUsageDiagnoser once
  11182. // the class has been completely parsed.
  11183. if (!CurContext->isRecord() &&
  11184. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  11185. AbstractParamType))
  11186. New->setInvalidDecl();
  11187. // Parameter declarators cannot be interface types. All ObjC objects are
  11188. // passed by reference.
  11189. if (T->isObjCObjectType()) {
  11190. SourceLocation TypeEndLoc =
  11191. getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
  11192. Diag(NameLoc,
  11193. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  11194. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  11195. T = Context.getObjCObjectPointerType(T);
  11196. New->setType(T);
  11197. }
  11198. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  11199. // duration shall not be qualified by an address-space qualifier."
  11200. // Since all parameters have automatic store duration, they can not have
  11201. // an address space.
  11202. if (T.getAddressSpace() != LangAS::Default &&
  11203. // OpenCL allows function arguments declared to be an array of a type
  11204. // to be qualified with an address space.
  11205. !(getLangOpts().OpenCL &&
  11206. (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
  11207. Diag(NameLoc, diag::err_arg_with_address_space);
  11208. New->setInvalidDecl();
  11209. }
  11210. return New;
  11211. }
  11212. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  11213. SourceLocation LocAfterDecls) {
  11214. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  11215. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  11216. // for a K&R function.
  11217. if (!FTI.hasPrototype) {
  11218. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  11219. --i;
  11220. if (FTI.Params[i].Param == nullptr) {
  11221. SmallString<256> Code;
  11222. llvm::raw_svector_ostream(Code)
  11223. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  11224. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  11225. << FTI.Params[i].Ident
  11226. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  11227. // Implicitly declare the argument as type 'int' for lack of a better
  11228. // type.
  11229. AttributeFactory attrs;
  11230. DeclSpec DS(attrs);
  11231. const char* PrevSpec; // unused
  11232. unsigned DiagID; // unused
  11233. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  11234. DiagID, Context.getPrintingPolicy());
  11235. // Use the identifier location for the type source range.
  11236. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  11237. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  11238. Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
  11239. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  11240. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  11241. }
  11242. }
  11243. }
  11244. }
  11245. Decl *
  11246. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  11247. MultiTemplateParamsArg TemplateParameterLists,
  11248. SkipBodyInfo *SkipBody) {
  11249. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  11250. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  11251. Scope *ParentScope = FnBodyScope->getParent();
  11252. D.setFunctionDefinitionKind(FDK_Definition);
  11253. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  11254. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  11255. }
  11256. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  11257. Consumer.HandleInlineFunctionDefinition(D);
  11258. }
  11259. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  11260. const FunctionDecl*& PossibleZeroParamPrototype) {
  11261. // Don't warn about invalid declarations.
  11262. if (FD->isInvalidDecl())
  11263. return false;
  11264. // Or declarations that aren't global.
  11265. if (!FD->isGlobal())
  11266. return false;
  11267. // Don't warn about C++ member functions.
  11268. if (isa<CXXMethodDecl>(FD))
  11269. return false;
  11270. // Don't warn about 'main'.
  11271. if (FD->isMain())
  11272. return false;
  11273. // Don't warn about inline functions.
  11274. if (FD->isInlined())
  11275. return false;
  11276. // Don't warn about function templates.
  11277. if (FD->getDescribedFunctionTemplate())
  11278. return false;
  11279. // Don't warn about function template specializations.
  11280. if (FD->isFunctionTemplateSpecialization())
  11281. return false;
  11282. // Don't warn for OpenCL kernels.
  11283. if (FD->hasAttr<OpenCLKernelAttr>())
  11284. return false;
  11285. // Don't warn on explicitly deleted functions.
  11286. if (FD->isDeleted())
  11287. return false;
  11288. bool MissingPrototype = true;
  11289. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  11290. Prev; Prev = Prev->getPreviousDecl()) {
  11291. // Ignore any declarations that occur in function or method
  11292. // scope, because they aren't visible from the header.
  11293. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  11294. continue;
  11295. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  11296. if (FD->getNumParams() == 0)
  11297. PossibleZeroParamPrototype = Prev;
  11298. break;
  11299. }
  11300. return MissingPrototype;
  11301. }
  11302. void
  11303. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  11304. const FunctionDecl *EffectiveDefinition,
  11305. SkipBodyInfo *SkipBody) {
  11306. const FunctionDecl *Definition = EffectiveDefinition;
  11307. if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
  11308. // If this is a friend function defined in a class template, it does not
  11309. // have a body until it is used, nevertheless it is a definition, see
  11310. // [temp.inst]p2:
  11311. //
  11312. // ... for the purpose of determining whether an instantiated redeclaration
  11313. // is valid according to [basic.def.odr] and [class.mem], a declaration that
  11314. // corresponds to a definition in the template is considered to be a
  11315. // definition.
  11316. //
  11317. // The following code must produce redefinition error:
  11318. //
  11319. // template<typename T> struct C20 { friend void func_20() {} };
  11320. // C20<int> c20i;
  11321. // void func_20() {}
  11322. //
  11323. for (auto I : FD->redecls()) {
  11324. if (I != FD && !I->isInvalidDecl() &&
  11325. I->getFriendObjectKind() != Decl::FOK_None) {
  11326. if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
  11327. if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
  11328. // A merged copy of the same function, instantiated as a member of
  11329. // the same class, is OK.
  11330. if (declaresSameEntity(OrigFD, Original) &&
  11331. declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
  11332. cast<Decl>(FD->getLexicalDeclContext())))
  11333. continue;
  11334. }
  11335. if (Original->isThisDeclarationADefinition()) {
  11336. Definition = I;
  11337. break;
  11338. }
  11339. }
  11340. }
  11341. }
  11342. }
  11343. if (!Definition)
  11344. // Similar to friend functions a friend function template may be a
  11345. // definition and do not have a body if it is instantiated in a class
  11346. // template.
  11347. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
  11348. for (auto I : FTD->redecls()) {
  11349. auto D = cast<FunctionTemplateDecl>(I);
  11350. if (D != FTD) {
  11351. assert(!D->isThisDeclarationADefinition() &&
  11352. "More than one definition in redeclaration chain");
  11353. if (D->getFriendObjectKind() != Decl::FOK_None)
  11354. if (FunctionTemplateDecl *FT =
  11355. D->getInstantiatedFromMemberTemplate()) {
  11356. if (FT->isThisDeclarationADefinition()) {
  11357. Definition = D->getTemplatedDecl();
  11358. break;
  11359. }
  11360. }
  11361. }
  11362. }
  11363. }
  11364. if (!Definition)
  11365. return;
  11366. if (canRedefineFunction(Definition, getLangOpts()))
  11367. return;
  11368. // Don't emit an error when this is redefinition of a typo-corrected
  11369. // definition.
  11370. if (TypoCorrectedFunctionDefinitions.count(Definition))
  11371. return;
  11372. // If we don't have a visible definition of the function, and it's inline or
  11373. // a template, skip the new definition.
  11374. if (SkipBody && !hasVisibleDefinition(Definition) &&
  11375. (Definition->getFormalLinkage() == InternalLinkage ||
  11376. Definition->isInlined() ||
  11377. Definition->getDescribedFunctionTemplate() ||
  11378. Definition->getNumTemplateParameterLists())) {
  11379. SkipBody->ShouldSkip = true;
  11380. SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
  11381. if (auto *TD = Definition->getDescribedFunctionTemplate())
  11382. makeMergedDefinitionVisible(TD);
  11383. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
  11384. return;
  11385. }
  11386. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  11387. Definition->getStorageClass() == SC_Extern)
  11388. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  11389. << FD->getDeclName() << getLangOpts().CPlusPlus;
  11390. else
  11391. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  11392. Diag(Definition->getLocation(), diag::note_previous_definition);
  11393. FD->setInvalidDecl();
  11394. }
  11395. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  11396. Sema &S) {
  11397. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  11398. LambdaScopeInfo *LSI = S.PushLambdaScope();
  11399. LSI->CallOperator = CallOperator;
  11400. LSI->Lambda = LambdaClass;
  11401. LSI->ReturnType = CallOperator->getReturnType();
  11402. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  11403. if (LCD == LCD_None)
  11404. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  11405. else if (LCD == LCD_ByCopy)
  11406. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  11407. else if (LCD == LCD_ByRef)
  11408. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  11409. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  11410. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  11411. LSI->Mutable = !CallOperator->isConst();
  11412. // Add the captures to the LSI so they can be noted as already
  11413. // captured within tryCaptureVar.
  11414. auto I = LambdaClass->field_begin();
  11415. for (const auto &C : LambdaClass->captures()) {
  11416. if (C.capturesVariable()) {
  11417. VarDecl *VD = C.getCapturedVar();
  11418. if (VD->isInitCapture())
  11419. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  11420. QualType CaptureType = VD->getType();
  11421. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  11422. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  11423. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  11424. /*EllipsisLoc*/C.isPackExpansion()
  11425. ? C.getEllipsisLoc() : SourceLocation(),
  11426. CaptureType, /*Invalid*/false);
  11427. } else if (C.capturesThis()) {
  11428. LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
  11429. C.getCaptureKind() == LCK_StarThis);
  11430. } else {
  11431. LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
  11432. I->getType());
  11433. }
  11434. ++I;
  11435. }
  11436. }
  11437. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  11438. SkipBodyInfo *SkipBody) {
  11439. if (!D) {
  11440. // Parsing the function declaration failed in some way. Push on a fake scope
  11441. // anyway so we can try to parse the function body.
  11442. PushFunctionScope();
  11443. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11444. return D;
  11445. }
  11446. FunctionDecl *FD = nullptr;
  11447. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  11448. FD = FunTmpl->getTemplatedDecl();
  11449. else
  11450. FD = cast<FunctionDecl>(D);
  11451. // Do not push if it is a lambda because one is already pushed when building
  11452. // the lambda in ActOnStartOfLambdaDefinition().
  11453. if (!isLambdaCallOperator(FD))
  11454. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11455. // Check for defining attributes before the check for redefinition.
  11456. if (const auto *Attr = FD->getAttr<AliasAttr>()) {
  11457. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
  11458. FD->dropAttr<AliasAttr>();
  11459. FD->setInvalidDecl();
  11460. }
  11461. if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
  11462. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
  11463. FD->dropAttr<IFuncAttr>();
  11464. FD->setInvalidDecl();
  11465. }
  11466. // See if this is a redefinition. If 'will have body' is already set, then
  11467. // these checks were already performed when it was set.
  11468. if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
  11469. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  11470. // If we're skipping the body, we're done. Don't enter the scope.
  11471. if (SkipBody && SkipBody->ShouldSkip)
  11472. return D;
  11473. }
  11474. // Mark this function as "will have a body eventually". This lets users to
  11475. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  11476. // this function.
  11477. FD->setWillHaveBody();
  11478. // If we are instantiating a generic lambda call operator, push
  11479. // a LambdaScopeInfo onto the function stack. But use the information
  11480. // that's already been calculated (ActOnLambdaExpr) to prime the current
  11481. // LambdaScopeInfo.
  11482. // When the template operator is being specialized, the LambdaScopeInfo,
  11483. // has to be properly restored so that tryCaptureVariable doesn't try
  11484. // and capture any new variables. In addition when calculating potential
  11485. // captures during transformation of nested lambdas, it is necessary to
  11486. // have the LSI properly restored.
  11487. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  11488. assert(inTemplateInstantiation() &&
  11489. "There should be an active template instantiation on the stack "
  11490. "when instantiating a generic lambda!");
  11491. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  11492. } else {
  11493. // Enter a new function scope
  11494. PushFunctionScope();
  11495. }
  11496. // Builtin functions cannot be defined.
  11497. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11498. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  11499. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  11500. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  11501. FD->setInvalidDecl();
  11502. }
  11503. }
  11504. // The return type of a function definition must be complete
  11505. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  11506. QualType ResultType = FD->getReturnType();
  11507. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  11508. !FD->isInvalidDecl() &&
  11509. RequireCompleteType(FD->getLocation(), ResultType,
  11510. diag::err_func_def_incomplete_result))
  11511. FD->setInvalidDecl();
  11512. if (FnBodyScope)
  11513. PushDeclContext(FnBodyScope, FD);
  11514. // Check the validity of our function parameters
  11515. CheckParmsForFunctionDef(FD->parameters(),
  11516. /*CheckParameterNames=*/true);
  11517. // Add non-parameter declarations already in the function to the current
  11518. // scope.
  11519. if (FnBodyScope) {
  11520. for (Decl *NPD : FD->decls()) {
  11521. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  11522. if (!NonParmDecl)
  11523. continue;
  11524. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  11525. "parameters should not be in newly created FD yet");
  11526. // If the decl has a name, make it accessible in the current scope.
  11527. if (NonParmDecl->getDeclName())
  11528. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  11529. // Similarly, dive into enums and fish their constants out, making them
  11530. // accessible in this scope.
  11531. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  11532. for (auto *EI : ED->enumerators())
  11533. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  11534. }
  11535. }
  11536. }
  11537. // Introduce our parameters into the function scope
  11538. for (auto Param : FD->parameters()) {
  11539. Param->setOwningFunction(FD);
  11540. // If this has an identifier, add it to the scope stack.
  11541. if (Param->getIdentifier() && FnBodyScope) {
  11542. CheckShadow(FnBodyScope, Param);
  11543. PushOnScopeChains(Param, FnBodyScope);
  11544. }
  11545. }
  11546. // Ensure that the function's exception specification is instantiated.
  11547. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  11548. ResolveExceptionSpec(D->getLocation(), FPT);
  11549. // dllimport cannot be applied to non-inline function definitions.
  11550. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  11551. !FD->isTemplateInstantiation()) {
  11552. assert(!FD->hasAttr<DLLExportAttr>());
  11553. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  11554. FD->setInvalidDecl();
  11555. return D;
  11556. }
  11557. // We want to attach documentation to original Decl (which might be
  11558. // a function template).
  11559. ActOnDocumentableDecl(D);
  11560. if (getCurLexicalContext()->isObjCContainer() &&
  11561. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  11562. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  11563. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  11564. return D;
  11565. }
  11566. /// Given the set of return statements within a function body,
  11567. /// compute the variables that are subject to the named return value
  11568. /// optimization.
  11569. ///
  11570. /// Each of the variables that is subject to the named return value
  11571. /// optimization will be marked as NRVO variables in the AST, and any
  11572. /// return statement that has a marked NRVO variable as its NRVO candidate can
  11573. /// use the named return value optimization.
  11574. ///
  11575. /// This function applies a very simplistic algorithm for NRVO: if every return
  11576. /// statement in the scope of a variable has the same NRVO candidate, that
  11577. /// candidate is an NRVO variable.
  11578. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  11579. ReturnStmt **Returns = Scope->Returns.data();
  11580. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  11581. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  11582. if (!NRVOCandidate->isNRVOVariable())
  11583. Returns[I]->setNRVOCandidate(nullptr);
  11584. }
  11585. }
  11586. }
  11587. bool Sema::canDelayFunctionBody(const Declarator &D) {
  11588. // We can't delay parsing the body of a constexpr function template (yet).
  11589. if (D.getDeclSpec().isConstexprSpecified())
  11590. return false;
  11591. // We can't delay parsing the body of a function template with a deduced
  11592. // return type (yet).
  11593. if (D.getDeclSpec().hasAutoTypeSpec()) {
  11594. // If the placeholder introduces a non-deduced trailing return type,
  11595. // we can still delay parsing it.
  11596. if (D.getNumTypeObjects()) {
  11597. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  11598. if (Outer.Kind == DeclaratorChunk::Function &&
  11599. Outer.Fun.hasTrailingReturnType()) {
  11600. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  11601. return Ty.isNull() || !Ty->isUndeducedType();
  11602. }
  11603. }
  11604. return false;
  11605. }
  11606. return true;
  11607. }
  11608. bool Sema::canSkipFunctionBody(Decl *D) {
  11609. // We cannot skip the body of a function (or function template) which is
  11610. // constexpr, since we may need to evaluate its body in order to parse the
  11611. // rest of the file.
  11612. // We cannot skip the body of a function with an undeduced return type,
  11613. // because any callers of that function need to know the type.
  11614. if (const FunctionDecl *FD = D->getAsFunction()) {
  11615. if (FD->isConstexpr())
  11616. return false;
  11617. // We can't simply call Type::isUndeducedType here, because inside template
  11618. // auto can be deduced to a dependent type, which is not considered
  11619. // "undeduced".
  11620. if (FD->getReturnType()->getContainedDeducedType())
  11621. return false;
  11622. }
  11623. return Consumer.shouldSkipFunctionBody(D);
  11624. }
  11625. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  11626. if (!Decl)
  11627. return nullptr;
  11628. if (FunctionDecl *FD = Decl->getAsFunction())
  11629. FD->setHasSkippedBody();
  11630. else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
  11631. MD->setHasSkippedBody();
  11632. return Decl;
  11633. }
  11634. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  11635. return ActOnFinishFunctionBody(D, BodyArg, false);
  11636. }
  11637. /// RAII object that pops an ExpressionEvaluationContext when exiting a function
  11638. /// body.
  11639. class ExitFunctionBodyRAII {
  11640. public:
  11641. ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
  11642. ~ExitFunctionBodyRAII() {
  11643. if (!IsLambda)
  11644. S.PopExpressionEvaluationContext();
  11645. }
  11646. private:
  11647. Sema &S;
  11648. bool IsLambda = false;
  11649. };
  11650. static void diagnoseImplicitlyRetainedSelf(Sema &S) {
  11651. llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
  11652. auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
  11653. if (EscapeInfo.count(BD))
  11654. return EscapeInfo[BD];
  11655. bool R = false;
  11656. const BlockDecl *CurBD = BD;
  11657. do {
  11658. R = !CurBD->doesNotEscape();
  11659. if (R)
  11660. break;
  11661. CurBD = CurBD->getParent()->getInnermostBlockDecl();
  11662. } while (CurBD);
  11663. return EscapeInfo[BD] = R;
  11664. };
  11665. // If the location where 'self' is implicitly retained is inside a escaping
  11666. // block, emit a diagnostic.
  11667. for (const std::pair<SourceLocation, const BlockDecl *> &P :
  11668. S.ImplicitlyRetainedSelfLocs)
  11669. if (IsOrNestedInEscapingBlock(P.second))
  11670. S.Diag(P.first, diag::warn_implicitly_retains_self)
  11671. << FixItHint::CreateInsertion(P.first, "self->");
  11672. }
  11673. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  11674. bool IsInstantiation) {
  11675. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  11676. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  11677. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  11678. if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
  11679. CheckCompletedCoroutineBody(FD, Body);
  11680. // Do not call PopExpressionEvaluationContext() if it is a lambda because one
  11681. // is already popped when finishing the lambda in BuildLambdaExpr(). This is
  11682. // meant to pop the context added in ActOnStartOfFunctionDef().
  11683. ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
  11684. if (FD) {
  11685. FD->setBody(Body);
  11686. FD->setWillHaveBody(false);
  11687. if (getLangOpts().CPlusPlus14) {
  11688. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  11689. FD->getReturnType()->isUndeducedType()) {
  11690. // If the function has a deduced result type but contains no 'return'
  11691. // statements, the result type as written must be exactly 'auto', and
  11692. // the deduced result type is 'void'.
  11693. if (!FD->getReturnType()->getAs<AutoType>()) {
  11694. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  11695. << FD->getReturnType();
  11696. FD->setInvalidDecl();
  11697. } else {
  11698. // Substitute 'void' for the 'auto' in the type.
  11699. TypeLoc ResultType = getReturnTypeLoc(FD);
  11700. Context.adjustDeducedFunctionResultType(
  11701. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  11702. }
  11703. }
  11704. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  11705. // In C++11, we don't use 'auto' deduction rules for lambda call
  11706. // operators because we don't support return type deduction.
  11707. auto *LSI = getCurLambda();
  11708. if (LSI->HasImplicitReturnType) {
  11709. deduceClosureReturnType(*LSI);
  11710. // C++11 [expr.prim.lambda]p4:
  11711. // [...] if there are no return statements in the compound-statement
  11712. // [the deduced type is] the type void
  11713. QualType RetType =
  11714. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  11715. // Update the return type to the deduced type.
  11716. const FunctionProtoType *Proto =
  11717. FD->getType()->getAs<FunctionProtoType>();
  11718. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  11719. Proto->getExtProtoInfo()));
  11720. }
  11721. }
  11722. // If the function implicitly returns zero (like 'main') or is naked,
  11723. // don't complain about missing return statements.
  11724. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  11725. WP.disableCheckFallThrough();
  11726. // MSVC permits the use of pure specifier (=0) on function definition,
  11727. // defined at class scope, warn about this non-standard construct.
  11728. if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
  11729. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  11730. if (!FD->isInvalidDecl()) {
  11731. // Don't diagnose unused parameters of defaulted or deleted functions.
  11732. if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
  11733. DiagnoseUnusedParameters(FD->parameters());
  11734. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  11735. FD->getReturnType(), FD);
  11736. // If this is a structor, we need a vtable.
  11737. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  11738. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  11739. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  11740. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  11741. // Try to apply the named return value optimization. We have to check
  11742. // if we can do this here because lambdas keep return statements around
  11743. // to deduce an implicit return type.
  11744. if (FD->getReturnType()->isRecordType() &&
  11745. (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
  11746. computeNRVO(Body, getCurFunction());
  11747. }
  11748. // GNU warning -Wmissing-prototypes:
  11749. // Warn if a global function is defined without a previous
  11750. // prototype declaration. This warning is issued even if the
  11751. // definition itself provides a prototype. The aim is to detect
  11752. // global functions that fail to be declared in header files.
  11753. const FunctionDecl *PossibleZeroParamPrototype = nullptr;
  11754. if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
  11755. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  11756. if (PossibleZeroParamPrototype) {
  11757. // We found a declaration that is not a prototype,
  11758. // but that could be a zero-parameter prototype
  11759. if (TypeSourceInfo *TI =
  11760. PossibleZeroParamPrototype->getTypeSourceInfo()) {
  11761. TypeLoc TL = TI->getTypeLoc();
  11762. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  11763. Diag(PossibleZeroParamPrototype->getLocation(),
  11764. diag::note_declaration_not_a_prototype)
  11765. << PossibleZeroParamPrototype
  11766. << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
  11767. }
  11768. }
  11769. // GNU warning -Wstrict-prototypes
  11770. // Warn if K&R function is defined without a previous declaration.
  11771. // This warning is issued only if the definition itself does not provide
  11772. // a prototype. Only K&R definitions do not provide a prototype.
  11773. // An empty list in a function declarator that is part of a definition
  11774. // of that function specifies that the function has no parameters
  11775. // (C99 6.7.5.3p14)
  11776. if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
  11777. !LangOpts.CPlusPlus) {
  11778. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  11779. TypeLoc TL = TI->getTypeLoc();
  11780. FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
  11781. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
  11782. }
  11783. }
  11784. // Warn on CPUDispatch with an actual body.
  11785. if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
  11786. if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
  11787. if (!CmpndBody->body_empty())
  11788. Diag(CmpndBody->body_front()->getBeginLoc(),
  11789. diag::warn_dispatch_body_ignored);
  11790. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  11791. const CXXMethodDecl *KeyFunction;
  11792. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  11793. MD->isVirtual() &&
  11794. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  11795. MD == KeyFunction->getCanonicalDecl()) {
  11796. // Update the key-function state if necessary for this ABI.
  11797. if (FD->isInlined() &&
  11798. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  11799. Context.setNonKeyFunction(MD);
  11800. // If the newly-chosen key function is already defined, then we
  11801. // need to mark the vtable as used retroactively.
  11802. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  11803. const FunctionDecl *Definition;
  11804. if (KeyFunction && KeyFunction->isDefined(Definition))
  11805. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  11806. } else {
  11807. // We just defined they key function; mark the vtable as used.
  11808. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  11809. }
  11810. }
  11811. }
  11812. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  11813. "Function parsing confused");
  11814. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  11815. assert(MD == getCurMethodDecl() && "Method parsing confused");
  11816. MD->setBody(Body);
  11817. if (!MD->isInvalidDecl()) {
  11818. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  11819. MD->getReturnType(), MD);
  11820. if (Body)
  11821. computeNRVO(Body, getCurFunction());
  11822. }
  11823. if (getCurFunction()->ObjCShouldCallSuper) {
  11824. Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
  11825. << MD->getSelector().getAsString();
  11826. getCurFunction()->ObjCShouldCallSuper = false;
  11827. }
  11828. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  11829. const ObjCMethodDecl *InitMethod = nullptr;
  11830. bool isDesignated =
  11831. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  11832. assert(isDesignated && InitMethod);
  11833. (void)isDesignated;
  11834. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  11835. auto IFace = MD->getClassInterface();
  11836. if (!IFace)
  11837. return false;
  11838. auto SuperD = IFace->getSuperClass();
  11839. if (!SuperD)
  11840. return false;
  11841. return SuperD->getIdentifier() ==
  11842. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  11843. };
  11844. // Don't issue this warning for unavailable inits or direct subclasses
  11845. // of NSObject.
  11846. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  11847. Diag(MD->getLocation(),
  11848. diag::warn_objc_designated_init_missing_super_call);
  11849. Diag(InitMethod->getLocation(),
  11850. diag::note_objc_designated_init_marked_here);
  11851. }
  11852. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  11853. }
  11854. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  11855. // Don't issue this warning for unavaialable inits.
  11856. if (!MD->isUnavailable())
  11857. Diag(MD->getLocation(),
  11858. diag::warn_objc_secondary_init_missing_init_call);
  11859. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  11860. }
  11861. diagnoseImplicitlyRetainedSelf(*this);
  11862. } else {
  11863. // Parsing the function declaration failed in some way. Pop the fake scope
  11864. // we pushed on.
  11865. PopFunctionScopeInfo(ActivePolicy, dcl);
  11866. return nullptr;
  11867. }
  11868. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  11869. DiagnoseUnguardedAvailabilityViolations(dcl);
  11870. assert(!getCurFunction()->ObjCShouldCallSuper &&
  11871. "This should only be set for ObjC methods, which should have been "
  11872. "handled in the block above.");
  11873. // Verify and clean out per-function state.
  11874. if (Body && (!FD || !FD->isDefaulted())) {
  11875. // C++ constructors that have function-try-blocks can't have return
  11876. // statements in the handlers of that block. (C++ [except.handle]p14)
  11877. // Verify this.
  11878. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  11879. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  11880. // Verify that gotos and switch cases don't jump into scopes illegally.
  11881. if (getCurFunction()->NeedsScopeChecking() &&
  11882. !PP.isCodeCompletionEnabled())
  11883. DiagnoseInvalidJumps(Body);
  11884. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  11885. if (!Destructor->getParent()->isDependentType())
  11886. CheckDestructor(Destructor);
  11887. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  11888. Destructor->getParent());
  11889. }
  11890. // If any errors have occurred, clear out any temporaries that may have
  11891. // been leftover. This ensures that these temporaries won't be picked up for
  11892. // deletion in some later function.
  11893. if (getDiagnostics().hasErrorOccurred() ||
  11894. getDiagnostics().getSuppressAllDiagnostics()) {
  11895. DiscardCleanupsInEvaluationContext();
  11896. }
  11897. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  11898. !isa<FunctionTemplateDecl>(dcl)) {
  11899. // Since the body is valid, issue any analysis-based warnings that are
  11900. // enabled.
  11901. ActivePolicy = &WP;
  11902. }
  11903. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  11904. (!CheckConstexprFunctionDecl(FD) ||
  11905. !CheckConstexprFunctionBody(FD, Body)))
  11906. FD->setInvalidDecl();
  11907. if (FD && FD->hasAttr<NakedAttr>()) {
  11908. for (const Stmt *S : Body->children()) {
  11909. // Allow local register variables without initializer as they don't
  11910. // require prologue.
  11911. bool RegisterVariables = false;
  11912. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  11913. for (const auto *Decl : DS->decls()) {
  11914. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  11915. RegisterVariables =
  11916. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  11917. if (!RegisterVariables)
  11918. break;
  11919. }
  11920. }
  11921. }
  11922. if (RegisterVariables)
  11923. continue;
  11924. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  11925. Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
  11926. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  11927. FD->setInvalidDecl();
  11928. break;
  11929. }
  11930. }
  11931. }
  11932. assert(ExprCleanupObjects.size() ==
  11933. ExprEvalContexts.back().NumCleanupObjects &&
  11934. "Leftover temporaries in function");
  11935. assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
  11936. assert(MaybeODRUseExprs.empty() &&
  11937. "Leftover expressions for odr-use checking");
  11938. }
  11939. if (!IsInstantiation)
  11940. PopDeclContext();
  11941. PopFunctionScopeInfo(ActivePolicy, dcl);
  11942. // If any errors have occurred, clear out any temporaries that may have
  11943. // been leftover. This ensures that these temporaries won't be picked up for
  11944. // deletion in some later function.
  11945. if (getDiagnostics().hasErrorOccurred()) {
  11946. DiscardCleanupsInEvaluationContext();
  11947. }
  11948. return dcl;
  11949. }
  11950. /// When we finish delayed parsing of an attribute, we must attach it to the
  11951. /// relevant Decl.
  11952. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  11953. ParsedAttributes &Attrs) {
  11954. // Always attach attributes to the underlying decl.
  11955. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  11956. D = TD->getTemplatedDecl();
  11957. ProcessDeclAttributeList(S, D, Attrs);
  11958. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  11959. if (Method->isStatic())
  11960. checkThisInStaticMemberFunctionAttributes(Method);
  11961. }
  11962. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  11963. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  11964. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  11965. IdentifierInfo &II, Scope *S) {
  11966. // Find the scope in which the identifier is injected and the corresponding
  11967. // DeclContext.
  11968. // FIXME: C89 does not say what happens if there is no enclosing block scope.
  11969. // In that case, we inject the declaration into the translation unit scope
  11970. // instead.
  11971. Scope *BlockScope = S;
  11972. while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
  11973. BlockScope = BlockScope->getParent();
  11974. Scope *ContextScope = BlockScope;
  11975. while (!ContextScope->getEntity())
  11976. ContextScope = ContextScope->getParent();
  11977. ContextRAII SavedContext(*this, ContextScope->getEntity());
  11978. // Before we produce a declaration for an implicitly defined
  11979. // function, see whether there was a locally-scoped declaration of
  11980. // this name as a function or variable. If so, use that
  11981. // (non-visible) declaration, and complain about it.
  11982. NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
  11983. if (ExternCPrev) {
  11984. // We still need to inject the function into the enclosing block scope so
  11985. // that later (non-call) uses can see it.
  11986. PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
  11987. // C89 footnote 38:
  11988. // If in fact it is not defined as having type "function returning int",
  11989. // the behavior is undefined.
  11990. if (!isa<FunctionDecl>(ExternCPrev) ||
  11991. !Context.typesAreCompatible(
  11992. cast<FunctionDecl>(ExternCPrev)->getType(),
  11993. Context.getFunctionNoProtoType(Context.IntTy))) {
  11994. Diag(Loc, diag::ext_use_out_of_scope_declaration)
  11995. << ExternCPrev << !getLangOpts().C99;
  11996. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  11997. return ExternCPrev;
  11998. }
  11999. }
  12000. // Extension in C99. Legal in C90, but warn about it.
  12001. unsigned diag_id;
  12002. if (II.getName().startswith("__builtin_"))
  12003. diag_id = diag::warn_builtin_unknown;
  12004. // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
  12005. else if (getLangOpts().OpenCL)
  12006. diag_id = diag::err_opencl_implicit_function_decl;
  12007. else if (getLangOpts().C99)
  12008. diag_id = diag::ext_implicit_function_decl;
  12009. else
  12010. diag_id = diag::warn_implicit_function_decl;
  12011. Diag(Loc, diag_id) << &II;
  12012. // If we found a prior declaration of this function, don't bother building
  12013. // another one. We've already pushed that one into scope, so there's nothing
  12014. // more to do.
  12015. if (ExternCPrev)
  12016. return ExternCPrev;
  12017. // Because typo correction is expensive, only do it if the implicit
  12018. // function declaration is going to be treated as an error.
  12019. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  12020. TypoCorrection Corrected;
  12021. DeclFilterCCC<FunctionDecl> CCC{};
  12022. if (S && (Corrected =
  12023. CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
  12024. S, nullptr, CCC, CTK_NonError)))
  12025. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  12026. /*ErrorRecovery*/false);
  12027. }
  12028. // Set a Declarator for the implicit definition: int foo();
  12029. const char *Dummy;
  12030. AttributeFactory attrFactory;
  12031. DeclSpec DS(attrFactory);
  12032. unsigned DiagID;
  12033. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  12034. Context.getPrintingPolicy());
  12035. (void)Error; // Silence warning.
  12036. assert(!Error && "Error setting up implicit decl!");
  12037. SourceLocation NoLoc;
  12038. Declarator D(DS, DeclaratorContext::BlockContext);
  12039. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  12040. /*IsAmbiguous=*/false,
  12041. /*LParenLoc=*/NoLoc,
  12042. /*Params=*/nullptr,
  12043. /*NumParams=*/0,
  12044. /*EllipsisLoc=*/NoLoc,
  12045. /*RParenLoc=*/NoLoc,
  12046. /*RefQualifierIsLvalueRef=*/true,
  12047. /*RefQualifierLoc=*/NoLoc,
  12048. /*MutableLoc=*/NoLoc, EST_None,
  12049. /*ESpecRange=*/SourceRange(),
  12050. /*Exceptions=*/nullptr,
  12051. /*ExceptionRanges=*/nullptr,
  12052. /*NumExceptions=*/0,
  12053. /*NoexceptExpr=*/nullptr,
  12054. /*ExceptionSpecTokens=*/nullptr,
  12055. /*DeclsInPrototype=*/None, Loc,
  12056. Loc, D),
  12057. std::move(DS.getAttributes()), SourceLocation());
  12058. D.SetIdentifier(&II, Loc);
  12059. // Insert this function into the enclosing block scope.
  12060. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
  12061. FD->setImplicit();
  12062. AddKnownFunctionAttributes(FD);
  12063. return FD;
  12064. }
  12065. /// Adds any function attributes that we know a priori based on
  12066. /// the declaration of this function.
  12067. ///
  12068. /// These attributes can apply both to implicitly-declared builtins
  12069. /// (like __builtin___printf_chk) or to library-declared functions
  12070. /// like NSLog or printf.
  12071. ///
  12072. /// We need to check for duplicate attributes both here and where user-written
  12073. /// attributes are applied to declarations.
  12074. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  12075. if (FD->isInvalidDecl())
  12076. return;
  12077. // If this is a built-in function, map its builtin attributes to
  12078. // actual attributes.
  12079. if (unsigned BuiltinID = FD->getBuiltinID()) {
  12080. // Handle printf-formatting attributes.
  12081. unsigned FormatIdx;
  12082. bool HasVAListArg;
  12083. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  12084. if (!FD->hasAttr<FormatAttr>()) {
  12085. const char *fmt = "printf";
  12086. unsigned int NumParams = FD->getNumParams();
  12087. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  12088. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  12089. fmt = "NSString";
  12090. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12091. &Context.Idents.get(fmt),
  12092. FormatIdx+1,
  12093. HasVAListArg ? 0 : FormatIdx+2,
  12094. FD->getLocation()));
  12095. }
  12096. }
  12097. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  12098. HasVAListArg)) {
  12099. if (!FD->hasAttr<FormatAttr>())
  12100. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12101. &Context.Idents.get("scanf"),
  12102. FormatIdx+1,
  12103. HasVAListArg ? 0 : FormatIdx+2,
  12104. FD->getLocation()));
  12105. }
  12106. // Handle automatically recognized callbacks.
  12107. SmallVector<int, 4> Encoding;
  12108. if (!FD->hasAttr<CallbackAttr>() &&
  12109. Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
  12110. FD->addAttr(CallbackAttr::CreateImplicit(
  12111. Context, Encoding.data(), Encoding.size(), FD->getLocation()));
  12112. // Mark const if we don't care about errno and that is the only thing
  12113. // preventing the function from being const. This allows IRgen to use LLVM
  12114. // intrinsics for such functions.
  12115. if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
  12116. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
  12117. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12118. // We make "fma" on some platforms const because we know it does not set
  12119. // errno in those environments even though it could set errno based on the
  12120. // C standard.
  12121. const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
  12122. if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
  12123. !FD->hasAttr<ConstAttr>()) {
  12124. switch (BuiltinID) {
  12125. case Builtin::BI__builtin_fma:
  12126. case Builtin::BI__builtin_fmaf:
  12127. case Builtin::BI__builtin_fmal:
  12128. case Builtin::BIfma:
  12129. case Builtin::BIfmaf:
  12130. case Builtin::BIfmal:
  12131. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12132. break;
  12133. default:
  12134. break;
  12135. }
  12136. }
  12137. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  12138. !FD->hasAttr<ReturnsTwiceAttr>())
  12139. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  12140. FD->getLocation()));
  12141. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  12142. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12143. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  12144. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  12145. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  12146. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12147. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  12148. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  12149. // Add the appropriate attribute, depending on the CUDA compilation mode
  12150. // and which target the builtin belongs to. For example, during host
  12151. // compilation, aux builtins are __device__, while the rest are __host__.
  12152. if (getLangOpts().CUDAIsDevice !=
  12153. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  12154. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  12155. else
  12156. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  12157. }
  12158. }
  12159. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  12160. // throw, add an implicit nothrow attribute to any extern "C" function we come
  12161. // across.
  12162. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  12163. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  12164. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  12165. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  12166. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12167. }
  12168. IdentifierInfo *Name = FD->getIdentifier();
  12169. if (!Name)
  12170. return;
  12171. if ((!getLangOpts().CPlusPlus &&
  12172. FD->getDeclContext()->isTranslationUnit()) ||
  12173. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  12174. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  12175. LinkageSpecDecl::lang_c)) {
  12176. // Okay: this could be a libc/libm/Objective-C function we know
  12177. // about.
  12178. } else
  12179. return;
  12180. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  12181. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  12182. // target-specific builtins, perhaps?
  12183. if (!FD->hasAttr<FormatAttr>())
  12184. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12185. &Context.Idents.get("printf"), 2,
  12186. Name->isStr("vasprintf") ? 0 : 3,
  12187. FD->getLocation()));
  12188. }
  12189. if (Name->isStr("__CFStringMakeConstantString")) {
  12190. // We already have a __builtin___CFStringMakeConstantString,
  12191. // but builds that use -fno-constant-cfstrings don't go through that.
  12192. if (!FD->hasAttr<FormatArgAttr>())
  12193. FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
  12194. FD->getLocation()));
  12195. }
  12196. }
  12197. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  12198. TypeSourceInfo *TInfo) {
  12199. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  12200. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  12201. if (!TInfo) {
  12202. assert(D.isInvalidType() && "no declarator info for valid type");
  12203. TInfo = Context.getTrivialTypeSourceInfo(T);
  12204. }
  12205. // Scope manipulation handled by caller.
  12206. TypedefDecl *NewTD =
  12207. TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
  12208. D.getIdentifierLoc(), D.getIdentifier(), TInfo);
  12209. // Bail out immediately if we have an invalid declaration.
  12210. if (D.isInvalidType()) {
  12211. NewTD->setInvalidDecl();
  12212. return NewTD;
  12213. }
  12214. if (D.getDeclSpec().isModulePrivateSpecified()) {
  12215. if (CurContext->isFunctionOrMethod())
  12216. Diag(NewTD->getLocation(), diag::err_module_private_local)
  12217. << 2 << NewTD->getDeclName()
  12218. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  12219. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  12220. else
  12221. NewTD->setModulePrivate();
  12222. }
  12223. // C++ [dcl.typedef]p8:
  12224. // If the typedef declaration defines an unnamed class (or
  12225. // enum), the first typedef-name declared by the declaration
  12226. // to be that class type (or enum type) is used to denote the
  12227. // class type (or enum type) for linkage purposes only.
  12228. // We need to check whether the type was declared in the declaration.
  12229. switch (D.getDeclSpec().getTypeSpecType()) {
  12230. case TST_enum:
  12231. case TST_struct:
  12232. case TST_interface:
  12233. case TST_union:
  12234. case TST_class: {
  12235. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  12236. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  12237. break;
  12238. }
  12239. default:
  12240. break;
  12241. }
  12242. return NewTD;
  12243. }
  12244. /// Check that this is a valid underlying type for an enum declaration.
  12245. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  12246. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  12247. QualType T = TI->getType();
  12248. if (T->isDependentType())
  12249. return false;
  12250. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  12251. if (BT->isInteger())
  12252. return false;
  12253. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  12254. return true;
  12255. }
  12256. /// Check whether this is a valid redeclaration of a previous enumeration.
  12257. /// \return true if the redeclaration was invalid.
  12258. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  12259. QualType EnumUnderlyingTy, bool IsFixed,
  12260. const EnumDecl *Prev) {
  12261. if (IsScoped != Prev->isScoped()) {
  12262. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  12263. << Prev->isScoped();
  12264. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12265. return true;
  12266. }
  12267. if (IsFixed && Prev->isFixed()) {
  12268. if (!EnumUnderlyingTy->isDependentType() &&
  12269. !Prev->getIntegerType()->isDependentType() &&
  12270. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  12271. Prev->getIntegerType())) {
  12272. // TODO: Highlight the underlying type of the redeclaration.
  12273. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  12274. << EnumUnderlyingTy << Prev->getIntegerType();
  12275. Diag(Prev->getLocation(), diag::note_previous_declaration)
  12276. << Prev->getIntegerTypeRange();
  12277. return true;
  12278. }
  12279. } else if (IsFixed != Prev->isFixed()) {
  12280. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  12281. << Prev->isFixed();
  12282. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12283. return true;
  12284. }
  12285. return false;
  12286. }
  12287. /// Get diagnostic %select index for tag kind for
  12288. /// redeclaration diagnostic message.
  12289. /// WARNING: Indexes apply to particular diagnostics only!
  12290. ///
  12291. /// \returns diagnostic %select index.
  12292. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  12293. switch (Tag) {
  12294. case TTK_Struct: return 0;
  12295. case TTK_Interface: return 1;
  12296. case TTK_Class: return 2;
  12297. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  12298. }
  12299. }
  12300. /// Determine if tag kind is a class-key compatible with
  12301. /// class for redeclaration (class, struct, or __interface).
  12302. ///
  12303. /// \returns true iff the tag kind is compatible.
  12304. static bool isClassCompatTagKind(TagTypeKind Tag)
  12305. {
  12306. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  12307. }
  12308. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  12309. TagTypeKind TTK) {
  12310. if (isa<TypedefDecl>(PrevDecl))
  12311. return NTK_Typedef;
  12312. else if (isa<TypeAliasDecl>(PrevDecl))
  12313. return NTK_TypeAlias;
  12314. else if (isa<ClassTemplateDecl>(PrevDecl))
  12315. return NTK_Template;
  12316. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  12317. return NTK_TypeAliasTemplate;
  12318. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  12319. return NTK_TemplateTemplateArgument;
  12320. switch (TTK) {
  12321. case TTK_Struct:
  12322. case TTK_Interface:
  12323. case TTK_Class:
  12324. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  12325. case TTK_Union:
  12326. return NTK_NonUnion;
  12327. case TTK_Enum:
  12328. return NTK_NonEnum;
  12329. }
  12330. llvm_unreachable("invalid TTK");
  12331. }
  12332. /// Determine whether a tag with a given kind is acceptable
  12333. /// as a redeclaration of the given tag declaration.
  12334. ///
  12335. /// \returns true if the new tag kind is acceptable, false otherwise.
  12336. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  12337. TagTypeKind NewTag, bool isDefinition,
  12338. SourceLocation NewTagLoc,
  12339. const IdentifierInfo *Name) {
  12340. // C++ [dcl.type.elab]p3:
  12341. // The class-key or enum keyword present in the
  12342. // elaborated-type-specifier shall agree in kind with the
  12343. // declaration to which the name in the elaborated-type-specifier
  12344. // refers. This rule also applies to the form of
  12345. // elaborated-type-specifier that declares a class-name or
  12346. // friend class since it can be construed as referring to the
  12347. // definition of the class. Thus, in any
  12348. // elaborated-type-specifier, the enum keyword shall be used to
  12349. // refer to an enumeration (7.2), the union class-key shall be
  12350. // used to refer to a union (clause 9), and either the class or
  12351. // struct class-key shall be used to refer to a class (clause 9)
  12352. // declared using the class or struct class-key.
  12353. TagTypeKind OldTag = Previous->getTagKind();
  12354. if (OldTag != NewTag &&
  12355. !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
  12356. return false;
  12357. // Tags are compatible, but we might still want to warn on mismatched tags.
  12358. // Non-class tags can't be mismatched at this point.
  12359. if (!isClassCompatTagKind(NewTag))
  12360. return true;
  12361. // Declarations for which -Wmismatched-tags is disabled are entirely ignored
  12362. // by our warning analysis. We don't want to warn about mismatches with (eg)
  12363. // declarations in system headers that are designed to be specialized, but if
  12364. // a user asks us to warn, we should warn if their code contains mismatched
  12365. // declarations.
  12366. auto IsIgnoredLoc = [&](SourceLocation Loc) {
  12367. return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
  12368. Loc);
  12369. };
  12370. if (IsIgnoredLoc(NewTagLoc))
  12371. return true;
  12372. auto IsIgnored = [&](const TagDecl *Tag) {
  12373. return IsIgnoredLoc(Tag->getLocation());
  12374. };
  12375. while (IsIgnored(Previous)) {
  12376. Previous = Previous->getPreviousDecl();
  12377. if (!Previous)
  12378. return true;
  12379. OldTag = Previous->getTagKind();
  12380. }
  12381. bool isTemplate = false;
  12382. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  12383. isTemplate = Record->getDescribedClassTemplate();
  12384. if (inTemplateInstantiation()) {
  12385. if (OldTag != NewTag) {
  12386. // In a template instantiation, do not offer fix-its for tag mismatches
  12387. // since they usually mess up the template instead of fixing the problem.
  12388. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12389. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12390. << getRedeclDiagFromTagKind(OldTag);
  12391. // FIXME: Note previous location?
  12392. }
  12393. return true;
  12394. }
  12395. if (isDefinition) {
  12396. // On definitions, check all previous tags and issue a fix-it for each
  12397. // one that doesn't match the current tag.
  12398. if (Previous->getDefinition()) {
  12399. // Don't suggest fix-its for redefinitions.
  12400. return true;
  12401. }
  12402. bool previousMismatch = false;
  12403. for (const TagDecl *I : Previous->redecls()) {
  12404. if (I->getTagKind() != NewTag) {
  12405. // Ignore previous declarations for which the warning was disabled.
  12406. if (IsIgnored(I))
  12407. continue;
  12408. if (!previousMismatch) {
  12409. previousMismatch = true;
  12410. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  12411. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12412. << getRedeclDiagFromTagKind(I->getTagKind());
  12413. }
  12414. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  12415. << getRedeclDiagFromTagKind(NewTag)
  12416. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  12417. TypeWithKeyword::getTagTypeKindName(NewTag));
  12418. }
  12419. }
  12420. return true;
  12421. }
  12422. // Identify the prevailing tag kind: this is the kind of the definition (if
  12423. // there is a non-ignored definition), or otherwise the kind of the prior
  12424. // (non-ignored) declaration.
  12425. const TagDecl *PrevDef = Previous->getDefinition();
  12426. if (PrevDef && IsIgnored(PrevDef))
  12427. PrevDef = nullptr;
  12428. const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
  12429. if (Redecl->getTagKind() != NewTag) {
  12430. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12431. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12432. << getRedeclDiagFromTagKind(OldTag);
  12433. Diag(Redecl->getLocation(), diag::note_previous_use);
  12434. // If there is a previous definition, suggest a fix-it.
  12435. if (PrevDef) {
  12436. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  12437. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  12438. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  12439. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  12440. }
  12441. }
  12442. return true;
  12443. }
  12444. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  12445. /// from an outer enclosing namespace or file scope inside a friend declaration.
  12446. /// This should provide the commented out code in the following snippet:
  12447. /// namespace N {
  12448. /// struct X;
  12449. /// namespace M {
  12450. /// struct Y { friend struct /*N::*/ X; };
  12451. /// }
  12452. /// }
  12453. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  12454. SourceLocation NameLoc) {
  12455. // While the decl is in a namespace, do repeated lookup of that name and see
  12456. // if we get the same namespace back. If we do not, continue until
  12457. // translation unit scope, at which point we have a fully qualified NNS.
  12458. SmallVector<IdentifierInfo *, 4> Namespaces;
  12459. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  12460. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  12461. // This tag should be declared in a namespace, which can only be enclosed by
  12462. // other namespaces. Bail if there's an anonymous namespace in the chain.
  12463. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  12464. if (!Namespace || Namespace->isAnonymousNamespace())
  12465. return FixItHint();
  12466. IdentifierInfo *II = Namespace->getIdentifier();
  12467. Namespaces.push_back(II);
  12468. NamedDecl *Lookup = SemaRef.LookupSingleName(
  12469. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  12470. if (Lookup == Namespace)
  12471. break;
  12472. }
  12473. // Once we have all the namespaces, reverse them to go outermost first, and
  12474. // build an NNS.
  12475. SmallString<64> Insertion;
  12476. llvm::raw_svector_ostream OS(Insertion);
  12477. if (DC->isTranslationUnit())
  12478. OS << "::";
  12479. std::reverse(Namespaces.begin(), Namespaces.end());
  12480. for (auto *II : Namespaces)
  12481. OS << II->getName() << "::";
  12482. return FixItHint::CreateInsertion(NameLoc, Insertion);
  12483. }
  12484. /// Determine whether a tag originally declared in context \p OldDC can
  12485. /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
  12486. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  12487. /// using-declaration).
  12488. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  12489. DeclContext *NewDC) {
  12490. OldDC = OldDC->getRedeclContext();
  12491. NewDC = NewDC->getRedeclContext();
  12492. if (OldDC->Equals(NewDC))
  12493. return true;
  12494. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  12495. // encloses the other).
  12496. if (S.getLangOpts().MSVCCompat &&
  12497. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  12498. return true;
  12499. return false;
  12500. }
  12501. /// This is invoked when we see 'struct foo' or 'struct {'. In the
  12502. /// former case, Name will be non-null. In the later case, Name will be null.
  12503. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  12504. /// reference/declaration/definition of a tag.
  12505. ///
  12506. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  12507. /// trailing-type-specifier) other than one in an alias-declaration.
  12508. ///
  12509. /// \param SkipBody If non-null, will be set to indicate if the caller should
  12510. /// skip the definition of this tag and treat it as if it were a declaration.
  12511. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  12512. SourceLocation KWLoc, CXXScopeSpec &SS,
  12513. IdentifierInfo *Name, SourceLocation NameLoc,
  12514. const ParsedAttributesView &Attrs, AccessSpecifier AS,
  12515. SourceLocation ModulePrivateLoc,
  12516. MultiTemplateParamsArg TemplateParameterLists,
  12517. bool &OwnedDecl, bool &IsDependent,
  12518. SourceLocation ScopedEnumKWLoc,
  12519. bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
  12520. bool IsTypeSpecifier, bool IsTemplateParamOrArg,
  12521. SkipBodyInfo *SkipBody) {
  12522. // If this is not a definition, it must have a name.
  12523. IdentifierInfo *OrigName = Name;
  12524. assert((Name != nullptr || TUK == TUK_Definition) &&
  12525. "Nameless record must be a definition!");
  12526. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  12527. OwnedDecl = false;
  12528. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  12529. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  12530. // FIXME: Check member specializations more carefully.
  12531. bool isMemberSpecialization = false;
  12532. bool Invalid = false;
  12533. // We only need to do this matching if we have template parameters
  12534. // or a scope specifier, which also conveniently avoids this work
  12535. // for non-C++ cases.
  12536. if (TemplateParameterLists.size() > 0 ||
  12537. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  12538. if (TemplateParameterList *TemplateParams =
  12539. MatchTemplateParametersToScopeSpecifier(
  12540. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  12541. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  12542. if (Kind == TTK_Enum) {
  12543. Diag(KWLoc, diag::err_enum_template);
  12544. return nullptr;
  12545. }
  12546. if (TemplateParams->size() > 0) {
  12547. // This is a declaration or definition of a class template (which may
  12548. // be a member of another template).
  12549. if (Invalid)
  12550. return nullptr;
  12551. OwnedDecl = false;
  12552. DeclResult Result = CheckClassTemplate(
  12553. S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
  12554. AS, ModulePrivateLoc,
  12555. /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
  12556. TemplateParameterLists.data(), SkipBody);
  12557. return Result.get();
  12558. } else {
  12559. // The "template<>" header is extraneous.
  12560. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12561. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12562. isMemberSpecialization = true;
  12563. }
  12564. }
  12565. }
  12566. // Figure out the underlying type if this a enum declaration. We need to do
  12567. // this early, because it's needed to detect if this is an incompatible
  12568. // redeclaration.
  12569. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  12570. bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
  12571. if (Kind == TTK_Enum) {
  12572. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
  12573. // No underlying type explicitly specified, or we failed to parse the
  12574. // type, default to int.
  12575. EnumUnderlying = Context.IntTy.getTypePtr();
  12576. } else if (UnderlyingType.get()) {
  12577. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  12578. // integral type; any cv-qualification is ignored.
  12579. TypeSourceInfo *TI = nullptr;
  12580. GetTypeFromParser(UnderlyingType.get(), &TI);
  12581. EnumUnderlying = TI;
  12582. if (CheckEnumUnderlyingType(TI))
  12583. // Recover by falling back to int.
  12584. EnumUnderlying = Context.IntTy.getTypePtr();
  12585. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  12586. UPPC_FixedUnderlyingType))
  12587. EnumUnderlying = Context.IntTy.getTypePtr();
  12588. } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  12589. // For MSVC ABI compatibility, unfixed enums must use an underlying type
  12590. // of 'int'. However, if this is an unfixed forward declaration, don't set
  12591. // the underlying type unless the user enables -fms-compatibility. This
  12592. // makes unfixed forward declared enums incomplete and is more conforming.
  12593. if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
  12594. EnumUnderlying = Context.IntTy.getTypePtr();
  12595. }
  12596. }
  12597. DeclContext *SearchDC = CurContext;
  12598. DeclContext *DC = CurContext;
  12599. bool isStdBadAlloc = false;
  12600. bool isStdAlignValT = false;
  12601. RedeclarationKind Redecl = forRedeclarationInCurContext();
  12602. if (TUK == TUK_Friend || TUK == TUK_Reference)
  12603. Redecl = NotForRedeclaration;
  12604. /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
  12605. /// implemented asks for structural equivalence checking, the returned decl
  12606. /// here is passed back to the parser, allowing the tag body to be parsed.
  12607. auto createTagFromNewDecl = [&]() -> TagDecl * {
  12608. assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
  12609. // If there is an identifier, use the location of the identifier as the
  12610. // location of the decl, otherwise use the location of the struct/union
  12611. // keyword.
  12612. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  12613. TagDecl *New = nullptr;
  12614. if (Kind == TTK_Enum) {
  12615. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
  12616. ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
  12617. // If this is an undefined enum, bail.
  12618. if (TUK != TUK_Definition && !Invalid)
  12619. return nullptr;
  12620. if (EnumUnderlying) {
  12621. EnumDecl *ED = cast<EnumDecl>(New);
  12622. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
  12623. ED->setIntegerTypeSourceInfo(TI);
  12624. else
  12625. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  12626. ED->setPromotionType(ED->getIntegerType());
  12627. }
  12628. } else { // struct/union
  12629. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12630. nullptr);
  12631. }
  12632. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  12633. // Add alignment attributes if necessary; these attributes are checked
  12634. // when the ASTContext lays out the structure.
  12635. //
  12636. // It is important for implementing the correct semantics that this
  12637. // happen here (in ActOnTag). The #pragma pack stack is
  12638. // maintained as a result of parser callbacks which can occur at
  12639. // many points during the parsing of a struct declaration (because
  12640. // the #pragma tokens are effectively skipped over during the
  12641. // parsing of the struct).
  12642. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  12643. AddAlignmentAttributesForRecord(RD);
  12644. AddMsStructLayoutForRecord(RD);
  12645. }
  12646. }
  12647. New->setLexicalDeclContext(CurContext);
  12648. return New;
  12649. };
  12650. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  12651. if (Name && SS.isNotEmpty()) {
  12652. // We have a nested-name tag ('struct foo::bar').
  12653. // Check for invalid 'foo::'.
  12654. if (SS.isInvalid()) {
  12655. Name = nullptr;
  12656. goto CreateNewDecl;
  12657. }
  12658. // If this is a friend or a reference to a class in a dependent
  12659. // context, don't try to make a decl for it.
  12660. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  12661. DC = computeDeclContext(SS, false);
  12662. if (!DC) {
  12663. IsDependent = true;
  12664. return nullptr;
  12665. }
  12666. } else {
  12667. DC = computeDeclContext(SS, true);
  12668. if (!DC) {
  12669. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  12670. << SS.getRange();
  12671. return nullptr;
  12672. }
  12673. }
  12674. if (RequireCompleteDeclContext(SS, DC))
  12675. return nullptr;
  12676. SearchDC = DC;
  12677. // Look-up name inside 'foo::'.
  12678. LookupQualifiedName(Previous, DC);
  12679. if (Previous.isAmbiguous())
  12680. return nullptr;
  12681. if (Previous.empty()) {
  12682. // Name lookup did not find anything. However, if the
  12683. // nested-name-specifier refers to the current instantiation,
  12684. // and that current instantiation has any dependent base
  12685. // classes, we might find something at instantiation time: treat
  12686. // this as a dependent elaborated-type-specifier.
  12687. // But this only makes any sense for reference-like lookups.
  12688. if (Previous.wasNotFoundInCurrentInstantiation() &&
  12689. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  12690. IsDependent = true;
  12691. return nullptr;
  12692. }
  12693. // A tag 'foo::bar' must already exist.
  12694. Diag(NameLoc, diag::err_not_tag_in_scope)
  12695. << Kind << Name << DC << SS.getRange();
  12696. Name = nullptr;
  12697. Invalid = true;
  12698. goto CreateNewDecl;
  12699. }
  12700. } else if (Name) {
  12701. // C++14 [class.mem]p14:
  12702. // If T is the name of a class, then each of the following shall have a
  12703. // name different from T:
  12704. // -- every member of class T that is itself a type
  12705. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  12706. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  12707. return nullptr;
  12708. // If this is a named struct, check to see if there was a previous forward
  12709. // declaration or definition.
  12710. // FIXME: We're looking into outer scopes here, even when we
  12711. // shouldn't be. Doing so can result in ambiguities that we
  12712. // shouldn't be diagnosing.
  12713. LookupName(Previous, S);
  12714. // When declaring or defining a tag, ignore ambiguities introduced
  12715. // by types using'ed into this scope.
  12716. if (Previous.isAmbiguous() &&
  12717. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  12718. LookupResult::Filter F = Previous.makeFilter();
  12719. while (F.hasNext()) {
  12720. NamedDecl *ND = F.next();
  12721. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  12722. SearchDC->getRedeclContext()))
  12723. F.erase();
  12724. }
  12725. F.done();
  12726. }
  12727. // C++11 [namespace.memdef]p3:
  12728. // If the name in a friend declaration is neither qualified nor
  12729. // a template-id and the declaration is a function or an
  12730. // elaborated-type-specifier, the lookup to determine whether
  12731. // the entity has been previously declared shall not consider
  12732. // any scopes outside the innermost enclosing namespace.
  12733. //
  12734. // MSVC doesn't implement the above rule for types, so a friend tag
  12735. // declaration may be a redeclaration of a type declared in an enclosing
  12736. // scope. They do implement this rule for friend functions.
  12737. //
  12738. // Does it matter that this should be by scope instead of by
  12739. // semantic context?
  12740. if (!Previous.empty() && TUK == TUK_Friend) {
  12741. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  12742. LookupResult::Filter F = Previous.makeFilter();
  12743. bool FriendSawTagOutsideEnclosingNamespace = false;
  12744. while (F.hasNext()) {
  12745. NamedDecl *ND = F.next();
  12746. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  12747. if (DC->isFileContext() &&
  12748. !EnclosingNS->Encloses(ND->getDeclContext())) {
  12749. if (getLangOpts().MSVCCompat)
  12750. FriendSawTagOutsideEnclosingNamespace = true;
  12751. else
  12752. F.erase();
  12753. }
  12754. }
  12755. F.done();
  12756. // Diagnose this MSVC extension in the easy case where lookup would have
  12757. // unambiguously found something outside the enclosing namespace.
  12758. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  12759. NamedDecl *ND = Previous.getFoundDecl();
  12760. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  12761. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  12762. }
  12763. }
  12764. // Note: there used to be some attempt at recovery here.
  12765. if (Previous.isAmbiguous())
  12766. return nullptr;
  12767. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  12768. // FIXME: This makes sure that we ignore the contexts associated
  12769. // with C structs, unions, and enums when looking for a matching
  12770. // tag declaration or definition. See the similar lookup tweak
  12771. // in Sema::LookupName; is there a better way to deal with this?
  12772. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  12773. SearchDC = SearchDC->getParent();
  12774. }
  12775. }
  12776. if (Previous.isSingleResult() &&
  12777. Previous.getFoundDecl()->isTemplateParameter()) {
  12778. // Maybe we will complain about the shadowed template parameter.
  12779. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  12780. // Just pretend that we didn't see the previous declaration.
  12781. Previous.clear();
  12782. }
  12783. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  12784. DC->Equals(getStdNamespace())) {
  12785. if (Name->isStr("bad_alloc")) {
  12786. // This is a declaration of or a reference to "std::bad_alloc".
  12787. isStdBadAlloc = true;
  12788. // If std::bad_alloc has been implicitly declared (but made invisible to
  12789. // name lookup), fill in this implicit declaration as the previous
  12790. // declaration, so that the declarations get chained appropriately.
  12791. if (Previous.empty() && StdBadAlloc)
  12792. Previous.addDecl(getStdBadAlloc());
  12793. } else if (Name->isStr("align_val_t")) {
  12794. isStdAlignValT = true;
  12795. if (Previous.empty() && StdAlignValT)
  12796. Previous.addDecl(getStdAlignValT());
  12797. }
  12798. }
  12799. // If we didn't find a previous declaration, and this is a reference
  12800. // (or friend reference), move to the correct scope. In C++, we
  12801. // also need to do a redeclaration lookup there, just in case
  12802. // there's a shadow friend decl.
  12803. if (Name && Previous.empty() &&
  12804. (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
  12805. if (Invalid) goto CreateNewDecl;
  12806. assert(SS.isEmpty());
  12807. if (TUK == TUK_Reference || IsTemplateParamOrArg) {
  12808. // C++ [basic.scope.pdecl]p5:
  12809. // -- for an elaborated-type-specifier of the form
  12810. //
  12811. // class-key identifier
  12812. //
  12813. // if the elaborated-type-specifier is used in the
  12814. // decl-specifier-seq or parameter-declaration-clause of a
  12815. // function defined in namespace scope, the identifier is
  12816. // declared as a class-name in the namespace that contains
  12817. // the declaration; otherwise, except as a friend
  12818. // declaration, the identifier is declared in the smallest
  12819. // non-class, non-function-prototype scope that contains the
  12820. // declaration.
  12821. //
  12822. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  12823. // C structs and unions.
  12824. //
  12825. // It is an error in C++ to declare (rather than define) an enum
  12826. // type, including via an elaborated type specifier. We'll
  12827. // diagnose that later; for now, declare the enum in the same
  12828. // scope as we would have picked for any other tag type.
  12829. //
  12830. // GNU C also supports this behavior as part of its incomplete
  12831. // enum types extension, while GNU C++ does not.
  12832. //
  12833. // Find the context where we'll be declaring the tag.
  12834. // FIXME: We would like to maintain the current DeclContext as the
  12835. // lexical context,
  12836. SearchDC = getTagInjectionContext(SearchDC);
  12837. // Find the scope where we'll be declaring the tag.
  12838. S = getTagInjectionScope(S, getLangOpts());
  12839. } else {
  12840. assert(TUK == TUK_Friend);
  12841. // C++ [namespace.memdef]p3:
  12842. // If a friend declaration in a non-local class first declares a
  12843. // class or function, the friend class or function is a member of
  12844. // the innermost enclosing namespace.
  12845. SearchDC = SearchDC->getEnclosingNamespaceContext();
  12846. }
  12847. // In C++, we need to do a redeclaration lookup to properly
  12848. // diagnose some problems.
  12849. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  12850. // hidden declaration so that we don't get ambiguity errors when using a
  12851. // type declared by an elaborated-type-specifier. In C that is not correct
  12852. // and we should instead merge compatible types found by lookup.
  12853. if (getLangOpts().CPlusPlus) {
  12854. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  12855. LookupQualifiedName(Previous, SearchDC);
  12856. } else {
  12857. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  12858. LookupName(Previous, S);
  12859. }
  12860. }
  12861. // If we have a known previous declaration to use, then use it.
  12862. if (Previous.empty() && SkipBody && SkipBody->Previous)
  12863. Previous.addDecl(SkipBody->Previous);
  12864. if (!Previous.empty()) {
  12865. NamedDecl *PrevDecl = Previous.getFoundDecl();
  12866. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  12867. // It's okay to have a tag decl in the same scope as a typedef
  12868. // which hides a tag decl in the same scope. Finding this
  12869. // insanity with a redeclaration lookup can only actually happen
  12870. // in C++.
  12871. //
  12872. // This is also okay for elaborated-type-specifiers, which is
  12873. // technically forbidden by the current standard but which is
  12874. // okay according to the likely resolution of an open issue;
  12875. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  12876. if (getLangOpts().CPlusPlus) {
  12877. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  12878. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  12879. TagDecl *Tag = TT->getDecl();
  12880. if (Tag->getDeclName() == Name &&
  12881. Tag->getDeclContext()->getRedeclContext()
  12882. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  12883. PrevDecl = Tag;
  12884. Previous.clear();
  12885. Previous.addDecl(Tag);
  12886. Previous.resolveKind();
  12887. }
  12888. }
  12889. }
  12890. }
  12891. // If this is a redeclaration of a using shadow declaration, it must
  12892. // declare a tag in the same context. In MSVC mode, we allow a
  12893. // redefinition if either context is within the other.
  12894. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  12895. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  12896. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  12897. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  12898. !(OldTag && isAcceptableTagRedeclContext(
  12899. *this, OldTag->getDeclContext(), SearchDC))) {
  12900. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  12901. Diag(Shadow->getTargetDecl()->getLocation(),
  12902. diag::note_using_decl_target);
  12903. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  12904. << 0;
  12905. // Recover by ignoring the old declaration.
  12906. Previous.clear();
  12907. goto CreateNewDecl;
  12908. }
  12909. }
  12910. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  12911. // If this is a use of a previous tag, or if the tag is already declared
  12912. // in the same scope (so that the definition/declaration completes or
  12913. // rementions the tag), reuse the decl.
  12914. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  12915. isDeclInScope(DirectPrevDecl, SearchDC, S,
  12916. SS.isNotEmpty() || isMemberSpecialization)) {
  12917. // Make sure that this wasn't declared as an enum and now used as a
  12918. // struct or something similar.
  12919. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  12920. TUK == TUK_Definition, KWLoc,
  12921. Name)) {
  12922. bool SafeToContinue
  12923. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  12924. Kind != TTK_Enum);
  12925. if (SafeToContinue)
  12926. Diag(KWLoc, diag::err_use_with_wrong_tag)
  12927. << Name
  12928. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  12929. PrevTagDecl->getKindName());
  12930. else
  12931. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  12932. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  12933. if (SafeToContinue)
  12934. Kind = PrevTagDecl->getTagKind();
  12935. else {
  12936. // Recover by making this an anonymous redefinition.
  12937. Name = nullptr;
  12938. Previous.clear();
  12939. Invalid = true;
  12940. }
  12941. }
  12942. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  12943. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  12944. // If this is an elaborated-type-specifier for a scoped enumeration,
  12945. // the 'class' keyword is not necessary and not permitted.
  12946. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12947. if (ScopedEnum)
  12948. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  12949. << PrevEnum->isScoped()
  12950. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  12951. return PrevTagDecl;
  12952. }
  12953. QualType EnumUnderlyingTy;
  12954. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  12955. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  12956. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  12957. EnumUnderlyingTy = QualType(T, 0);
  12958. // All conflicts with previous declarations are recovered by
  12959. // returning the previous declaration, unless this is a definition,
  12960. // in which case we want the caller to bail out.
  12961. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  12962. ScopedEnum, EnumUnderlyingTy,
  12963. IsFixed, PrevEnum))
  12964. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  12965. }
  12966. // C++11 [class.mem]p1:
  12967. // A member shall not be declared twice in the member-specification,
  12968. // except that a nested class or member class template can be declared
  12969. // and then later defined.
  12970. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  12971. S->isDeclScope(PrevDecl)) {
  12972. Diag(NameLoc, diag::ext_member_redeclared);
  12973. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  12974. }
  12975. if (!Invalid) {
  12976. // If this is a use, just return the declaration we found, unless
  12977. // we have attributes.
  12978. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12979. if (!Attrs.empty()) {
  12980. // FIXME: Diagnose these attributes. For now, we create a new
  12981. // declaration to hold them.
  12982. } else if (TUK == TUK_Reference &&
  12983. (PrevTagDecl->getFriendObjectKind() ==
  12984. Decl::FOK_Undeclared ||
  12985. PrevDecl->getOwningModule() != getCurrentModule()) &&
  12986. SS.isEmpty()) {
  12987. // This declaration is a reference to an existing entity, but
  12988. // has different visibility from that entity: it either makes
  12989. // a friend visible or it makes a type visible in a new module.
  12990. // In either case, create a new declaration. We only do this if
  12991. // the declaration would have meant the same thing if no prior
  12992. // declaration were found, that is, if it was found in the same
  12993. // scope where we would have injected a declaration.
  12994. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  12995. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  12996. return PrevTagDecl;
  12997. // This is in the injected scope, create a new declaration in
  12998. // that scope.
  12999. S = getTagInjectionScope(S, getLangOpts());
  13000. } else {
  13001. return PrevTagDecl;
  13002. }
  13003. }
  13004. // Diagnose attempts to redefine a tag.
  13005. if (TUK == TUK_Definition) {
  13006. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  13007. // If we're defining a specialization and the previous definition
  13008. // is from an implicit instantiation, don't emit an error
  13009. // here; we'll catch this in the general case below.
  13010. bool IsExplicitSpecializationAfterInstantiation = false;
  13011. if (isMemberSpecialization) {
  13012. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  13013. IsExplicitSpecializationAfterInstantiation =
  13014. RD->getTemplateSpecializationKind() !=
  13015. TSK_ExplicitSpecialization;
  13016. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  13017. IsExplicitSpecializationAfterInstantiation =
  13018. ED->getTemplateSpecializationKind() !=
  13019. TSK_ExplicitSpecialization;
  13020. }
  13021. // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
  13022. // not keep more that one definition around (merge them). However,
  13023. // ensure the decl passes the structural compatibility check in
  13024. // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
  13025. NamedDecl *Hidden = nullptr;
  13026. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  13027. // There is a definition of this tag, but it is not visible. We
  13028. // explicitly make use of C++'s one definition rule here, and
  13029. // assume that this definition is identical to the hidden one
  13030. // we already have. Make the existing definition visible and
  13031. // use it in place of this one.
  13032. if (!getLangOpts().CPlusPlus) {
  13033. // Postpone making the old definition visible until after we
  13034. // complete parsing the new one and do the structural
  13035. // comparison.
  13036. SkipBody->CheckSameAsPrevious = true;
  13037. SkipBody->New = createTagFromNewDecl();
  13038. SkipBody->Previous = Def;
  13039. return Def;
  13040. } else {
  13041. SkipBody->ShouldSkip = true;
  13042. SkipBody->Previous = Def;
  13043. makeMergedDefinitionVisible(Hidden);
  13044. // Carry on and handle it like a normal definition. We'll
  13045. // skip starting the definitiion later.
  13046. }
  13047. } else if (!IsExplicitSpecializationAfterInstantiation) {
  13048. // A redeclaration in function prototype scope in C isn't
  13049. // visible elsewhere, so merely issue a warning.
  13050. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  13051. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  13052. else
  13053. Diag(NameLoc, diag::err_redefinition) << Name;
  13054. notePreviousDefinition(Def,
  13055. NameLoc.isValid() ? NameLoc : KWLoc);
  13056. // If this is a redefinition, recover by making this
  13057. // struct be anonymous, which will make any later
  13058. // references get the previous definition.
  13059. Name = nullptr;
  13060. Previous.clear();
  13061. Invalid = true;
  13062. }
  13063. } else {
  13064. // If the type is currently being defined, complain
  13065. // about a nested redefinition.
  13066. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  13067. if (TD->isBeingDefined()) {
  13068. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  13069. Diag(PrevTagDecl->getLocation(),
  13070. diag::note_previous_definition);
  13071. Name = nullptr;
  13072. Previous.clear();
  13073. Invalid = true;
  13074. }
  13075. }
  13076. // Okay, this is definition of a previously declared or referenced
  13077. // tag. We're going to create a new Decl for it.
  13078. }
  13079. // Okay, we're going to make a redeclaration. If this is some kind
  13080. // of reference, make sure we build the redeclaration in the same DC
  13081. // as the original, and ignore the current access specifier.
  13082. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  13083. SearchDC = PrevTagDecl->getDeclContext();
  13084. AS = AS_none;
  13085. }
  13086. }
  13087. // If we get here we have (another) forward declaration or we
  13088. // have a definition. Just create a new decl.
  13089. } else {
  13090. // If we get here, this is a definition of a new tag type in a nested
  13091. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  13092. // new decl/type. We set PrevDecl to NULL so that the entities
  13093. // have distinct types.
  13094. Previous.clear();
  13095. }
  13096. // If we get here, we're going to create a new Decl. If PrevDecl
  13097. // is non-NULL, it's a definition of the tag declared by
  13098. // PrevDecl. If it's NULL, we have a new definition.
  13099. // Otherwise, PrevDecl is not a tag, but was found with tag
  13100. // lookup. This is only actually possible in C++, where a few
  13101. // things like templates still live in the tag namespace.
  13102. } else {
  13103. // Use a better diagnostic if an elaborated-type-specifier
  13104. // found the wrong kind of type on the first
  13105. // (non-redeclaration) lookup.
  13106. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  13107. !Previous.isForRedeclaration()) {
  13108. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13109. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  13110. << Kind;
  13111. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  13112. Invalid = true;
  13113. // Otherwise, only diagnose if the declaration is in scope.
  13114. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  13115. SS.isNotEmpty() || isMemberSpecialization)) {
  13116. // do nothing
  13117. // Diagnose implicit declarations introduced by elaborated types.
  13118. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13119. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13120. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  13121. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13122. Invalid = true;
  13123. // Otherwise it's a declaration. Call out a particularly common
  13124. // case here.
  13125. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  13126. unsigned Kind = 0;
  13127. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  13128. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  13129. << Name << Kind << TND->getUnderlyingType();
  13130. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13131. Invalid = true;
  13132. // Otherwise, diagnose.
  13133. } else {
  13134. // The tag name clashes with something else in the target scope,
  13135. // issue an error and recover by making this tag be anonymous.
  13136. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  13137. notePreviousDefinition(PrevDecl, NameLoc);
  13138. Name = nullptr;
  13139. Invalid = true;
  13140. }
  13141. // The existing declaration isn't relevant to us; we're in a
  13142. // new scope, so clear out the previous declaration.
  13143. Previous.clear();
  13144. }
  13145. }
  13146. CreateNewDecl:
  13147. TagDecl *PrevDecl = nullptr;
  13148. if (Previous.isSingleResult())
  13149. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  13150. // If there is an identifier, use the location of the identifier as the
  13151. // location of the decl, otherwise use the location of the struct/union
  13152. // keyword.
  13153. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  13154. // Otherwise, create a new declaration. If there is a previous
  13155. // declaration of the same entity, the two will be linked via
  13156. // PrevDecl.
  13157. TagDecl *New;
  13158. if (Kind == TTK_Enum) {
  13159. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13160. // enum X { A, B, C } D; D should chain to X.
  13161. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  13162. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  13163. ScopedEnumUsesClassTag, IsFixed);
  13164. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  13165. StdAlignValT = cast<EnumDecl>(New);
  13166. // If this is an undefined enum, warn.
  13167. if (TUK != TUK_Definition && !Invalid) {
  13168. TagDecl *Def;
  13169. if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
  13170. // C++0x: 7.2p2: opaque-enum-declaration.
  13171. // Conflicts are diagnosed above. Do nothing.
  13172. }
  13173. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  13174. Diag(Loc, diag::ext_forward_ref_enum_def)
  13175. << New;
  13176. Diag(Def->getLocation(), diag::note_previous_definition);
  13177. } else {
  13178. unsigned DiagID = diag::ext_forward_ref_enum;
  13179. if (getLangOpts().MSVCCompat)
  13180. DiagID = diag::ext_ms_forward_ref_enum;
  13181. else if (getLangOpts().CPlusPlus)
  13182. DiagID = diag::err_forward_ref_enum;
  13183. Diag(Loc, DiagID);
  13184. }
  13185. }
  13186. if (EnumUnderlying) {
  13187. EnumDecl *ED = cast<EnumDecl>(New);
  13188. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  13189. ED->setIntegerTypeSourceInfo(TI);
  13190. else
  13191. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  13192. ED->setPromotionType(ED->getIntegerType());
  13193. assert(ED->isComplete() && "enum with type should be complete");
  13194. }
  13195. } else {
  13196. // struct/union/class
  13197. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13198. // struct X { int A; } D; D should chain to X.
  13199. if (getLangOpts().CPlusPlus) {
  13200. // FIXME: Look for a way to use RecordDecl for simple structs.
  13201. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13202. cast_or_null<CXXRecordDecl>(PrevDecl));
  13203. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  13204. StdBadAlloc = cast<CXXRecordDecl>(New);
  13205. } else
  13206. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13207. cast_or_null<RecordDecl>(PrevDecl));
  13208. }
  13209. // C++11 [dcl.type]p3:
  13210. // A type-specifier-seq shall not define a class or enumeration [...].
  13211. if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
  13212. TUK == TUK_Definition) {
  13213. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  13214. << Context.getTagDeclType(New);
  13215. Invalid = true;
  13216. }
  13217. if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
  13218. DC->getDeclKind() == Decl::Enum) {
  13219. Diag(New->getLocation(), diag::err_type_defined_in_enum)
  13220. << Context.getTagDeclType(New);
  13221. Invalid = true;
  13222. }
  13223. // Maybe add qualifier info.
  13224. if (SS.isNotEmpty()) {
  13225. if (SS.isSet()) {
  13226. // If this is either a declaration or a definition, check the
  13227. // nested-name-specifier against the current context.
  13228. if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
  13229. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
  13230. isMemberSpecialization))
  13231. Invalid = true;
  13232. New->setQualifierInfo(SS.getWithLocInContext(Context));
  13233. if (TemplateParameterLists.size() > 0) {
  13234. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  13235. }
  13236. }
  13237. else
  13238. Invalid = true;
  13239. }
  13240. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  13241. // Add alignment attributes if necessary; these attributes are checked when
  13242. // the ASTContext lays out the structure.
  13243. //
  13244. // It is important for implementing the correct semantics that this
  13245. // happen here (in ActOnTag). The #pragma pack stack is
  13246. // maintained as a result of parser callbacks which can occur at
  13247. // many points during the parsing of a struct declaration (because
  13248. // the #pragma tokens are effectively skipped over during the
  13249. // parsing of the struct).
  13250. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  13251. AddAlignmentAttributesForRecord(RD);
  13252. AddMsStructLayoutForRecord(RD);
  13253. }
  13254. }
  13255. if (ModulePrivateLoc.isValid()) {
  13256. if (isMemberSpecialization)
  13257. Diag(New->getLocation(), diag::err_module_private_specialization)
  13258. << 2
  13259. << FixItHint::CreateRemoval(ModulePrivateLoc);
  13260. // __module_private__ does not apply to local classes. However, we only
  13261. // diagnose this as an error when the declaration specifiers are
  13262. // freestanding. Here, we just ignore the __module_private__.
  13263. else if (!SearchDC->isFunctionOrMethod())
  13264. New->setModulePrivate();
  13265. }
  13266. // If this is a specialization of a member class (of a class template),
  13267. // check the specialization.
  13268. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  13269. Invalid = true;
  13270. // If we're declaring or defining a tag in function prototype scope in C,
  13271. // note that this type can only be used within the function and add it to
  13272. // the list of decls to inject into the function definition scope.
  13273. if ((Name || Kind == TTK_Enum) &&
  13274. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  13275. if (getLangOpts().CPlusPlus) {
  13276. // C++ [dcl.fct]p6:
  13277. // Types shall not be defined in return or parameter types.
  13278. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  13279. Diag(Loc, diag::err_type_defined_in_param_type)
  13280. << Name;
  13281. Invalid = true;
  13282. }
  13283. } else if (!PrevDecl) {
  13284. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  13285. }
  13286. }
  13287. if (Invalid)
  13288. New->setInvalidDecl();
  13289. // Set the lexical context. If the tag has a C++ scope specifier, the
  13290. // lexical context will be different from the semantic context.
  13291. New->setLexicalDeclContext(CurContext);
  13292. // Mark this as a friend decl if applicable.
  13293. // In Microsoft mode, a friend declaration also acts as a forward
  13294. // declaration so we always pass true to setObjectOfFriendDecl to make
  13295. // the tag name visible.
  13296. if (TUK == TUK_Friend)
  13297. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  13298. // Set the access specifier.
  13299. if (!Invalid && SearchDC->isRecord())
  13300. SetMemberAccessSpecifier(New, PrevDecl, AS);
  13301. if (PrevDecl)
  13302. CheckRedeclarationModuleOwnership(New, PrevDecl);
  13303. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  13304. New->startDefinition();
  13305. ProcessDeclAttributeList(S, New, Attrs);
  13306. AddPragmaAttributes(S, New);
  13307. // If this has an identifier, add it to the scope stack.
  13308. if (TUK == TUK_Friend) {
  13309. // We might be replacing an existing declaration in the lookup tables;
  13310. // if so, borrow its access specifier.
  13311. if (PrevDecl)
  13312. New->setAccess(PrevDecl->getAccess());
  13313. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  13314. DC->makeDeclVisibleInContext(New);
  13315. if (Name) // can be null along some error paths
  13316. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  13317. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  13318. } else if (Name) {
  13319. S = getNonFieldDeclScope(S);
  13320. PushOnScopeChains(New, S, true);
  13321. } else {
  13322. CurContext->addDecl(New);
  13323. }
  13324. // If this is the C FILE type, notify the AST context.
  13325. if (IdentifierInfo *II = New->getIdentifier())
  13326. if (!New->isInvalidDecl() &&
  13327. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  13328. II->isStr("FILE"))
  13329. Context.setFILEDecl(New);
  13330. if (PrevDecl)
  13331. mergeDeclAttributes(New, PrevDecl);
  13332. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13333. // record.
  13334. AddPushedVisibilityAttribute(New);
  13335. if (isMemberSpecialization && !New->isInvalidDecl())
  13336. CompleteMemberSpecialization(New, Previous);
  13337. OwnedDecl = true;
  13338. // In C++, don't return an invalid declaration. We can't recover well from
  13339. // the cases where we make the type anonymous.
  13340. if (Invalid && getLangOpts().CPlusPlus) {
  13341. if (New->isBeingDefined())
  13342. if (auto RD = dyn_cast<RecordDecl>(New))
  13343. RD->completeDefinition();
  13344. return nullptr;
  13345. } else if (SkipBody && SkipBody->ShouldSkip) {
  13346. return SkipBody->Previous;
  13347. } else {
  13348. return New;
  13349. }
  13350. }
  13351. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  13352. AdjustDeclIfTemplate(TagD);
  13353. TagDecl *Tag = cast<TagDecl>(TagD);
  13354. // Enter the tag context.
  13355. PushDeclContext(S, Tag);
  13356. ActOnDocumentableDecl(TagD);
  13357. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13358. // record.
  13359. AddPushedVisibilityAttribute(Tag);
  13360. }
  13361. bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
  13362. SkipBodyInfo &SkipBody) {
  13363. if (!hasStructuralCompatLayout(Prev, SkipBody.New))
  13364. return false;
  13365. // Make the previous decl visible.
  13366. makeMergedDefinitionVisible(SkipBody.Previous);
  13367. return true;
  13368. }
  13369. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  13370. assert(isa<ObjCContainerDecl>(IDecl) &&
  13371. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  13372. DeclContext *OCD = cast<DeclContext>(IDecl);
  13373. assert(getContainingDC(OCD) == CurContext &&
  13374. "The next DeclContext should be lexically contained in the current one.");
  13375. CurContext = OCD;
  13376. return IDecl;
  13377. }
  13378. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  13379. SourceLocation FinalLoc,
  13380. bool IsFinalSpelledSealed,
  13381. SourceLocation LBraceLoc) {
  13382. AdjustDeclIfTemplate(TagD);
  13383. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  13384. FieldCollector->StartClass();
  13385. if (!Record->getIdentifier())
  13386. return;
  13387. if (FinalLoc.isValid())
  13388. Record->addAttr(new (Context)
  13389. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  13390. // C++ [class]p2:
  13391. // [...] The class-name is also inserted into the scope of the
  13392. // class itself; this is known as the injected-class-name. For
  13393. // purposes of access checking, the injected-class-name is treated
  13394. // as if it were a public member name.
  13395. CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
  13396. Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
  13397. Record->getLocation(), Record->getIdentifier(),
  13398. /*PrevDecl=*/nullptr,
  13399. /*DelayTypeCreation=*/true);
  13400. Context.getTypeDeclType(InjectedClassName, Record);
  13401. InjectedClassName->setImplicit();
  13402. InjectedClassName->setAccess(AS_public);
  13403. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  13404. InjectedClassName->setDescribedClassTemplate(Template);
  13405. PushOnScopeChains(InjectedClassName, S);
  13406. assert(InjectedClassName->isInjectedClassName() &&
  13407. "Broken injected-class-name");
  13408. }
  13409. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  13410. SourceRange BraceRange) {
  13411. AdjustDeclIfTemplate(TagD);
  13412. TagDecl *Tag = cast<TagDecl>(TagD);
  13413. Tag->setBraceRange(BraceRange);
  13414. // Make sure we "complete" the definition even it is invalid.
  13415. if (Tag->isBeingDefined()) {
  13416. assert(Tag->isInvalidDecl() && "We should already have completed it");
  13417. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13418. RD->completeDefinition();
  13419. }
  13420. if (isa<CXXRecordDecl>(Tag)) {
  13421. FieldCollector->FinishClass();
  13422. }
  13423. // Exit this scope of this tag's definition.
  13424. PopDeclContext();
  13425. if (getCurLexicalContext()->isObjCContainer() &&
  13426. Tag->getDeclContext()->isFileContext())
  13427. Tag->setTopLevelDeclInObjCContainer();
  13428. // Notify the consumer that we've defined a tag.
  13429. if (!Tag->isInvalidDecl())
  13430. Consumer.HandleTagDeclDefinition(Tag);
  13431. }
  13432. void Sema::ActOnObjCContainerFinishDefinition() {
  13433. // Exit this scope of this interface definition.
  13434. PopDeclContext();
  13435. }
  13436. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  13437. assert(DC == CurContext && "Mismatch of container contexts");
  13438. OriginalLexicalContext = DC;
  13439. ActOnObjCContainerFinishDefinition();
  13440. }
  13441. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  13442. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  13443. OriginalLexicalContext = nullptr;
  13444. }
  13445. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  13446. AdjustDeclIfTemplate(TagD);
  13447. TagDecl *Tag = cast<TagDecl>(TagD);
  13448. Tag->setInvalidDecl();
  13449. // Make sure we "complete" the definition even it is invalid.
  13450. if (Tag->isBeingDefined()) {
  13451. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13452. RD->completeDefinition();
  13453. }
  13454. // We're undoing ActOnTagStartDefinition here, not
  13455. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  13456. // the FieldCollector.
  13457. PopDeclContext();
  13458. }
  13459. // Note that FieldName may be null for anonymous bitfields.
  13460. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  13461. IdentifierInfo *FieldName,
  13462. QualType FieldTy, bool IsMsStruct,
  13463. Expr *BitWidth, bool *ZeroWidth) {
  13464. // Default to true; that shouldn't confuse checks for emptiness
  13465. if (ZeroWidth)
  13466. *ZeroWidth = true;
  13467. // C99 6.7.2.1p4 - verify the field type.
  13468. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  13469. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  13470. // Handle incomplete types with specific error.
  13471. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  13472. return ExprError();
  13473. if (FieldName)
  13474. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  13475. << FieldName << FieldTy << BitWidth->getSourceRange();
  13476. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  13477. << FieldTy << BitWidth->getSourceRange();
  13478. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  13479. UPPC_BitFieldWidth))
  13480. return ExprError();
  13481. // If the bit-width is type- or value-dependent, don't try to check
  13482. // it now.
  13483. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  13484. return BitWidth;
  13485. llvm::APSInt Value;
  13486. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  13487. if (ICE.isInvalid())
  13488. return ICE;
  13489. BitWidth = ICE.get();
  13490. if (Value != 0 && ZeroWidth)
  13491. *ZeroWidth = false;
  13492. // Zero-width bitfield is ok for anonymous field.
  13493. if (Value == 0 && FieldName)
  13494. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  13495. if (Value.isSigned() && Value.isNegative()) {
  13496. if (FieldName)
  13497. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  13498. << FieldName << Value.toString(10);
  13499. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  13500. << Value.toString(10);
  13501. }
  13502. if (!FieldTy->isDependentType()) {
  13503. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  13504. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  13505. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  13506. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  13507. // ABI.
  13508. bool CStdConstraintViolation =
  13509. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  13510. bool MSBitfieldViolation =
  13511. Value.ugt(TypeStorageSize) &&
  13512. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  13513. if (CStdConstraintViolation || MSBitfieldViolation) {
  13514. unsigned DiagWidth =
  13515. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  13516. if (FieldName)
  13517. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  13518. << FieldName << (unsigned)Value.getZExtValue()
  13519. << !CStdConstraintViolation << DiagWidth;
  13520. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  13521. << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
  13522. << DiagWidth;
  13523. }
  13524. // Warn on types where the user might conceivably expect to get all
  13525. // specified bits as value bits: that's all integral types other than
  13526. // 'bool'.
  13527. if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
  13528. if (FieldName)
  13529. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  13530. << FieldName << (unsigned)Value.getZExtValue()
  13531. << (unsigned)TypeWidth;
  13532. else
  13533. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  13534. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  13535. }
  13536. }
  13537. return BitWidth;
  13538. }
  13539. /// ActOnField - Each field of a C struct/union is passed into this in order
  13540. /// to create a FieldDecl object for it.
  13541. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  13542. Declarator &D, Expr *BitfieldWidth) {
  13543. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  13544. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  13545. /*InitStyle=*/ICIS_NoInit, AS_public);
  13546. return Res;
  13547. }
  13548. /// HandleField - Analyze a field of a C struct or a C++ data member.
  13549. ///
  13550. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  13551. SourceLocation DeclStart,
  13552. Declarator &D, Expr *BitWidth,
  13553. InClassInitStyle InitStyle,
  13554. AccessSpecifier AS) {
  13555. if (D.isDecompositionDeclarator()) {
  13556. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  13557. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  13558. << Decomp.getSourceRange();
  13559. return nullptr;
  13560. }
  13561. IdentifierInfo *II = D.getIdentifier();
  13562. SourceLocation Loc = DeclStart;
  13563. if (II) Loc = D.getIdentifierLoc();
  13564. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13565. QualType T = TInfo->getType();
  13566. if (getLangOpts().CPlusPlus) {
  13567. CheckExtraCXXDefaultArguments(D);
  13568. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  13569. UPPC_DataMemberType)) {
  13570. D.setInvalidType();
  13571. T = Context.IntTy;
  13572. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  13573. }
  13574. }
  13575. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  13576. if (D.getDeclSpec().isInlineSpecified())
  13577. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  13578. << getLangOpts().CPlusPlus17;
  13579. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  13580. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  13581. diag::err_invalid_thread)
  13582. << DeclSpec::getSpecifierName(TSCS);
  13583. // Check to see if this name was declared as a member previously
  13584. NamedDecl *PrevDecl = nullptr;
  13585. LookupResult Previous(*this, II, Loc, LookupMemberName,
  13586. ForVisibleRedeclaration);
  13587. LookupName(Previous, S);
  13588. switch (Previous.getResultKind()) {
  13589. case LookupResult::Found:
  13590. case LookupResult::FoundUnresolvedValue:
  13591. PrevDecl = Previous.getAsSingle<NamedDecl>();
  13592. break;
  13593. case LookupResult::FoundOverloaded:
  13594. PrevDecl = Previous.getRepresentativeDecl();
  13595. break;
  13596. case LookupResult::NotFound:
  13597. case LookupResult::NotFoundInCurrentInstantiation:
  13598. case LookupResult::Ambiguous:
  13599. break;
  13600. }
  13601. Previous.suppressDiagnostics();
  13602. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13603. // Maybe we will complain about the shadowed template parameter.
  13604. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  13605. // Just pretend that we didn't see the previous declaration.
  13606. PrevDecl = nullptr;
  13607. }
  13608. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  13609. PrevDecl = nullptr;
  13610. bool Mutable
  13611. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  13612. SourceLocation TSSL = D.getBeginLoc();
  13613. FieldDecl *NewFD
  13614. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  13615. TSSL, AS, PrevDecl, &D);
  13616. if (NewFD->isInvalidDecl())
  13617. Record->setInvalidDecl();
  13618. if (D.getDeclSpec().isModulePrivateSpecified())
  13619. NewFD->setModulePrivate();
  13620. if (NewFD->isInvalidDecl() && PrevDecl) {
  13621. // Don't introduce NewFD into scope; there's already something
  13622. // with the same name in the same scope.
  13623. } else if (II) {
  13624. PushOnScopeChains(NewFD, S);
  13625. } else
  13626. Record->addDecl(NewFD);
  13627. return NewFD;
  13628. }
  13629. /// Build a new FieldDecl and check its well-formedness.
  13630. ///
  13631. /// This routine builds a new FieldDecl given the fields name, type,
  13632. /// record, etc. \p PrevDecl should refer to any previous declaration
  13633. /// with the same name and in the same scope as the field to be
  13634. /// created.
  13635. ///
  13636. /// \returns a new FieldDecl.
  13637. ///
  13638. /// \todo The Declarator argument is a hack. It will be removed once
  13639. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  13640. TypeSourceInfo *TInfo,
  13641. RecordDecl *Record, SourceLocation Loc,
  13642. bool Mutable, Expr *BitWidth,
  13643. InClassInitStyle InitStyle,
  13644. SourceLocation TSSL,
  13645. AccessSpecifier AS, NamedDecl *PrevDecl,
  13646. Declarator *D) {
  13647. IdentifierInfo *II = Name.getAsIdentifierInfo();
  13648. bool InvalidDecl = false;
  13649. if (D) InvalidDecl = D->isInvalidType();
  13650. // If we receive a broken type, recover by assuming 'int' and
  13651. // marking this declaration as invalid.
  13652. if (T.isNull()) {
  13653. InvalidDecl = true;
  13654. T = Context.IntTy;
  13655. }
  13656. QualType EltTy = Context.getBaseElementType(T);
  13657. if (!EltTy->isDependentType()) {
  13658. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  13659. // Fields of incomplete type force their record to be invalid.
  13660. Record->setInvalidDecl();
  13661. InvalidDecl = true;
  13662. } else {
  13663. NamedDecl *Def;
  13664. EltTy->isIncompleteType(&Def);
  13665. if (Def && Def->isInvalidDecl()) {
  13666. Record->setInvalidDecl();
  13667. InvalidDecl = true;
  13668. }
  13669. }
  13670. }
  13671. // TR 18037 does not allow fields to be declared with address space
  13672. if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
  13673. T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
  13674. Diag(Loc, diag::err_field_with_address_space);
  13675. Record->setInvalidDecl();
  13676. InvalidDecl = true;
  13677. }
  13678. if (LangOpts.OpenCL) {
  13679. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  13680. // used as structure or union field: image, sampler, event or block types.
  13681. if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
  13682. T->isBlockPointerType()) {
  13683. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  13684. Record->setInvalidDecl();
  13685. InvalidDecl = true;
  13686. }
  13687. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  13688. if (BitWidth) {
  13689. Diag(Loc, diag::err_opencl_bitfields);
  13690. InvalidDecl = true;
  13691. }
  13692. }
  13693. // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
  13694. if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
  13695. T.hasQualifiers()) {
  13696. InvalidDecl = true;
  13697. Diag(Loc, diag::err_anon_bitfield_qualifiers);
  13698. }
  13699. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  13700. // than a variably modified type.
  13701. if (!InvalidDecl && T->isVariablyModifiedType()) {
  13702. bool SizeIsNegative;
  13703. llvm::APSInt Oversized;
  13704. TypeSourceInfo *FixedTInfo =
  13705. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  13706. SizeIsNegative,
  13707. Oversized);
  13708. if (FixedTInfo) {
  13709. Diag(Loc, diag::warn_illegal_constant_array_size);
  13710. TInfo = FixedTInfo;
  13711. T = FixedTInfo->getType();
  13712. } else {
  13713. if (SizeIsNegative)
  13714. Diag(Loc, diag::err_typecheck_negative_array_size);
  13715. else if (Oversized.getBoolValue())
  13716. Diag(Loc, diag::err_array_too_large)
  13717. << Oversized.toString(10);
  13718. else
  13719. Diag(Loc, diag::err_typecheck_field_variable_size);
  13720. InvalidDecl = true;
  13721. }
  13722. }
  13723. // Fields can not have abstract class types
  13724. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  13725. diag::err_abstract_type_in_decl,
  13726. AbstractFieldType))
  13727. InvalidDecl = true;
  13728. bool ZeroWidth = false;
  13729. if (InvalidDecl)
  13730. BitWidth = nullptr;
  13731. // If this is declared as a bit-field, check the bit-field.
  13732. if (BitWidth) {
  13733. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  13734. &ZeroWidth).get();
  13735. if (!BitWidth) {
  13736. InvalidDecl = true;
  13737. BitWidth = nullptr;
  13738. ZeroWidth = false;
  13739. }
  13740. }
  13741. // Check that 'mutable' is consistent with the type of the declaration.
  13742. if (!InvalidDecl && Mutable) {
  13743. unsigned DiagID = 0;
  13744. if (T->isReferenceType())
  13745. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  13746. : diag::err_mutable_reference;
  13747. else if (T.isConstQualified())
  13748. DiagID = diag::err_mutable_const;
  13749. if (DiagID) {
  13750. SourceLocation ErrLoc = Loc;
  13751. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  13752. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  13753. Diag(ErrLoc, DiagID);
  13754. if (DiagID != diag::ext_mutable_reference) {
  13755. Mutable = false;
  13756. InvalidDecl = true;
  13757. }
  13758. }
  13759. }
  13760. // C++11 [class.union]p8 (DR1460):
  13761. // At most one variant member of a union may have a
  13762. // brace-or-equal-initializer.
  13763. if (InitStyle != ICIS_NoInit)
  13764. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  13765. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  13766. BitWidth, Mutable, InitStyle);
  13767. if (InvalidDecl)
  13768. NewFD->setInvalidDecl();
  13769. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  13770. Diag(Loc, diag::err_duplicate_member) << II;
  13771. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  13772. NewFD->setInvalidDecl();
  13773. }
  13774. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  13775. if (Record->isUnion()) {
  13776. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  13777. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  13778. if (RDecl->getDefinition()) {
  13779. // C++ [class.union]p1: An object of a class with a non-trivial
  13780. // constructor, a non-trivial copy constructor, a non-trivial
  13781. // destructor, or a non-trivial copy assignment operator
  13782. // cannot be a member of a union, nor can an array of such
  13783. // objects.
  13784. if (CheckNontrivialField(NewFD))
  13785. NewFD->setInvalidDecl();
  13786. }
  13787. }
  13788. // C++ [class.union]p1: If a union contains a member of reference type,
  13789. // the program is ill-formed, except when compiling with MSVC extensions
  13790. // enabled.
  13791. if (EltTy->isReferenceType()) {
  13792. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  13793. diag::ext_union_member_of_reference_type :
  13794. diag::err_union_member_of_reference_type)
  13795. << NewFD->getDeclName() << EltTy;
  13796. if (!getLangOpts().MicrosoftExt)
  13797. NewFD->setInvalidDecl();
  13798. }
  13799. }
  13800. }
  13801. // FIXME: We need to pass in the attributes given an AST
  13802. // representation, not a parser representation.
  13803. if (D) {
  13804. // FIXME: The current scope is almost... but not entirely... correct here.
  13805. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  13806. if (NewFD->hasAttrs())
  13807. CheckAlignasUnderalignment(NewFD);
  13808. }
  13809. // In auto-retain/release, infer strong retension for fields of
  13810. // retainable type.
  13811. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  13812. NewFD->setInvalidDecl();
  13813. if (T.isObjCGCWeak())
  13814. Diag(Loc, diag::warn_attribute_weak_on_field);
  13815. NewFD->setAccess(AS);
  13816. return NewFD;
  13817. }
  13818. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  13819. assert(FD);
  13820. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  13821. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  13822. return false;
  13823. QualType EltTy = Context.getBaseElementType(FD->getType());
  13824. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  13825. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  13826. if (RDecl->getDefinition()) {
  13827. // We check for copy constructors before constructors
  13828. // because otherwise we'll never get complaints about
  13829. // copy constructors.
  13830. CXXSpecialMember member = CXXInvalid;
  13831. // We're required to check for any non-trivial constructors. Since the
  13832. // implicit default constructor is suppressed if there are any
  13833. // user-declared constructors, we just need to check that there is a
  13834. // trivial default constructor and a trivial copy constructor. (We don't
  13835. // worry about move constructors here, since this is a C++98 check.)
  13836. if (RDecl->hasNonTrivialCopyConstructor())
  13837. member = CXXCopyConstructor;
  13838. else if (!RDecl->hasTrivialDefaultConstructor())
  13839. member = CXXDefaultConstructor;
  13840. else if (RDecl->hasNonTrivialCopyAssignment())
  13841. member = CXXCopyAssignment;
  13842. else if (RDecl->hasNonTrivialDestructor())
  13843. member = CXXDestructor;
  13844. if (member != CXXInvalid) {
  13845. if (!getLangOpts().CPlusPlus11 &&
  13846. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  13847. // Objective-C++ ARC: it is an error to have a non-trivial field of
  13848. // a union. However, system headers in Objective-C programs
  13849. // occasionally have Objective-C lifetime objects within unions,
  13850. // and rather than cause the program to fail, we make those
  13851. // members unavailable.
  13852. SourceLocation Loc = FD->getLocation();
  13853. if (getSourceManager().isInSystemHeader(Loc)) {
  13854. if (!FD->hasAttr<UnavailableAttr>())
  13855. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  13856. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  13857. return false;
  13858. }
  13859. }
  13860. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  13861. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  13862. diag::err_illegal_union_or_anon_struct_member)
  13863. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  13864. DiagnoseNontrivial(RDecl, member);
  13865. return !getLangOpts().CPlusPlus11;
  13866. }
  13867. }
  13868. }
  13869. return false;
  13870. }
  13871. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  13872. /// AST enum value.
  13873. static ObjCIvarDecl::AccessControl
  13874. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  13875. switch (ivarVisibility) {
  13876. default: llvm_unreachable("Unknown visitibility kind");
  13877. case tok::objc_private: return ObjCIvarDecl::Private;
  13878. case tok::objc_public: return ObjCIvarDecl::Public;
  13879. case tok::objc_protected: return ObjCIvarDecl::Protected;
  13880. case tok::objc_package: return ObjCIvarDecl::Package;
  13881. }
  13882. }
  13883. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  13884. /// in order to create an IvarDecl object for it.
  13885. Decl *Sema::ActOnIvar(Scope *S,
  13886. SourceLocation DeclStart,
  13887. Declarator &D, Expr *BitfieldWidth,
  13888. tok::ObjCKeywordKind Visibility) {
  13889. IdentifierInfo *II = D.getIdentifier();
  13890. Expr *BitWidth = (Expr*)BitfieldWidth;
  13891. SourceLocation Loc = DeclStart;
  13892. if (II) Loc = D.getIdentifierLoc();
  13893. // FIXME: Unnamed fields can be handled in various different ways, for
  13894. // example, unnamed unions inject all members into the struct namespace!
  13895. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13896. QualType T = TInfo->getType();
  13897. if (BitWidth) {
  13898. // 6.7.2.1p3, 6.7.2.1p4
  13899. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  13900. if (!BitWidth)
  13901. D.setInvalidType();
  13902. } else {
  13903. // Not a bitfield.
  13904. // validate II.
  13905. }
  13906. if (T->isReferenceType()) {
  13907. Diag(Loc, diag::err_ivar_reference_type);
  13908. D.setInvalidType();
  13909. }
  13910. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  13911. // than a variably modified type.
  13912. else if (T->isVariablyModifiedType()) {
  13913. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  13914. D.setInvalidType();
  13915. }
  13916. // Get the visibility (access control) for this ivar.
  13917. ObjCIvarDecl::AccessControl ac =
  13918. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  13919. : ObjCIvarDecl::None;
  13920. // Must set ivar's DeclContext to its enclosing interface.
  13921. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  13922. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  13923. return nullptr;
  13924. ObjCContainerDecl *EnclosingContext;
  13925. if (ObjCImplementationDecl *IMPDecl =
  13926. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  13927. if (LangOpts.ObjCRuntime.isFragile()) {
  13928. // Case of ivar declared in an implementation. Context is that of its class.
  13929. EnclosingContext = IMPDecl->getClassInterface();
  13930. assert(EnclosingContext && "Implementation has no class interface!");
  13931. }
  13932. else
  13933. EnclosingContext = EnclosingDecl;
  13934. } else {
  13935. if (ObjCCategoryDecl *CDecl =
  13936. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  13937. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  13938. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  13939. return nullptr;
  13940. }
  13941. }
  13942. EnclosingContext = EnclosingDecl;
  13943. }
  13944. // Construct the decl.
  13945. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  13946. DeclStart, Loc, II, T,
  13947. TInfo, ac, (Expr *)BitfieldWidth);
  13948. if (II) {
  13949. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  13950. ForVisibleRedeclaration);
  13951. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  13952. && !isa<TagDecl>(PrevDecl)) {
  13953. Diag(Loc, diag::err_duplicate_member) << II;
  13954. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  13955. NewID->setInvalidDecl();
  13956. }
  13957. }
  13958. // Process attributes attached to the ivar.
  13959. ProcessDeclAttributes(S, NewID, D);
  13960. if (D.isInvalidType())
  13961. NewID->setInvalidDecl();
  13962. // In ARC, infer 'retaining' for ivars of retainable type.
  13963. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  13964. NewID->setInvalidDecl();
  13965. if (D.getDeclSpec().isModulePrivateSpecified())
  13966. NewID->setModulePrivate();
  13967. if (II) {
  13968. // FIXME: When interfaces are DeclContexts, we'll need to add
  13969. // these to the interface.
  13970. S->AddDecl(NewID);
  13971. IdResolver.AddDecl(NewID);
  13972. }
  13973. if (LangOpts.ObjCRuntime.isNonFragile() &&
  13974. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  13975. Diag(Loc, diag::warn_ivars_in_interface);
  13976. return NewID;
  13977. }
  13978. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  13979. /// class and class extensions. For every class \@interface and class
  13980. /// extension \@interface, if the last ivar is a bitfield of any type,
  13981. /// then add an implicit `char :0` ivar to the end of that interface.
  13982. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  13983. SmallVectorImpl<Decl *> &AllIvarDecls) {
  13984. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  13985. return;
  13986. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  13987. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  13988. if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
  13989. return;
  13990. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  13991. if (!ID) {
  13992. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  13993. if (!CD->IsClassExtension())
  13994. return;
  13995. }
  13996. // No need to add this to end of @implementation.
  13997. else
  13998. return;
  13999. }
  14000. // All conditions are met. Add a new bitfield to the tail end of ivars.
  14001. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  14002. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  14003. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  14004. DeclLoc, DeclLoc, nullptr,
  14005. Context.CharTy,
  14006. Context.getTrivialTypeSourceInfo(Context.CharTy,
  14007. DeclLoc),
  14008. ObjCIvarDecl::Private, BW,
  14009. true);
  14010. AllIvarDecls.push_back(Ivar);
  14011. }
  14012. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  14013. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  14014. SourceLocation RBrac,
  14015. const ParsedAttributesView &Attrs) {
  14016. assert(EnclosingDecl && "missing record or interface decl");
  14017. // If this is an Objective-C @implementation or category and we have
  14018. // new fields here we should reset the layout of the interface since
  14019. // it will now change.
  14020. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  14021. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  14022. switch (DC->getKind()) {
  14023. default: break;
  14024. case Decl::ObjCCategory:
  14025. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  14026. break;
  14027. case Decl::ObjCImplementation:
  14028. Context.
  14029. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  14030. break;
  14031. }
  14032. }
  14033. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  14034. CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
  14035. // Start counting up the number of named members; make sure to include
  14036. // members of anonymous structs and unions in the total.
  14037. unsigned NumNamedMembers = 0;
  14038. if (Record) {
  14039. for (const auto *I : Record->decls()) {
  14040. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  14041. if (IFD->getDeclName())
  14042. ++NumNamedMembers;
  14043. }
  14044. }
  14045. // Verify that all the fields are okay.
  14046. SmallVector<FieldDecl*, 32> RecFields;
  14047. bool ObjCFieldLifetimeErrReported = false;
  14048. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  14049. i != end; ++i) {
  14050. FieldDecl *FD = cast<FieldDecl>(*i);
  14051. // Get the type for the field.
  14052. const Type *FDTy = FD->getType().getTypePtr();
  14053. if (!FD->isAnonymousStructOrUnion()) {
  14054. // Remember all fields written by the user.
  14055. RecFields.push_back(FD);
  14056. }
  14057. // If the field is already invalid for some reason, don't emit more
  14058. // diagnostics about it.
  14059. if (FD->isInvalidDecl()) {
  14060. EnclosingDecl->setInvalidDecl();
  14061. continue;
  14062. }
  14063. // C99 6.7.2.1p2:
  14064. // A structure or union shall not contain a member with
  14065. // incomplete or function type (hence, a structure shall not
  14066. // contain an instance of itself, but may contain a pointer to
  14067. // an instance of itself), except that the last member of a
  14068. // structure with more than one named member may have incomplete
  14069. // array type; such a structure (and any union containing,
  14070. // possibly recursively, a member that is such a structure)
  14071. // shall not be a member of a structure or an element of an
  14072. // array.
  14073. bool IsLastField = (i + 1 == Fields.end());
  14074. if (FDTy->isFunctionType()) {
  14075. // Field declared as a function.
  14076. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  14077. << FD->getDeclName();
  14078. FD->setInvalidDecl();
  14079. EnclosingDecl->setInvalidDecl();
  14080. continue;
  14081. } else if (FDTy->isIncompleteArrayType() &&
  14082. (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
  14083. if (Record) {
  14084. // Flexible array member.
  14085. // Microsoft and g++ is more permissive regarding flexible array.
  14086. // It will accept flexible array in union and also
  14087. // as the sole element of a struct/class.
  14088. unsigned DiagID = 0;
  14089. if (!Record->isUnion() && !IsLastField) {
  14090. Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
  14091. << FD->getDeclName() << FD->getType() << Record->getTagKind();
  14092. Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
  14093. FD->setInvalidDecl();
  14094. EnclosingDecl->setInvalidDecl();
  14095. continue;
  14096. } else if (Record->isUnion())
  14097. DiagID = getLangOpts().MicrosoftExt
  14098. ? diag::ext_flexible_array_union_ms
  14099. : getLangOpts().CPlusPlus
  14100. ? diag::ext_flexible_array_union_gnu
  14101. : diag::err_flexible_array_union;
  14102. else if (NumNamedMembers < 1)
  14103. DiagID = getLangOpts().MicrosoftExt
  14104. ? diag::ext_flexible_array_empty_aggregate_ms
  14105. : getLangOpts().CPlusPlus
  14106. ? diag::ext_flexible_array_empty_aggregate_gnu
  14107. : diag::err_flexible_array_empty_aggregate;
  14108. if (DiagID)
  14109. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  14110. << Record->getTagKind();
  14111. // While the layout of types that contain virtual bases is not specified
  14112. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  14113. // virtual bases after the derived members. This would make a flexible
  14114. // array member declared at the end of an object not adjacent to the end
  14115. // of the type.
  14116. if (CXXRecord && CXXRecord->getNumVBases() != 0)
  14117. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  14118. << FD->getDeclName() << Record->getTagKind();
  14119. if (!getLangOpts().C99)
  14120. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  14121. << FD->getDeclName() << Record->getTagKind();
  14122. // If the element type has a non-trivial destructor, we would not
  14123. // implicitly destroy the elements, so disallow it for now.
  14124. //
  14125. // FIXME: GCC allows this. We should probably either implicitly delete
  14126. // the destructor of the containing class, or just allow this.
  14127. QualType BaseElem = Context.getBaseElementType(FD->getType());
  14128. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  14129. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  14130. << FD->getDeclName() << FD->getType();
  14131. FD->setInvalidDecl();
  14132. EnclosingDecl->setInvalidDecl();
  14133. continue;
  14134. }
  14135. // Okay, we have a legal flexible array member at the end of the struct.
  14136. Record->setHasFlexibleArrayMember(true);
  14137. } else {
  14138. // In ObjCContainerDecl ivars with incomplete array type are accepted,
  14139. // unless they are followed by another ivar. That check is done
  14140. // elsewhere, after synthesized ivars are known.
  14141. }
  14142. } else if (!FDTy->isDependentType() &&
  14143. RequireCompleteType(FD->getLocation(), FD->getType(),
  14144. diag::err_field_incomplete)) {
  14145. // Incomplete type
  14146. FD->setInvalidDecl();
  14147. EnclosingDecl->setInvalidDecl();
  14148. continue;
  14149. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  14150. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  14151. // A type which contains a flexible array member is considered to be a
  14152. // flexible array member.
  14153. Record->setHasFlexibleArrayMember(true);
  14154. if (!Record->isUnion()) {
  14155. // If this is a struct/class and this is not the last element, reject
  14156. // it. Note that GCC supports variable sized arrays in the middle of
  14157. // structures.
  14158. if (!IsLastField)
  14159. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  14160. << FD->getDeclName() << FD->getType();
  14161. else {
  14162. // We support flexible arrays at the end of structs in
  14163. // other structs as an extension.
  14164. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  14165. << FD->getDeclName();
  14166. }
  14167. }
  14168. }
  14169. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  14170. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  14171. diag::err_abstract_type_in_decl,
  14172. AbstractIvarType)) {
  14173. // Ivars can not have abstract class types
  14174. FD->setInvalidDecl();
  14175. }
  14176. if (Record && FDTTy->getDecl()->hasObjectMember())
  14177. Record->setHasObjectMember(true);
  14178. if (Record && FDTTy->getDecl()->hasVolatileMember())
  14179. Record->setHasVolatileMember(true);
  14180. if (Record && Record->isUnion() &&
  14181. FD->getType().isNonTrivialPrimitiveCType(Context))
  14182. Diag(FD->getLocation(),
  14183. diag::err_nontrivial_primitive_type_in_union);
  14184. } else if (FDTy->isObjCObjectType()) {
  14185. /// A field cannot be an Objective-c object
  14186. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  14187. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  14188. QualType T = Context.getObjCObjectPointerType(FD->getType());
  14189. FD->setType(T);
  14190. } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  14191. Record && !ObjCFieldLifetimeErrReported && Record->isUnion() &&
  14192. !getLangOpts().CPlusPlus) {
  14193. // It's an error in ARC or Weak if a field has lifetime.
  14194. // We don't want to report this in a system header, though,
  14195. // so we just make the field unavailable.
  14196. // FIXME: that's really not sufficient; we need to make the type
  14197. // itself invalid to, say, initialize or copy.
  14198. QualType T = FD->getType();
  14199. if (T.hasNonTrivialObjCLifetime()) {
  14200. SourceLocation loc = FD->getLocation();
  14201. if (getSourceManager().isInSystemHeader(loc)) {
  14202. if (!FD->hasAttr<UnavailableAttr>()) {
  14203. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  14204. UnavailableAttr::IR_ARCFieldWithOwnership, loc));
  14205. }
  14206. } else {
  14207. Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
  14208. << T->isBlockPointerType() << Record->getTagKind();
  14209. }
  14210. ObjCFieldLifetimeErrReported = true;
  14211. }
  14212. } else if (getLangOpts().ObjC &&
  14213. getLangOpts().getGC() != LangOptions::NonGC &&
  14214. Record && !Record->hasObjectMember()) {
  14215. if (FD->getType()->isObjCObjectPointerType() ||
  14216. FD->getType().isObjCGCStrong())
  14217. Record->setHasObjectMember(true);
  14218. else if (Context.getAsArrayType(FD->getType())) {
  14219. QualType BaseType = Context.getBaseElementType(FD->getType());
  14220. if (BaseType->isRecordType() &&
  14221. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  14222. Record->setHasObjectMember(true);
  14223. else if (BaseType->isObjCObjectPointerType() ||
  14224. BaseType.isObjCGCStrong())
  14225. Record->setHasObjectMember(true);
  14226. }
  14227. }
  14228. if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
  14229. QualType FT = FD->getType();
  14230. if (FT.isNonTrivialToPrimitiveDefaultInitialize())
  14231. Record->setNonTrivialToPrimitiveDefaultInitialize(true);
  14232. QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
  14233. if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
  14234. Record->setNonTrivialToPrimitiveCopy(true);
  14235. if (FT.isDestructedType()) {
  14236. Record->setNonTrivialToPrimitiveDestroy(true);
  14237. Record->setParamDestroyedInCallee(true);
  14238. }
  14239. if (const auto *RT = FT->getAs<RecordType>()) {
  14240. if (RT->getDecl()->getArgPassingRestrictions() ==
  14241. RecordDecl::APK_CanNeverPassInRegs)
  14242. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14243. } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
  14244. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14245. }
  14246. if (Record && FD->getType().isVolatileQualified())
  14247. Record->setHasVolatileMember(true);
  14248. // Keep track of the number of named members.
  14249. if (FD->getIdentifier())
  14250. ++NumNamedMembers;
  14251. }
  14252. // Okay, we successfully defined 'Record'.
  14253. if (Record) {
  14254. bool Completed = false;
  14255. if (CXXRecord) {
  14256. if (!CXXRecord->isInvalidDecl()) {
  14257. // Set access bits correctly on the directly-declared conversions.
  14258. for (CXXRecordDecl::conversion_iterator
  14259. I = CXXRecord->conversion_begin(),
  14260. E = CXXRecord->conversion_end(); I != E; ++I)
  14261. I.setAccess((*I)->getAccess());
  14262. }
  14263. if (!CXXRecord->isDependentType()) {
  14264. // Add any implicitly-declared members to this class.
  14265. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  14266. if (!CXXRecord->isInvalidDecl()) {
  14267. // If we have virtual base classes, we may end up finding multiple
  14268. // final overriders for a given virtual function. Check for this
  14269. // problem now.
  14270. if (CXXRecord->getNumVBases()) {
  14271. CXXFinalOverriderMap FinalOverriders;
  14272. CXXRecord->getFinalOverriders(FinalOverriders);
  14273. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  14274. MEnd = FinalOverriders.end();
  14275. M != MEnd; ++M) {
  14276. for (OverridingMethods::iterator SO = M->second.begin(),
  14277. SOEnd = M->second.end();
  14278. SO != SOEnd; ++SO) {
  14279. assert(SO->second.size() > 0 &&
  14280. "Virtual function without overriding functions?");
  14281. if (SO->second.size() == 1)
  14282. continue;
  14283. // C++ [class.virtual]p2:
  14284. // In a derived class, if a virtual member function of a base
  14285. // class subobject has more than one final overrider the
  14286. // program is ill-formed.
  14287. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  14288. << (const NamedDecl *)M->first << Record;
  14289. Diag(M->first->getLocation(),
  14290. diag::note_overridden_virtual_function);
  14291. for (OverridingMethods::overriding_iterator
  14292. OM = SO->second.begin(),
  14293. OMEnd = SO->second.end();
  14294. OM != OMEnd; ++OM)
  14295. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  14296. << (const NamedDecl *)M->first << OM->Method->getParent();
  14297. Record->setInvalidDecl();
  14298. }
  14299. }
  14300. CXXRecord->completeDefinition(&FinalOverriders);
  14301. Completed = true;
  14302. }
  14303. }
  14304. }
  14305. }
  14306. if (!Completed)
  14307. Record->completeDefinition();
  14308. // Handle attributes before checking the layout.
  14309. ProcessDeclAttributeList(S, Record, Attrs);
  14310. // We may have deferred checking for a deleted destructor. Check now.
  14311. if (CXXRecord) {
  14312. auto *Dtor = CXXRecord->getDestructor();
  14313. if (Dtor && Dtor->isImplicit() &&
  14314. ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
  14315. CXXRecord->setImplicitDestructorIsDeleted();
  14316. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  14317. }
  14318. }
  14319. if (Record->hasAttrs()) {
  14320. CheckAlignasUnderalignment(Record);
  14321. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  14322. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  14323. IA->getRange(), IA->getBestCase(),
  14324. IA->getSemanticSpelling());
  14325. }
  14326. // Check if the structure/union declaration is a type that can have zero
  14327. // size in C. For C this is a language extension, for C++ it may cause
  14328. // compatibility problems.
  14329. bool CheckForZeroSize;
  14330. if (!getLangOpts().CPlusPlus) {
  14331. CheckForZeroSize = true;
  14332. } else {
  14333. // For C++ filter out types that cannot be referenced in C code.
  14334. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  14335. CheckForZeroSize =
  14336. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  14337. !CXXRecord->isDependentType() &&
  14338. CXXRecord->isCLike();
  14339. }
  14340. if (CheckForZeroSize) {
  14341. bool ZeroSize = true;
  14342. bool IsEmpty = true;
  14343. unsigned NonBitFields = 0;
  14344. for (RecordDecl::field_iterator I = Record->field_begin(),
  14345. E = Record->field_end();
  14346. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  14347. IsEmpty = false;
  14348. if (I->isUnnamedBitfield()) {
  14349. if (!I->isZeroLengthBitField(Context))
  14350. ZeroSize = false;
  14351. } else {
  14352. ++NonBitFields;
  14353. QualType FieldType = I->getType();
  14354. if (FieldType->isIncompleteType() ||
  14355. !Context.getTypeSizeInChars(FieldType).isZero())
  14356. ZeroSize = false;
  14357. }
  14358. }
  14359. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  14360. // allowed in C++, but warn if its declaration is inside
  14361. // extern "C" block.
  14362. if (ZeroSize) {
  14363. Diag(RecLoc, getLangOpts().CPlusPlus ?
  14364. diag::warn_zero_size_struct_union_in_extern_c :
  14365. diag::warn_zero_size_struct_union_compat)
  14366. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  14367. }
  14368. // Structs without named members are extension in C (C99 6.7.2.1p7),
  14369. // but are accepted by GCC.
  14370. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  14371. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  14372. diag::ext_no_named_members_in_struct_union)
  14373. << Record->isUnion();
  14374. }
  14375. }
  14376. } else {
  14377. ObjCIvarDecl **ClsFields =
  14378. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  14379. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  14380. ID->setEndOfDefinitionLoc(RBrac);
  14381. // Add ivar's to class's DeclContext.
  14382. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14383. ClsFields[i]->setLexicalDeclContext(ID);
  14384. ID->addDecl(ClsFields[i]);
  14385. }
  14386. // Must enforce the rule that ivars in the base classes may not be
  14387. // duplicates.
  14388. if (ID->getSuperClass())
  14389. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  14390. } else if (ObjCImplementationDecl *IMPDecl =
  14391. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  14392. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  14393. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  14394. // Ivar declared in @implementation never belongs to the implementation.
  14395. // Only it is in implementation's lexical context.
  14396. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  14397. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  14398. IMPDecl->setIvarLBraceLoc(LBrac);
  14399. IMPDecl->setIvarRBraceLoc(RBrac);
  14400. } else if (ObjCCategoryDecl *CDecl =
  14401. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  14402. // case of ivars in class extension; all other cases have been
  14403. // reported as errors elsewhere.
  14404. // FIXME. Class extension does not have a LocEnd field.
  14405. // CDecl->setLocEnd(RBrac);
  14406. // Add ivar's to class extension's DeclContext.
  14407. // Diagnose redeclaration of private ivars.
  14408. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  14409. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14410. if (IDecl) {
  14411. if (const ObjCIvarDecl *ClsIvar =
  14412. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14413. Diag(ClsFields[i]->getLocation(),
  14414. diag::err_duplicate_ivar_declaration);
  14415. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  14416. continue;
  14417. }
  14418. for (const auto *Ext : IDecl->known_extensions()) {
  14419. if (const ObjCIvarDecl *ClsExtIvar
  14420. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14421. Diag(ClsFields[i]->getLocation(),
  14422. diag::err_duplicate_ivar_declaration);
  14423. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  14424. continue;
  14425. }
  14426. }
  14427. }
  14428. ClsFields[i]->setLexicalDeclContext(CDecl);
  14429. CDecl->addDecl(ClsFields[i]);
  14430. }
  14431. CDecl->setIvarLBraceLoc(LBrac);
  14432. CDecl->setIvarRBraceLoc(RBrac);
  14433. }
  14434. }
  14435. }
  14436. /// Determine whether the given integral value is representable within
  14437. /// the given type T.
  14438. static bool isRepresentableIntegerValue(ASTContext &Context,
  14439. llvm::APSInt &Value,
  14440. QualType T) {
  14441. assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
  14442. "Integral type required!");
  14443. unsigned BitWidth = Context.getIntWidth(T);
  14444. if (Value.isUnsigned() || Value.isNonNegative()) {
  14445. if (T->isSignedIntegerOrEnumerationType())
  14446. --BitWidth;
  14447. return Value.getActiveBits() <= BitWidth;
  14448. }
  14449. return Value.getMinSignedBits() <= BitWidth;
  14450. }
  14451. // Given an integral type, return the next larger integral type
  14452. // (or a NULL type of no such type exists).
  14453. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  14454. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  14455. // enum checking below.
  14456. assert((T->isIntegralType(Context) ||
  14457. T->isEnumeralType()) && "Integral type required!");
  14458. const unsigned NumTypes = 4;
  14459. QualType SignedIntegralTypes[NumTypes] = {
  14460. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  14461. };
  14462. QualType UnsignedIntegralTypes[NumTypes] = {
  14463. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  14464. Context.UnsignedLongLongTy
  14465. };
  14466. unsigned BitWidth = Context.getTypeSize(T);
  14467. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  14468. : UnsignedIntegralTypes;
  14469. for (unsigned I = 0; I != NumTypes; ++I)
  14470. if (Context.getTypeSize(Types[I]) > BitWidth)
  14471. return Types[I];
  14472. return QualType();
  14473. }
  14474. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  14475. EnumConstantDecl *LastEnumConst,
  14476. SourceLocation IdLoc,
  14477. IdentifierInfo *Id,
  14478. Expr *Val) {
  14479. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  14480. llvm::APSInt EnumVal(IntWidth);
  14481. QualType EltTy;
  14482. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  14483. Val = nullptr;
  14484. if (Val)
  14485. Val = DefaultLvalueConversion(Val).get();
  14486. if (Val) {
  14487. if (Enum->isDependentType() || Val->isTypeDependent())
  14488. EltTy = Context.DependentTy;
  14489. else {
  14490. if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
  14491. !getLangOpts().MSVCCompat) {
  14492. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  14493. // constant-expression in the enumerator-definition shall be a converted
  14494. // constant expression of the underlying type.
  14495. EltTy = Enum->getIntegerType();
  14496. ExprResult Converted =
  14497. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  14498. CCEK_Enumerator);
  14499. if (Converted.isInvalid())
  14500. Val = nullptr;
  14501. else
  14502. Val = Converted.get();
  14503. } else if (!Val->isValueDependent() &&
  14504. !(Val = VerifyIntegerConstantExpression(Val,
  14505. &EnumVal).get())) {
  14506. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  14507. } else {
  14508. if (Enum->isComplete()) {
  14509. EltTy = Enum->getIntegerType();
  14510. // In Obj-C and Microsoft mode, require the enumeration value to be
  14511. // representable in the underlying type of the enumeration. In C++11,
  14512. // we perform a non-narrowing conversion as part of converted constant
  14513. // expression checking.
  14514. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14515. if (getLangOpts().MSVCCompat) {
  14516. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  14517. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  14518. } else
  14519. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  14520. } else
  14521. Val = ImpCastExprToType(Val, EltTy,
  14522. EltTy->isBooleanType() ?
  14523. CK_IntegralToBoolean : CK_IntegralCast)
  14524. .get();
  14525. } else if (getLangOpts().CPlusPlus) {
  14526. // C++11 [dcl.enum]p5:
  14527. // If the underlying type is not fixed, the type of each enumerator
  14528. // is the type of its initializing value:
  14529. // - If an initializer is specified for an enumerator, the
  14530. // initializing value has the same type as the expression.
  14531. EltTy = Val->getType();
  14532. } else {
  14533. // C99 6.7.2.2p2:
  14534. // The expression that defines the value of an enumeration constant
  14535. // shall be an integer constant expression that has a value
  14536. // representable as an int.
  14537. // Complain if the value is not representable in an int.
  14538. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  14539. Diag(IdLoc, diag::ext_enum_value_not_int)
  14540. << EnumVal.toString(10) << Val->getSourceRange()
  14541. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  14542. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  14543. // Force the type of the expression to 'int'.
  14544. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  14545. }
  14546. EltTy = Val->getType();
  14547. }
  14548. }
  14549. }
  14550. }
  14551. if (!Val) {
  14552. if (Enum->isDependentType())
  14553. EltTy = Context.DependentTy;
  14554. else if (!LastEnumConst) {
  14555. // C++0x [dcl.enum]p5:
  14556. // If the underlying type is not fixed, the type of each enumerator
  14557. // is the type of its initializing value:
  14558. // - If no initializer is specified for the first enumerator, the
  14559. // initializing value has an unspecified integral type.
  14560. //
  14561. // GCC uses 'int' for its unspecified integral type, as does
  14562. // C99 6.7.2.2p3.
  14563. if (Enum->isFixed()) {
  14564. EltTy = Enum->getIntegerType();
  14565. }
  14566. else {
  14567. EltTy = Context.IntTy;
  14568. }
  14569. } else {
  14570. // Assign the last value + 1.
  14571. EnumVal = LastEnumConst->getInitVal();
  14572. ++EnumVal;
  14573. EltTy = LastEnumConst->getType();
  14574. // Check for overflow on increment.
  14575. if (EnumVal < LastEnumConst->getInitVal()) {
  14576. // C++0x [dcl.enum]p5:
  14577. // If the underlying type is not fixed, the type of each enumerator
  14578. // is the type of its initializing value:
  14579. //
  14580. // - Otherwise the type of the initializing value is the same as
  14581. // the type of the initializing value of the preceding enumerator
  14582. // unless the incremented value is not representable in that type,
  14583. // in which case the type is an unspecified integral type
  14584. // sufficient to contain the incremented value. If no such type
  14585. // exists, the program is ill-formed.
  14586. QualType T = getNextLargerIntegralType(Context, EltTy);
  14587. if (T.isNull() || Enum->isFixed()) {
  14588. // There is no integral type larger enough to represent this
  14589. // value. Complain, then allow the value to wrap around.
  14590. EnumVal = LastEnumConst->getInitVal();
  14591. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  14592. ++EnumVal;
  14593. if (Enum->isFixed())
  14594. // When the underlying type is fixed, this is ill-formed.
  14595. Diag(IdLoc, diag::err_enumerator_wrapped)
  14596. << EnumVal.toString(10)
  14597. << EltTy;
  14598. else
  14599. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  14600. << EnumVal.toString(10);
  14601. } else {
  14602. EltTy = T;
  14603. }
  14604. // Retrieve the last enumerator's value, extent that type to the
  14605. // type that is supposed to be large enough to represent the incremented
  14606. // value, then increment.
  14607. EnumVal = LastEnumConst->getInitVal();
  14608. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  14609. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  14610. ++EnumVal;
  14611. // If we're not in C++, diagnose the overflow of enumerator values,
  14612. // which in C99 means that the enumerator value is not representable in
  14613. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  14614. // permits enumerator values that are representable in some larger
  14615. // integral type.
  14616. if (!getLangOpts().CPlusPlus && !T.isNull())
  14617. Diag(IdLoc, diag::warn_enum_value_overflow);
  14618. } else if (!getLangOpts().CPlusPlus &&
  14619. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14620. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  14621. Diag(IdLoc, diag::ext_enum_value_not_int)
  14622. << EnumVal.toString(10) << 1;
  14623. }
  14624. }
  14625. }
  14626. if (!EltTy->isDependentType()) {
  14627. // Make the enumerator value match the signedness and size of the
  14628. // enumerator's type.
  14629. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  14630. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  14631. }
  14632. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  14633. Val, EnumVal);
  14634. }
  14635. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  14636. SourceLocation IILoc) {
  14637. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  14638. !getLangOpts().CPlusPlus)
  14639. return SkipBodyInfo();
  14640. // We have an anonymous enum definition. Look up the first enumerator to
  14641. // determine if we should merge the definition with an existing one and
  14642. // skip the body.
  14643. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  14644. forRedeclarationInCurContext());
  14645. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  14646. if (!PrevECD)
  14647. return SkipBodyInfo();
  14648. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  14649. NamedDecl *Hidden;
  14650. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  14651. SkipBodyInfo Skip;
  14652. Skip.Previous = Hidden;
  14653. return Skip;
  14654. }
  14655. return SkipBodyInfo();
  14656. }
  14657. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  14658. SourceLocation IdLoc, IdentifierInfo *Id,
  14659. const ParsedAttributesView &Attrs,
  14660. SourceLocation EqualLoc, Expr *Val) {
  14661. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  14662. EnumConstantDecl *LastEnumConst =
  14663. cast_or_null<EnumConstantDecl>(lastEnumConst);
  14664. // The scope passed in may not be a decl scope. Zip up the scope tree until
  14665. // we find one that is.
  14666. S = getNonFieldDeclScope(S);
  14667. // Verify that there isn't already something declared with this name in this
  14668. // scope.
  14669. LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
  14670. LookupName(R, S);
  14671. NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
  14672. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  14673. // Maybe we will complain about the shadowed template parameter.
  14674. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  14675. // Just pretend that we didn't see the previous declaration.
  14676. PrevDecl = nullptr;
  14677. }
  14678. // C++ [class.mem]p15:
  14679. // If T is the name of a class, then each of the following shall have a name
  14680. // different from T:
  14681. // - every enumerator of every member of class T that is an unscoped
  14682. // enumerated type
  14683. if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
  14684. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  14685. DeclarationNameInfo(Id, IdLoc));
  14686. EnumConstantDecl *New =
  14687. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  14688. if (!New)
  14689. return nullptr;
  14690. if (PrevDecl) {
  14691. if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
  14692. // Check for other kinds of shadowing not already handled.
  14693. CheckShadow(New, PrevDecl, R);
  14694. }
  14695. // When in C++, we may get a TagDecl with the same name; in this case the
  14696. // enum constant will 'hide' the tag.
  14697. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  14698. "Received TagDecl when not in C++!");
  14699. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  14700. if (isa<EnumConstantDecl>(PrevDecl))
  14701. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  14702. else
  14703. Diag(IdLoc, diag::err_redefinition) << Id;
  14704. notePreviousDefinition(PrevDecl, IdLoc);
  14705. return nullptr;
  14706. }
  14707. }
  14708. // Process attributes.
  14709. ProcessDeclAttributeList(S, New, Attrs);
  14710. AddPragmaAttributes(S, New);
  14711. // Register this decl in the current scope stack.
  14712. New->setAccess(TheEnumDecl->getAccess());
  14713. PushOnScopeChains(New, S);
  14714. ActOnDocumentableDecl(New);
  14715. return New;
  14716. }
  14717. // Returns true when the enum initial expression does not trigger the
  14718. // duplicate enum warning. A few common cases are exempted as follows:
  14719. // Element2 = Element1
  14720. // Element2 = Element1 + 1
  14721. // Element2 = Element1 - 1
  14722. // Where Element2 and Element1 are from the same enum.
  14723. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  14724. Expr *InitExpr = ECD->getInitExpr();
  14725. if (!InitExpr)
  14726. return true;
  14727. InitExpr = InitExpr->IgnoreImpCasts();
  14728. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  14729. if (!BO->isAdditiveOp())
  14730. return true;
  14731. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  14732. if (!IL)
  14733. return true;
  14734. if (IL->getValue() != 1)
  14735. return true;
  14736. InitExpr = BO->getLHS();
  14737. }
  14738. // This checks if the elements are from the same enum.
  14739. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  14740. if (!DRE)
  14741. return true;
  14742. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  14743. if (!EnumConstant)
  14744. return true;
  14745. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  14746. Enum)
  14747. return true;
  14748. return false;
  14749. }
  14750. // Emits a warning when an element is implicitly set a value that
  14751. // a previous element has already been set to.
  14752. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  14753. EnumDecl *Enum, QualType EnumType) {
  14754. // Avoid anonymous enums
  14755. if (!Enum->getIdentifier())
  14756. return;
  14757. // Only check for small enums.
  14758. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  14759. return;
  14760. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  14761. return;
  14762. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  14763. typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
  14764. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  14765. typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
  14766. // Use int64_t as a key to avoid needing special handling for DenseMap keys.
  14767. auto EnumConstantToKey = [](const EnumConstantDecl *D) {
  14768. llvm::APSInt Val = D->getInitVal();
  14769. return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
  14770. };
  14771. DuplicatesVector DupVector;
  14772. ValueToVectorMap EnumMap;
  14773. // Populate the EnumMap with all values represented by enum constants without
  14774. // an initializer.
  14775. for (auto *Element : Elements) {
  14776. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
  14777. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  14778. // this constant. Skip this enum since it may be ill-formed.
  14779. if (!ECD) {
  14780. return;
  14781. }
  14782. // Constants with initalizers are handled in the next loop.
  14783. if (ECD->getInitExpr())
  14784. continue;
  14785. // Duplicate values are handled in the next loop.
  14786. EnumMap.insert({EnumConstantToKey(ECD), ECD});
  14787. }
  14788. if (EnumMap.size() == 0)
  14789. return;
  14790. // Create vectors for any values that has duplicates.
  14791. for (auto *Element : Elements) {
  14792. // The last loop returned if any constant was null.
  14793. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
  14794. if (!ValidDuplicateEnum(ECD, Enum))
  14795. continue;
  14796. auto Iter = EnumMap.find(EnumConstantToKey(ECD));
  14797. if (Iter == EnumMap.end())
  14798. continue;
  14799. DeclOrVector& Entry = Iter->second;
  14800. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  14801. // Ensure constants are different.
  14802. if (D == ECD)
  14803. continue;
  14804. // Create new vector and push values onto it.
  14805. auto Vec = llvm::make_unique<ECDVector>();
  14806. Vec->push_back(D);
  14807. Vec->push_back(ECD);
  14808. // Update entry to point to the duplicates vector.
  14809. Entry = Vec.get();
  14810. // Store the vector somewhere we can consult later for quick emission of
  14811. // diagnostics.
  14812. DupVector.emplace_back(std::move(Vec));
  14813. continue;
  14814. }
  14815. ECDVector *Vec = Entry.get<ECDVector*>();
  14816. // Make sure constants are not added more than once.
  14817. if (*Vec->begin() == ECD)
  14818. continue;
  14819. Vec->push_back(ECD);
  14820. }
  14821. // Emit diagnostics.
  14822. for (const auto &Vec : DupVector) {
  14823. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  14824. // Emit warning for one enum constant.
  14825. auto *FirstECD = Vec->front();
  14826. S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
  14827. << FirstECD << FirstECD->getInitVal().toString(10)
  14828. << FirstECD->getSourceRange();
  14829. // Emit one note for each of the remaining enum constants with
  14830. // the same value.
  14831. for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
  14832. S.Diag(ECD->getLocation(), diag::note_duplicate_element)
  14833. << ECD << ECD->getInitVal().toString(10)
  14834. << ECD->getSourceRange();
  14835. }
  14836. }
  14837. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  14838. bool AllowMask) const {
  14839. assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
  14840. assert(ED->isCompleteDefinition() && "expected enum definition");
  14841. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  14842. llvm::APInt &FlagBits = R.first->second;
  14843. if (R.second) {
  14844. for (auto *E : ED->enumerators()) {
  14845. const auto &EVal = E->getInitVal();
  14846. // Only single-bit enumerators introduce new flag values.
  14847. if (EVal.isPowerOf2())
  14848. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  14849. }
  14850. }
  14851. // A value is in a flag enum if either its bits are a subset of the enum's
  14852. // flag bits (the first condition) or we are allowing masks and the same is
  14853. // true of its complement (the second condition). When masks are allowed, we
  14854. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  14855. //
  14856. // While it's true that any value could be used as a mask, the assumption is
  14857. // that a mask will have all of the insignificant bits set. Anything else is
  14858. // likely a logic error.
  14859. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  14860. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  14861. }
  14862. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  14863. Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
  14864. const ParsedAttributesView &Attrs) {
  14865. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  14866. QualType EnumType = Context.getTypeDeclType(Enum);
  14867. ProcessDeclAttributeList(S, Enum, Attrs);
  14868. if (Enum->isDependentType()) {
  14869. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  14870. EnumConstantDecl *ECD =
  14871. cast_or_null<EnumConstantDecl>(Elements[i]);
  14872. if (!ECD) continue;
  14873. ECD->setType(EnumType);
  14874. }
  14875. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  14876. return;
  14877. }
  14878. // TODO: If the result value doesn't fit in an int, it must be a long or long
  14879. // long value. ISO C does not support this, but GCC does as an extension,
  14880. // emit a warning.
  14881. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  14882. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  14883. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  14884. // Verify that all the values are okay, compute the size of the values, and
  14885. // reverse the list.
  14886. unsigned NumNegativeBits = 0;
  14887. unsigned NumPositiveBits = 0;
  14888. // Keep track of whether all elements have type int.
  14889. bool AllElementsInt = true;
  14890. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  14891. EnumConstantDecl *ECD =
  14892. cast_or_null<EnumConstantDecl>(Elements[i]);
  14893. if (!ECD) continue; // Already issued a diagnostic.
  14894. const llvm::APSInt &InitVal = ECD->getInitVal();
  14895. // Keep track of the size of positive and negative values.
  14896. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  14897. NumPositiveBits = std::max(NumPositiveBits,
  14898. (unsigned)InitVal.getActiveBits());
  14899. else
  14900. NumNegativeBits = std::max(NumNegativeBits,
  14901. (unsigned)InitVal.getMinSignedBits());
  14902. // Keep track of whether every enum element has type int (very common).
  14903. if (AllElementsInt)
  14904. AllElementsInt = ECD->getType() == Context.IntTy;
  14905. }
  14906. // Figure out the type that should be used for this enum.
  14907. QualType BestType;
  14908. unsigned BestWidth;
  14909. // C++0x N3000 [conv.prom]p3:
  14910. // An rvalue of an unscoped enumeration type whose underlying
  14911. // type is not fixed can be converted to an rvalue of the first
  14912. // of the following types that can represent all the values of
  14913. // the enumeration: int, unsigned int, long int, unsigned long
  14914. // int, long long int, or unsigned long long int.
  14915. // C99 6.4.4.3p2:
  14916. // An identifier declared as an enumeration constant has type int.
  14917. // The C99 rule is modified by a gcc extension
  14918. QualType BestPromotionType;
  14919. bool Packed = Enum->hasAttr<PackedAttr>();
  14920. // -fshort-enums is the equivalent to specifying the packed attribute on all
  14921. // enum definitions.
  14922. if (LangOpts.ShortEnums)
  14923. Packed = true;
  14924. // If the enum already has a type because it is fixed or dictated by the
  14925. // target, promote that type instead of analyzing the enumerators.
  14926. if (Enum->isComplete()) {
  14927. BestType = Enum->getIntegerType();
  14928. if (BestType->isPromotableIntegerType())
  14929. BestPromotionType = Context.getPromotedIntegerType(BestType);
  14930. else
  14931. BestPromotionType = BestType;
  14932. BestWidth = Context.getIntWidth(BestType);
  14933. }
  14934. else if (NumNegativeBits) {
  14935. // If there is a negative value, figure out the smallest integer type (of
  14936. // int/long/longlong) that fits.
  14937. // If it's packed, check also if it fits a char or a short.
  14938. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  14939. BestType = Context.SignedCharTy;
  14940. BestWidth = CharWidth;
  14941. } else if (Packed && NumNegativeBits <= ShortWidth &&
  14942. NumPositiveBits < ShortWidth) {
  14943. BestType = Context.ShortTy;
  14944. BestWidth = ShortWidth;
  14945. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  14946. BestType = Context.IntTy;
  14947. BestWidth = IntWidth;
  14948. } else {
  14949. BestWidth = Context.getTargetInfo().getLongWidth();
  14950. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  14951. BestType = Context.LongTy;
  14952. } else {
  14953. BestWidth = Context.getTargetInfo().getLongLongWidth();
  14954. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  14955. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  14956. BestType = Context.LongLongTy;
  14957. }
  14958. }
  14959. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  14960. } else {
  14961. // If there is no negative value, figure out the smallest type that fits
  14962. // all of the enumerator values.
  14963. // If it's packed, check also if it fits a char or a short.
  14964. if (Packed && NumPositiveBits <= CharWidth) {
  14965. BestType = Context.UnsignedCharTy;
  14966. BestPromotionType = Context.IntTy;
  14967. BestWidth = CharWidth;
  14968. } else if (Packed && NumPositiveBits <= ShortWidth) {
  14969. BestType = Context.UnsignedShortTy;
  14970. BestPromotionType = Context.IntTy;
  14971. BestWidth = ShortWidth;
  14972. } else if (NumPositiveBits <= IntWidth) {
  14973. BestType = Context.UnsignedIntTy;
  14974. BestWidth = IntWidth;
  14975. BestPromotionType
  14976. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14977. ? Context.UnsignedIntTy : Context.IntTy;
  14978. } else if (NumPositiveBits <=
  14979. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  14980. BestType = Context.UnsignedLongTy;
  14981. BestPromotionType
  14982. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14983. ? Context.UnsignedLongTy : Context.LongTy;
  14984. } else {
  14985. BestWidth = Context.getTargetInfo().getLongLongWidth();
  14986. assert(NumPositiveBits <= BestWidth &&
  14987. "How could an initializer get larger than ULL?");
  14988. BestType = Context.UnsignedLongLongTy;
  14989. BestPromotionType
  14990. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14991. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  14992. }
  14993. }
  14994. // Loop over all of the enumerator constants, changing their types to match
  14995. // the type of the enum if needed.
  14996. for (auto *D : Elements) {
  14997. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  14998. if (!ECD) continue; // Already issued a diagnostic.
  14999. // Standard C says the enumerators have int type, but we allow, as an
  15000. // extension, the enumerators to be larger than int size. If each
  15001. // enumerator value fits in an int, type it as an int, otherwise type it the
  15002. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  15003. // that X has type 'int', not 'unsigned'.
  15004. // Determine whether the value fits into an int.
  15005. llvm::APSInt InitVal = ECD->getInitVal();
  15006. // If it fits into an integer type, force it. Otherwise force it to match
  15007. // the enum decl type.
  15008. QualType NewTy;
  15009. unsigned NewWidth;
  15010. bool NewSign;
  15011. if (!getLangOpts().CPlusPlus &&
  15012. !Enum->isFixed() &&
  15013. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  15014. NewTy = Context.IntTy;
  15015. NewWidth = IntWidth;
  15016. NewSign = true;
  15017. } else if (ECD->getType() == BestType) {
  15018. // Already the right type!
  15019. if (getLangOpts().CPlusPlus)
  15020. // C++ [dcl.enum]p4: Following the closing brace of an
  15021. // enum-specifier, each enumerator has the type of its
  15022. // enumeration.
  15023. ECD->setType(EnumType);
  15024. continue;
  15025. } else {
  15026. NewTy = BestType;
  15027. NewWidth = BestWidth;
  15028. NewSign = BestType->isSignedIntegerOrEnumerationType();
  15029. }
  15030. // Adjust the APSInt value.
  15031. InitVal = InitVal.extOrTrunc(NewWidth);
  15032. InitVal.setIsSigned(NewSign);
  15033. ECD->setInitVal(InitVal);
  15034. // Adjust the Expr initializer and type.
  15035. if (ECD->getInitExpr() &&
  15036. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  15037. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  15038. CK_IntegralCast,
  15039. ECD->getInitExpr(),
  15040. /*base paths*/ nullptr,
  15041. VK_RValue));
  15042. if (getLangOpts().CPlusPlus)
  15043. // C++ [dcl.enum]p4: Following the closing brace of an
  15044. // enum-specifier, each enumerator has the type of its
  15045. // enumeration.
  15046. ECD->setType(EnumType);
  15047. else
  15048. ECD->setType(NewTy);
  15049. }
  15050. Enum->completeDefinition(BestType, BestPromotionType,
  15051. NumPositiveBits, NumNegativeBits);
  15052. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  15053. if (Enum->isClosedFlag()) {
  15054. for (Decl *D : Elements) {
  15055. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  15056. if (!ECD) continue; // Already issued a diagnostic.
  15057. llvm::APSInt InitVal = ECD->getInitVal();
  15058. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  15059. !IsValueInFlagEnum(Enum, InitVal, true))
  15060. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  15061. << ECD << Enum;
  15062. }
  15063. }
  15064. // Now that the enum type is defined, ensure it's not been underaligned.
  15065. if (Enum->hasAttrs())
  15066. CheckAlignasUnderalignment(Enum);
  15067. }
  15068. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  15069. SourceLocation StartLoc,
  15070. SourceLocation EndLoc) {
  15071. StringLiteral *AsmString = cast<StringLiteral>(expr);
  15072. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  15073. AsmString, StartLoc,
  15074. EndLoc);
  15075. CurContext->addDecl(New);
  15076. return New;
  15077. }
  15078. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  15079. IdentifierInfo* AliasName,
  15080. SourceLocation PragmaLoc,
  15081. SourceLocation NameLoc,
  15082. SourceLocation AliasNameLoc) {
  15083. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  15084. LookupOrdinaryName);
  15085. AsmLabelAttr *Attr =
  15086. AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
  15087. // If a declaration that:
  15088. // 1) declares a function or a variable
  15089. // 2) has external linkage
  15090. // already exists, add a label attribute to it.
  15091. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15092. if (isDeclExternC(PrevDecl))
  15093. PrevDecl->addAttr(Attr);
  15094. else
  15095. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  15096. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  15097. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  15098. } else
  15099. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  15100. }
  15101. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  15102. SourceLocation PragmaLoc,
  15103. SourceLocation NameLoc) {
  15104. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  15105. if (PrevDecl) {
  15106. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  15107. } else {
  15108. (void)WeakUndeclaredIdentifiers.insert(
  15109. std::pair<IdentifierInfo*,WeakInfo>
  15110. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  15111. }
  15112. }
  15113. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  15114. IdentifierInfo* AliasName,
  15115. SourceLocation PragmaLoc,
  15116. SourceLocation NameLoc,
  15117. SourceLocation AliasNameLoc) {
  15118. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  15119. LookupOrdinaryName);
  15120. WeakInfo W = WeakInfo(Name, NameLoc);
  15121. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15122. if (!PrevDecl->hasAttr<AliasAttr>())
  15123. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  15124. DeclApplyPragmaWeak(TUScope, ND, W);
  15125. } else {
  15126. (void)WeakUndeclaredIdentifiers.insert(
  15127. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  15128. }
  15129. }
  15130. Decl *Sema::getObjCDeclContext() const {
  15131. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  15132. }