SemaDecl.cpp 611 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769
  1. //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for declarations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "TypeLocBuilder.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTLambda.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/CommentDiagnostic.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclTemplate.h"
  23. #include "clang/AST/EvaluatedExprVisitor.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/StmtCXX.h"
  26. #include "clang/Basic/Builtins.h"
  27. #include "clang/Basic/PartialDiagnostic.h"
  28. #include "clang/Basic/SourceManager.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  31. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  32. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  33. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  34. #include "clang/Sema/CXXFieldCollector.h"
  35. #include "clang/Sema/DeclSpec.h"
  36. #include "clang/Sema/DelayedDiagnostic.h"
  37. #include "clang/Sema/Initialization.h"
  38. #include "clang/Sema/Lookup.h"
  39. #include "clang/Sema/ParsedTemplate.h"
  40. #include "clang/Sema/Scope.h"
  41. #include "clang/Sema/ScopeInfo.h"
  42. #include "clang/Sema/SemaInternal.h"
  43. #include "clang/Sema/Template.h"
  44. #include "llvm/ADT/SmallString.h"
  45. #include "llvm/ADT/Triple.h"
  46. #include <algorithm>
  47. #include <cstring>
  48. #include <functional>
  49. using namespace clang;
  50. using namespace sema;
  51. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  52. if (OwnedType) {
  53. Decl *Group[2] = { OwnedType, Ptr };
  54. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  55. }
  56. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  57. }
  58. namespace {
  59. class TypeNameValidatorCCC : public CorrectionCandidateCallback {
  60. public:
  61. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
  62. bool AllowTemplates=false)
  63. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  64. AllowClassTemplates(AllowTemplates) {
  65. WantExpressionKeywords = false;
  66. WantCXXNamedCasts = false;
  67. WantRemainingKeywords = false;
  68. }
  69. bool ValidateCandidate(const TypoCorrection &candidate) override {
  70. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  71. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  72. bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
  73. return (IsType || AllowedTemplate) &&
  74. (AllowInvalidDecl || !ND->isInvalidDecl());
  75. }
  76. return !WantClassName && candidate.isKeyword();
  77. }
  78. private:
  79. bool AllowInvalidDecl;
  80. bool WantClassName;
  81. bool AllowClassTemplates;
  82. };
  83. } // end anonymous namespace
  84. /// \brief Determine whether the token kind starts a simple-type-specifier.
  85. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  86. switch (Kind) {
  87. // FIXME: Take into account the current language when deciding whether a
  88. // token kind is a valid type specifier
  89. case tok::kw_short:
  90. case tok::kw_long:
  91. case tok::kw___int64:
  92. case tok::kw___int128:
  93. case tok::kw_signed:
  94. case tok::kw_unsigned:
  95. case tok::kw_void:
  96. case tok::kw_char:
  97. case tok::kw_int:
  98. case tok::kw_half:
  99. case tok::kw_float:
  100. case tok::kw_double:
  101. case tok::kw___float128:
  102. case tok::kw_wchar_t:
  103. case tok::kw_bool:
  104. case tok::kw___underlying_type:
  105. case tok::kw___auto_type:
  106. return true;
  107. case tok::annot_typename:
  108. case tok::kw_char16_t:
  109. case tok::kw_char32_t:
  110. case tok::kw_typeof:
  111. case tok::annot_decltype:
  112. case tok::kw_decltype:
  113. return getLangOpts().CPlusPlus;
  114. default:
  115. break;
  116. }
  117. return false;
  118. }
  119. namespace {
  120. enum class UnqualifiedTypeNameLookupResult {
  121. NotFound,
  122. FoundNonType,
  123. FoundType
  124. };
  125. } // end anonymous namespace
  126. /// \brief Tries to perform unqualified lookup of the type decls in bases for
  127. /// dependent class.
  128. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  129. /// type decl, \a FoundType if only type decls are found.
  130. static UnqualifiedTypeNameLookupResult
  131. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  132. SourceLocation NameLoc,
  133. const CXXRecordDecl *RD) {
  134. if (!RD->hasDefinition())
  135. return UnqualifiedTypeNameLookupResult::NotFound;
  136. // Look for type decls in base classes.
  137. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  138. UnqualifiedTypeNameLookupResult::NotFound;
  139. for (const auto &Base : RD->bases()) {
  140. const CXXRecordDecl *BaseRD = nullptr;
  141. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  142. BaseRD = BaseTT->getAsCXXRecordDecl();
  143. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  144. // Look for type decls in dependent base classes that have known primary
  145. // templates.
  146. if (!TST || !TST->isDependentType())
  147. continue;
  148. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  149. if (!TD)
  150. continue;
  151. if (auto *BasePrimaryTemplate =
  152. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
  153. if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
  154. BaseRD = BasePrimaryTemplate;
  155. else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
  156. if (const ClassTemplatePartialSpecializationDecl *PS =
  157. CTD->findPartialSpecialization(Base.getType()))
  158. if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
  159. BaseRD = PS;
  160. }
  161. }
  162. }
  163. if (BaseRD) {
  164. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  165. if (!isa<TypeDecl>(ND))
  166. return UnqualifiedTypeNameLookupResult::FoundNonType;
  167. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  168. }
  169. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  170. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  171. case UnqualifiedTypeNameLookupResult::FoundNonType:
  172. return UnqualifiedTypeNameLookupResult::FoundNonType;
  173. case UnqualifiedTypeNameLookupResult::FoundType:
  174. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  175. break;
  176. case UnqualifiedTypeNameLookupResult::NotFound:
  177. break;
  178. }
  179. }
  180. }
  181. }
  182. return FoundTypeDecl;
  183. }
  184. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  185. const IdentifierInfo &II,
  186. SourceLocation NameLoc) {
  187. // Lookup in the parent class template context, if any.
  188. const CXXRecordDecl *RD = nullptr;
  189. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  190. UnqualifiedTypeNameLookupResult::NotFound;
  191. for (DeclContext *DC = S.CurContext;
  192. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  193. DC = DC->getParent()) {
  194. // Look for type decls in dependent base classes that have known primary
  195. // templates.
  196. RD = dyn_cast<CXXRecordDecl>(DC);
  197. if (RD && RD->getDescribedClassTemplate())
  198. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  199. }
  200. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  201. return nullptr;
  202. // We found some types in dependent base classes. Recover as if the user
  203. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  204. // lookup during template instantiation.
  205. S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
  206. ASTContext &Context = S.Context;
  207. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  208. cast<Type>(Context.getRecordType(RD)));
  209. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  210. CXXScopeSpec SS;
  211. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  212. TypeLocBuilder Builder;
  213. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  214. DepTL.setNameLoc(NameLoc);
  215. DepTL.setElaboratedKeywordLoc(SourceLocation());
  216. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  217. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  218. }
  219. /// \brief If the identifier refers to a type name within this scope,
  220. /// return the declaration of that type.
  221. ///
  222. /// This routine performs ordinary name lookup of the identifier II
  223. /// within the given scope, with optional C++ scope specifier SS, to
  224. /// determine whether the name refers to a type. If so, returns an
  225. /// opaque pointer (actually a QualType) corresponding to that
  226. /// type. Otherwise, returns NULL.
  227. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  228. Scope *S, CXXScopeSpec *SS,
  229. bool isClassName, bool HasTrailingDot,
  230. ParsedType ObjectTypePtr,
  231. bool IsCtorOrDtorName,
  232. bool WantNontrivialTypeSourceInfo,
  233. IdentifierInfo **CorrectedII) {
  234. // Determine where we will perform name lookup.
  235. DeclContext *LookupCtx = nullptr;
  236. if (ObjectTypePtr) {
  237. QualType ObjectType = ObjectTypePtr.get();
  238. if (ObjectType->isRecordType())
  239. LookupCtx = computeDeclContext(ObjectType);
  240. } else if (SS && SS->isNotEmpty()) {
  241. LookupCtx = computeDeclContext(*SS, false);
  242. if (!LookupCtx) {
  243. if (isDependentScopeSpecifier(*SS)) {
  244. // C++ [temp.res]p3:
  245. // A qualified-id that refers to a type and in which the
  246. // nested-name-specifier depends on a template-parameter (14.6.2)
  247. // shall be prefixed by the keyword typename to indicate that the
  248. // qualified-id denotes a type, forming an
  249. // elaborated-type-specifier (7.1.5.3).
  250. //
  251. // We therefore do not perform any name lookup if the result would
  252. // refer to a member of an unknown specialization.
  253. if (!isClassName && !IsCtorOrDtorName)
  254. return nullptr;
  255. // We know from the grammar that this name refers to a type,
  256. // so build a dependent node to describe the type.
  257. if (WantNontrivialTypeSourceInfo)
  258. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  259. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  260. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  261. II, NameLoc);
  262. return ParsedType::make(T);
  263. }
  264. return nullptr;
  265. }
  266. if (!LookupCtx->isDependentContext() &&
  267. RequireCompleteDeclContext(*SS, LookupCtx))
  268. return nullptr;
  269. }
  270. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  271. // lookup for class-names.
  272. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  273. LookupOrdinaryName;
  274. LookupResult Result(*this, &II, NameLoc, Kind);
  275. if (LookupCtx) {
  276. // Perform "qualified" name lookup into the declaration context we
  277. // computed, which is either the type of the base of a member access
  278. // expression or the declaration context associated with a prior
  279. // nested-name-specifier.
  280. LookupQualifiedName(Result, LookupCtx);
  281. if (ObjectTypePtr && Result.empty()) {
  282. // C++ [basic.lookup.classref]p3:
  283. // If the unqualified-id is ~type-name, the type-name is looked up
  284. // in the context of the entire postfix-expression. If the type T of
  285. // the object expression is of a class type C, the type-name is also
  286. // looked up in the scope of class C. At least one of the lookups shall
  287. // find a name that refers to (possibly cv-qualified) T.
  288. LookupName(Result, S);
  289. }
  290. } else {
  291. // Perform unqualified name lookup.
  292. LookupName(Result, S);
  293. // For unqualified lookup in a class template in MSVC mode, look into
  294. // dependent base classes where the primary class template is known.
  295. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  296. if (ParsedType TypeInBase =
  297. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  298. return TypeInBase;
  299. }
  300. }
  301. NamedDecl *IIDecl = nullptr;
  302. switch (Result.getResultKind()) {
  303. case LookupResult::NotFound:
  304. case LookupResult::NotFoundInCurrentInstantiation:
  305. if (CorrectedII) {
  306. TypoCorrection Correction = CorrectTypo(
  307. Result.getLookupNameInfo(), Kind, S, SS,
  308. llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
  309. CTK_ErrorRecovery);
  310. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  311. TemplateTy Template;
  312. bool MemberOfUnknownSpecialization;
  313. UnqualifiedId TemplateName;
  314. TemplateName.setIdentifier(NewII, NameLoc);
  315. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  316. CXXScopeSpec NewSS, *NewSSPtr = SS;
  317. if (SS && NNS) {
  318. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  319. NewSSPtr = &NewSS;
  320. }
  321. if (Correction && (NNS || NewII != &II) &&
  322. // Ignore a correction to a template type as the to-be-corrected
  323. // identifier is not a template (typo correction for template names
  324. // is handled elsewhere).
  325. !(getLangOpts().CPlusPlus && NewSSPtr &&
  326. isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
  327. Template, MemberOfUnknownSpecialization))) {
  328. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  329. isClassName, HasTrailingDot, ObjectTypePtr,
  330. IsCtorOrDtorName,
  331. WantNontrivialTypeSourceInfo);
  332. if (Ty) {
  333. diagnoseTypo(Correction,
  334. PDiag(diag::err_unknown_type_or_class_name_suggest)
  335. << Result.getLookupName() << isClassName);
  336. if (SS && NNS)
  337. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  338. *CorrectedII = NewII;
  339. return Ty;
  340. }
  341. }
  342. }
  343. // If typo correction failed or was not performed, fall through
  344. case LookupResult::FoundOverloaded:
  345. case LookupResult::FoundUnresolvedValue:
  346. Result.suppressDiagnostics();
  347. return nullptr;
  348. case LookupResult::Ambiguous:
  349. // Recover from type-hiding ambiguities by hiding the type. We'll
  350. // do the lookup again when looking for an object, and we can
  351. // diagnose the error then. If we don't do this, then the error
  352. // about hiding the type will be immediately followed by an error
  353. // that only makes sense if the identifier was treated like a type.
  354. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  355. Result.suppressDiagnostics();
  356. return nullptr;
  357. }
  358. // Look to see if we have a type anywhere in the list of results.
  359. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  360. Res != ResEnd; ++Res) {
  361. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
  362. if (!IIDecl ||
  363. (*Res)->getLocation().getRawEncoding() <
  364. IIDecl->getLocation().getRawEncoding())
  365. IIDecl = *Res;
  366. }
  367. }
  368. if (!IIDecl) {
  369. // None of the entities we found is a type, so there is no way
  370. // to even assume that the result is a type. In this case, don't
  371. // complain about the ambiguity. The parser will either try to
  372. // perform this lookup again (e.g., as an object name), which
  373. // will produce the ambiguity, or will complain that it expected
  374. // a type name.
  375. Result.suppressDiagnostics();
  376. return nullptr;
  377. }
  378. // We found a type within the ambiguous lookup; diagnose the
  379. // ambiguity and then return that type. This might be the right
  380. // answer, or it might not be, but it suppresses any attempt to
  381. // perform the name lookup again.
  382. break;
  383. case LookupResult::Found:
  384. IIDecl = Result.getFoundDecl();
  385. break;
  386. }
  387. assert(IIDecl && "Didn't find decl");
  388. QualType T;
  389. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  390. DiagnoseUseOfDecl(IIDecl, NameLoc);
  391. T = Context.getTypeDeclType(TD);
  392. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  393. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  394. // constructor or destructor name (in such a case, the scope specifier
  395. // will be attached to the enclosing Expr or Decl node).
  396. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
  397. if (WantNontrivialTypeSourceInfo) {
  398. // Construct a type with type-source information.
  399. TypeLocBuilder Builder;
  400. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  401. T = getElaboratedType(ETK_None, *SS, T);
  402. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  403. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  404. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  405. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  406. } else {
  407. T = getElaboratedType(ETK_None, *SS, T);
  408. }
  409. }
  410. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  411. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  412. if (!HasTrailingDot)
  413. T = Context.getObjCInterfaceType(IDecl);
  414. }
  415. if (T.isNull()) {
  416. // If it's not plausibly a type, suppress diagnostics.
  417. Result.suppressDiagnostics();
  418. return nullptr;
  419. }
  420. return ParsedType::make(T);
  421. }
  422. // Builds a fake NNS for the given decl context.
  423. static NestedNameSpecifier *
  424. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  425. for (;; DC = DC->getLookupParent()) {
  426. DC = DC->getPrimaryContext();
  427. auto *ND = dyn_cast<NamespaceDecl>(DC);
  428. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  429. return NestedNameSpecifier::Create(Context, nullptr, ND);
  430. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  431. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  432. RD->getTypeForDecl());
  433. else if (isa<TranslationUnitDecl>(DC))
  434. return NestedNameSpecifier::GlobalSpecifier(Context);
  435. }
  436. llvm_unreachable("something isn't in TU scope?");
  437. }
  438. /// Find the parent class with dependent bases of the innermost enclosing method
  439. /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
  440. /// up allowing unqualified dependent type names at class-level, which MSVC
  441. /// correctly rejects.
  442. static const CXXRecordDecl *
  443. findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
  444. for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
  445. DC = DC->getPrimaryContext();
  446. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  447. if (MD->getParent()->hasAnyDependentBases())
  448. return MD->getParent();
  449. }
  450. return nullptr;
  451. }
  452. ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
  453. SourceLocation NameLoc,
  454. bool IsTemplateTypeArg) {
  455. assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
  456. NestedNameSpecifier *NNS = nullptr;
  457. if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
  458. // If we weren't able to parse a default template argument, delay lookup
  459. // until instantiation time by making a non-dependent DependentTypeName. We
  460. // pretend we saw a NestedNameSpecifier referring to the current scope, and
  461. // lookup is retried.
  462. // FIXME: This hurts our diagnostic quality, since we get errors like "no
  463. // type named 'Foo' in 'current_namespace'" when the user didn't write any
  464. // name specifiers.
  465. NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  466. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  467. } else if (const CXXRecordDecl *RD =
  468. findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
  469. // Build a DependentNameType that will perform lookup into RD at
  470. // instantiation time.
  471. NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  472. RD->getTypeForDecl());
  473. // Diagnose that this identifier was undeclared, and retry the lookup during
  474. // template instantiation.
  475. Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
  476. << RD;
  477. } else {
  478. // This is not a situation that we should recover from.
  479. return ParsedType();
  480. }
  481. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  482. // Build type location information. We synthesized the qualifier, so we have
  483. // to build a fake NestedNameSpecifierLoc.
  484. NestedNameSpecifierLocBuilder NNSLocBuilder;
  485. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  486. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  487. TypeLocBuilder Builder;
  488. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  489. DepTL.setNameLoc(NameLoc);
  490. DepTL.setElaboratedKeywordLoc(SourceLocation());
  491. DepTL.setQualifierLoc(QualifierLoc);
  492. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  493. }
  494. /// isTagName() - This method is called *for error recovery purposes only*
  495. /// to determine if the specified name is a valid tag name ("struct foo"). If
  496. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  497. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  498. /// cases in C where the user forgot to specify the tag.
  499. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  500. // Do a tag name lookup in this scope.
  501. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  502. LookupName(R, S, false);
  503. R.suppressDiagnostics();
  504. if (R.getResultKind() == LookupResult::Found)
  505. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  506. switch (TD->getTagKind()) {
  507. case TTK_Struct: return DeclSpec::TST_struct;
  508. case TTK_Interface: return DeclSpec::TST_interface;
  509. case TTK_Union: return DeclSpec::TST_union;
  510. case TTK_Class: return DeclSpec::TST_class;
  511. case TTK_Enum: return DeclSpec::TST_enum;
  512. }
  513. }
  514. return DeclSpec::TST_unspecified;
  515. }
  516. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  517. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  518. /// then downgrade the missing typename error to a warning.
  519. /// This is needed for MSVC compatibility; Example:
  520. /// @code
  521. /// template<class T> class A {
  522. /// public:
  523. /// typedef int TYPE;
  524. /// };
  525. /// template<class T> class B : public A<T> {
  526. /// public:
  527. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  528. /// };
  529. /// @endcode
  530. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  531. if (CurContext->isRecord()) {
  532. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  533. return true;
  534. const Type *Ty = SS->getScopeRep()->getAsType();
  535. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  536. for (const auto &Base : RD->bases())
  537. if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  538. return true;
  539. return S->isFunctionPrototypeScope();
  540. }
  541. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  542. }
  543. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  544. SourceLocation IILoc,
  545. Scope *S,
  546. CXXScopeSpec *SS,
  547. ParsedType &SuggestedType,
  548. bool AllowClassTemplates) {
  549. // We don't have anything to suggest (yet).
  550. SuggestedType = nullptr;
  551. // There may have been a typo in the name of the type. Look up typo
  552. // results, in case we have something that we can suggest.
  553. if (TypoCorrection Corrected =
  554. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  555. llvm::make_unique<TypeNameValidatorCCC>(
  556. false, false, AllowClassTemplates),
  557. CTK_ErrorRecovery)) {
  558. if (Corrected.isKeyword()) {
  559. // We corrected to a keyword.
  560. diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
  561. II = Corrected.getCorrectionAsIdentifierInfo();
  562. } else {
  563. // We found a similarly-named type or interface; suggest that.
  564. if (!SS || !SS->isSet()) {
  565. diagnoseTypo(Corrected,
  566. PDiag(diag::err_unknown_typename_suggest) << II);
  567. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  568. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  569. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  570. II->getName().equals(CorrectedStr);
  571. diagnoseTypo(Corrected,
  572. PDiag(diag::err_unknown_nested_typename_suggest)
  573. << II << DC << DroppedSpecifier << SS->getRange());
  574. } else {
  575. llvm_unreachable("could not have corrected a typo here");
  576. }
  577. CXXScopeSpec tmpSS;
  578. if (Corrected.getCorrectionSpecifier())
  579. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  580. SourceRange(IILoc));
  581. SuggestedType =
  582. getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
  583. tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
  584. /*IsCtorOrDtorName=*/false,
  585. /*NonTrivialTypeSourceInfo=*/true);
  586. }
  587. return;
  588. }
  589. if (getLangOpts().CPlusPlus) {
  590. // See if II is a class template that the user forgot to pass arguments to.
  591. UnqualifiedId Name;
  592. Name.setIdentifier(II, IILoc);
  593. CXXScopeSpec EmptySS;
  594. TemplateTy TemplateResult;
  595. bool MemberOfUnknownSpecialization;
  596. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  597. Name, nullptr, true, TemplateResult,
  598. MemberOfUnknownSpecialization) == TNK_Type_template) {
  599. TemplateName TplName = TemplateResult.get();
  600. Diag(IILoc, diag::err_template_missing_args) << TplName;
  601. if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
  602. Diag(TplDecl->getLocation(), diag::note_template_decl_here)
  603. << TplDecl->getTemplateParameters()->getSourceRange();
  604. }
  605. return;
  606. }
  607. }
  608. // FIXME: Should we move the logic that tries to recover from a missing tag
  609. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  610. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  611. Diag(IILoc, diag::err_unknown_typename) << II;
  612. else if (DeclContext *DC = computeDeclContext(*SS, false))
  613. Diag(IILoc, diag::err_typename_nested_not_found)
  614. << II << DC << SS->getRange();
  615. else if (isDependentScopeSpecifier(*SS)) {
  616. unsigned DiagID = diag::err_typename_missing;
  617. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  618. DiagID = diag::ext_typename_missing;
  619. Diag(SS->getRange().getBegin(), DiagID)
  620. << SS->getScopeRep() << II->getName()
  621. << SourceRange(SS->getRange().getBegin(), IILoc)
  622. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  623. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  624. *SS, *II, IILoc).get();
  625. } else {
  626. assert(SS && SS->isInvalid() &&
  627. "Invalid scope specifier has already been diagnosed");
  628. }
  629. }
  630. /// \brief Determine whether the given result set contains either a type name
  631. /// or
  632. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  633. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  634. NextToken.is(tok::less);
  635. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  636. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  637. return true;
  638. if (CheckTemplate && isa<TemplateDecl>(*I))
  639. return true;
  640. }
  641. return false;
  642. }
  643. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  644. Scope *S, CXXScopeSpec &SS,
  645. IdentifierInfo *&Name,
  646. SourceLocation NameLoc) {
  647. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  648. SemaRef.LookupParsedName(R, S, &SS);
  649. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  650. StringRef FixItTagName;
  651. switch (Tag->getTagKind()) {
  652. case TTK_Class:
  653. FixItTagName = "class ";
  654. break;
  655. case TTK_Enum:
  656. FixItTagName = "enum ";
  657. break;
  658. case TTK_Struct:
  659. FixItTagName = "struct ";
  660. break;
  661. case TTK_Interface:
  662. FixItTagName = "__interface ";
  663. break;
  664. case TTK_Union:
  665. FixItTagName = "union ";
  666. break;
  667. }
  668. StringRef TagName = FixItTagName.drop_back();
  669. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  670. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  671. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  672. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  673. I != IEnd; ++I)
  674. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  675. << Name << TagName;
  676. // Replace lookup results with just the tag decl.
  677. Result.clear(Sema::LookupTagName);
  678. SemaRef.LookupParsedName(Result, S, &SS);
  679. return true;
  680. }
  681. return false;
  682. }
  683. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  684. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  685. QualType T, SourceLocation NameLoc) {
  686. ASTContext &Context = S.Context;
  687. TypeLocBuilder Builder;
  688. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  689. T = S.getElaboratedType(ETK_None, SS, T);
  690. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  691. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  692. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  693. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  694. }
  695. Sema::NameClassification
  696. Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
  697. SourceLocation NameLoc, const Token &NextToken,
  698. bool IsAddressOfOperand,
  699. std::unique_ptr<CorrectionCandidateCallback> CCC) {
  700. DeclarationNameInfo NameInfo(Name, NameLoc);
  701. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  702. if (NextToken.is(tok::coloncolon)) {
  703. NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
  704. BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
  705. }
  706. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  707. LookupParsedName(Result, S, &SS, !CurMethod);
  708. // For unqualified lookup in a class template in MSVC mode, look into
  709. // dependent base classes where the primary class template is known.
  710. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  711. if (ParsedType TypeInBase =
  712. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  713. return TypeInBase;
  714. }
  715. // Perform lookup for Objective-C instance variables (including automatically
  716. // synthesized instance variables), if we're in an Objective-C method.
  717. // FIXME: This lookup really, really needs to be folded in to the normal
  718. // unqualified lookup mechanism.
  719. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  720. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  721. if (E.get() || E.isInvalid())
  722. return E;
  723. }
  724. bool SecondTry = false;
  725. bool IsFilteredTemplateName = false;
  726. Corrected:
  727. switch (Result.getResultKind()) {
  728. case LookupResult::NotFound:
  729. // If an unqualified-id is followed by a '(', then we have a function
  730. // call.
  731. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  732. // In C++, this is an ADL-only call.
  733. // FIXME: Reference?
  734. if (getLangOpts().CPlusPlus)
  735. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  736. // C90 6.3.2.2:
  737. // If the expression that precedes the parenthesized argument list in a
  738. // function call consists solely of an identifier, and if no
  739. // declaration is visible for this identifier, the identifier is
  740. // implicitly declared exactly as if, in the innermost block containing
  741. // the function call, the declaration
  742. //
  743. // extern int identifier ();
  744. //
  745. // appeared.
  746. //
  747. // We also allow this in C99 as an extension.
  748. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  749. Result.addDecl(D);
  750. Result.resolveKind();
  751. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  752. }
  753. }
  754. // In C, we first see whether there is a tag type by the same name, in
  755. // which case it's likely that the user just forgot to write "enum",
  756. // "struct", or "union".
  757. if (!getLangOpts().CPlusPlus && !SecondTry &&
  758. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  759. break;
  760. }
  761. // Perform typo correction to determine if there is another name that is
  762. // close to this name.
  763. if (!SecondTry && CCC) {
  764. SecondTry = true;
  765. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  766. Result.getLookupKind(), S,
  767. &SS, std::move(CCC),
  768. CTK_ErrorRecovery)) {
  769. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  770. unsigned QualifiedDiag = diag::err_no_member_suggest;
  771. NamedDecl *FirstDecl = Corrected.getFoundDecl();
  772. NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
  773. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  774. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  775. UnqualifiedDiag = diag::err_no_template_suggest;
  776. QualifiedDiag = diag::err_no_member_template_suggest;
  777. } else if (UnderlyingFirstDecl &&
  778. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  779. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  780. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  781. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  782. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  783. }
  784. if (SS.isEmpty()) {
  785. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  786. } else {// FIXME: is this even reachable? Test it.
  787. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  788. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  789. Name->getName().equals(CorrectedStr);
  790. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  791. << Name << computeDeclContext(SS, false)
  792. << DroppedSpecifier << SS.getRange());
  793. }
  794. // Update the name, so that the caller has the new name.
  795. Name = Corrected.getCorrectionAsIdentifierInfo();
  796. // Typo correction corrected to a keyword.
  797. if (Corrected.isKeyword())
  798. return Name;
  799. // Also update the LookupResult...
  800. // FIXME: This should probably go away at some point
  801. Result.clear();
  802. Result.setLookupName(Corrected.getCorrection());
  803. if (FirstDecl)
  804. Result.addDecl(FirstDecl);
  805. // If we found an Objective-C instance variable, let
  806. // LookupInObjCMethod build the appropriate expression to
  807. // reference the ivar.
  808. // FIXME: This is a gross hack.
  809. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  810. Result.clear();
  811. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  812. return E;
  813. }
  814. goto Corrected;
  815. }
  816. }
  817. // We failed to correct; just fall through and let the parser deal with it.
  818. Result.suppressDiagnostics();
  819. return NameClassification::Unknown();
  820. case LookupResult::NotFoundInCurrentInstantiation: {
  821. // We performed name lookup into the current instantiation, and there were
  822. // dependent bases, so we treat this result the same way as any other
  823. // dependent nested-name-specifier.
  824. // C++ [temp.res]p2:
  825. // A name used in a template declaration or definition and that is
  826. // dependent on a template-parameter is assumed not to name a type
  827. // unless the applicable name lookup finds a type name or the name is
  828. // qualified by the keyword typename.
  829. //
  830. // FIXME: If the next token is '<', we might want to ask the parser to
  831. // perform some heroics to see if we actually have a
  832. // template-argument-list, which would indicate a missing 'template'
  833. // keyword here.
  834. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  835. NameInfo, IsAddressOfOperand,
  836. /*TemplateArgs=*/nullptr);
  837. }
  838. case LookupResult::Found:
  839. case LookupResult::FoundOverloaded:
  840. case LookupResult::FoundUnresolvedValue:
  841. break;
  842. case LookupResult::Ambiguous:
  843. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  844. hasAnyAcceptableTemplateNames(Result)) {
  845. // C++ [temp.local]p3:
  846. // A lookup that finds an injected-class-name (10.2) can result in an
  847. // ambiguity in certain cases (for example, if it is found in more than
  848. // one base class). If all of the injected-class-names that are found
  849. // refer to specializations of the same class template, and if the name
  850. // is followed by a template-argument-list, the reference refers to the
  851. // class template itself and not a specialization thereof, and is not
  852. // ambiguous.
  853. //
  854. // This filtering can make an ambiguous result into an unambiguous one,
  855. // so try again after filtering out template names.
  856. FilterAcceptableTemplateNames(Result);
  857. if (!Result.isAmbiguous()) {
  858. IsFilteredTemplateName = true;
  859. break;
  860. }
  861. }
  862. // Diagnose the ambiguity and return an error.
  863. return NameClassification::Error();
  864. }
  865. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  866. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  867. // C++ [temp.names]p3:
  868. // After name lookup (3.4) finds that a name is a template-name or that
  869. // an operator-function-id or a literal- operator-id refers to a set of
  870. // overloaded functions any member of which is a function template if
  871. // this is followed by a <, the < is always taken as the delimiter of a
  872. // template-argument-list and never as the less-than operator.
  873. if (!IsFilteredTemplateName)
  874. FilterAcceptableTemplateNames(Result);
  875. if (!Result.empty()) {
  876. bool IsFunctionTemplate;
  877. bool IsVarTemplate;
  878. TemplateName Template;
  879. if (Result.end() - Result.begin() > 1) {
  880. IsFunctionTemplate = true;
  881. Template = Context.getOverloadedTemplateName(Result.begin(),
  882. Result.end());
  883. } else {
  884. TemplateDecl *TD
  885. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  886. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  887. IsVarTemplate = isa<VarTemplateDecl>(TD);
  888. if (SS.isSet() && !SS.isInvalid())
  889. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  890. /*TemplateKeyword=*/false,
  891. TD);
  892. else
  893. Template = TemplateName(TD);
  894. }
  895. if (IsFunctionTemplate) {
  896. // Function templates always go through overload resolution, at which
  897. // point we'll perform the various checks (e.g., accessibility) we need
  898. // to based on which function we selected.
  899. Result.suppressDiagnostics();
  900. return NameClassification::FunctionTemplate(Template);
  901. }
  902. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  903. : NameClassification::TypeTemplate(Template);
  904. }
  905. }
  906. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  907. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  908. DiagnoseUseOfDecl(Type, NameLoc);
  909. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  910. QualType T = Context.getTypeDeclType(Type);
  911. if (SS.isNotEmpty())
  912. return buildNestedType(*this, SS, T, NameLoc);
  913. return ParsedType::make(T);
  914. }
  915. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  916. if (!Class) {
  917. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  918. if (ObjCCompatibleAliasDecl *Alias =
  919. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  920. Class = Alias->getClassInterface();
  921. }
  922. if (Class) {
  923. DiagnoseUseOfDecl(Class, NameLoc);
  924. if (NextToken.is(tok::period)) {
  925. // Interface. <something> is parsed as a property reference expression.
  926. // Just return "unknown" as a fall-through for now.
  927. Result.suppressDiagnostics();
  928. return NameClassification::Unknown();
  929. }
  930. QualType T = Context.getObjCInterfaceType(Class);
  931. return ParsedType::make(T);
  932. }
  933. // We can have a type template here if we're classifying a template argument.
  934. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
  935. return NameClassification::TypeTemplate(
  936. TemplateName(cast<TemplateDecl>(FirstDecl)));
  937. // Check for a tag type hidden by a non-type decl in a few cases where it
  938. // seems likely a type is wanted instead of the non-type that was found.
  939. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  940. if ((NextToken.is(tok::identifier) ||
  941. (NextIsOp &&
  942. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  943. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  944. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  945. DiagnoseUseOfDecl(Type, NameLoc);
  946. QualType T = Context.getTypeDeclType(Type);
  947. if (SS.isNotEmpty())
  948. return buildNestedType(*this, SS, T, NameLoc);
  949. return ParsedType::make(T);
  950. }
  951. if (FirstDecl->isCXXClassMember())
  952. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  953. nullptr, S);
  954. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  955. return BuildDeclarationNameExpr(SS, Result, ADL);
  956. }
  957. // Determines the context to return to after temporarily entering a
  958. // context. This depends in an unnecessarily complicated way on the
  959. // exact ordering of callbacks from the parser.
  960. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  961. // Functions defined inline within classes aren't parsed until we've
  962. // finished parsing the top-level class, so the top-level class is
  963. // the context we'll need to return to.
  964. // A Lambda call operator whose parent is a class must not be treated
  965. // as an inline member function. A Lambda can be used legally
  966. // either as an in-class member initializer or a default argument. These
  967. // are parsed once the class has been marked complete and so the containing
  968. // context would be the nested class (when the lambda is defined in one);
  969. // If the class is not complete, then the lambda is being used in an
  970. // ill-formed fashion (such as to specify the width of a bit-field, or
  971. // in an array-bound) - in which case we still want to return the
  972. // lexically containing DC (which could be a nested class).
  973. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  974. DC = DC->getLexicalParent();
  975. // A function not defined within a class will always return to its
  976. // lexical context.
  977. if (!isa<CXXRecordDecl>(DC))
  978. return DC;
  979. // A C++ inline method/friend is parsed *after* the topmost class
  980. // it was declared in is fully parsed ("complete"); the topmost
  981. // class is the context we need to return to.
  982. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  983. DC = RD;
  984. // Return the declaration context of the topmost class the inline method is
  985. // declared in.
  986. return DC;
  987. }
  988. return DC->getLexicalParent();
  989. }
  990. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  991. assert(getContainingDC(DC) == CurContext &&
  992. "The next DeclContext should be lexically contained in the current one.");
  993. CurContext = DC;
  994. S->setEntity(DC);
  995. }
  996. void Sema::PopDeclContext() {
  997. assert(CurContext && "DeclContext imbalance!");
  998. CurContext = getContainingDC(CurContext);
  999. assert(CurContext && "Popped translation unit!");
  1000. }
  1001. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  1002. Decl *D) {
  1003. // Unlike PushDeclContext, the context to which we return is not necessarily
  1004. // the containing DC of TD, because the new context will be some pre-existing
  1005. // TagDecl definition instead of a fresh one.
  1006. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  1007. CurContext = cast<TagDecl>(D)->getDefinition();
  1008. assert(CurContext && "skipping definition of undefined tag");
  1009. // Start lookups from the parent of the current context; we don't want to look
  1010. // into the pre-existing complete definition.
  1011. S->setEntity(CurContext->getLookupParent());
  1012. return Result;
  1013. }
  1014. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  1015. CurContext = static_cast<decltype(CurContext)>(Context);
  1016. }
  1017. /// EnterDeclaratorContext - Used when we must lookup names in the context
  1018. /// of a declarator's nested name specifier.
  1019. ///
  1020. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  1021. // C++0x [basic.lookup.unqual]p13:
  1022. // A name used in the definition of a static data member of class
  1023. // X (after the qualified-id of the static member) is looked up as
  1024. // if the name was used in a member function of X.
  1025. // C++0x [basic.lookup.unqual]p14:
  1026. // If a variable member of a namespace is defined outside of the
  1027. // scope of its namespace then any name used in the definition of
  1028. // the variable member (after the declarator-id) is looked up as
  1029. // if the definition of the variable member occurred in its
  1030. // namespace.
  1031. // Both of these imply that we should push a scope whose context
  1032. // is the semantic context of the declaration. We can't use
  1033. // PushDeclContext here because that context is not necessarily
  1034. // lexically contained in the current context. Fortunately,
  1035. // the containing scope should have the appropriate information.
  1036. assert(!S->getEntity() && "scope already has entity");
  1037. #ifndef NDEBUG
  1038. Scope *Ancestor = S->getParent();
  1039. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1040. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1041. #endif
  1042. CurContext = DC;
  1043. S->setEntity(DC);
  1044. }
  1045. void Sema::ExitDeclaratorContext(Scope *S) {
  1046. assert(S->getEntity() == CurContext && "Context imbalance!");
  1047. // Switch back to the lexical context. The safety of this is
  1048. // enforced by an assert in EnterDeclaratorContext.
  1049. Scope *Ancestor = S->getParent();
  1050. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1051. CurContext = Ancestor->getEntity();
  1052. // We don't need to do anything with the scope, which is going to
  1053. // disappear.
  1054. }
  1055. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1056. // We assume that the caller has already called
  1057. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1058. FunctionDecl *FD = D->getAsFunction();
  1059. if (!FD)
  1060. return;
  1061. // Same implementation as PushDeclContext, but enters the context
  1062. // from the lexical parent, rather than the top-level class.
  1063. assert(CurContext == FD->getLexicalParent() &&
  1064. "The next DeclContext should be lexically contained in the current one.");
  1065. CurContext = FD;
  1066. S->setEntity(CurContext);
  1067. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1068. ParmVarDecl *Param = FD->getParamDecl(P);
  1069. // If the parameter has an identifier, then add it to the scope
  1070. if (Param->getIdentifier()) {
  1071. S->AddDecl(Param);
  1072. IdResolver.AddDecl(Param);
  1073. }
  1074. }
  1075. }
  1076. void Sema::ActOnExitFunctionContext() {
  1077. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1078. // rather than the top-level class.
  1079. assert(CurContext && "DeclContext imbalance!");
  1080. CurContext = CurContext->getLexicalParent();
  1081. assert(CurContext && "Popped translation unit!");
  1082. }
  1083. /// \brief Determine whether we allow overloading of the function
  1084. /// PrevDecl with another declaration.
  1085. ///
  1086. /// This routine determines whether overloading is possible, not
  1087. /// whether some new function is actually an overload. It will return
  1088. /// true in C++ (where we can always provide overloads) or, as an
  1089. /// extension, in C when the previous function is already an
  1090. /// overloaded function declaration or has the "overloadable"
  1091. /// attribute.
  1092. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1093. ASTContext &Context) {
  1094. if (Context.getLangOpts().CPlusPlus)
  1095. return true;
  1096. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1097. return true;
  1098. return (Previous.getResultKind() == LookupResult::Found
  1099. && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
  1100. }
  1101. /// Add this decl to the scope shadowed decl chains.
  1102. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1103. // Move up the scope chain until we find the nearest enclosing
  1104. // non-transparent context. The declaration will be introduced into this
  1105. // scope.
  1106. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1107. S = S->getParent();
  1108. // Add scoped declarations into their context, so that they can be
  1109. // found later. Declarations without a context won't be inserted
  1110. // into any context.
  1111. if (AddToContext)
  1112. CurContext->addDecl(D);
  1113. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1114. // are function-local declarations.
  1115. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1116. !D->getDeclContext()->getRedeclContext()->Equals(
  1117. D->getLexicalDeclContext()->getRedeclContext()) &&
  1118. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1119. return;
  1120. // Template instantiations should also not be pushed into scope.
  1121. if (isa<FunctionDecl>(D) &&
  1122. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1123. return;
  1124. // If this replaces anything in the current scope,
  1125. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1126. IEnd = IdResolver.end();
  1127. for (; I != IEnd; ++I) {
  1128. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1129. S->RemoveDecl(*I);
  1130. IdResolver.RemoveDecl(*I);
  1131. // Should only need to replace one decl.
  1132. break;
  1133. }
  1134. }
  1135. S->AddDecl(D);
  1136. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1137. // Implicitly-generated labels may end up getting generated in an order that
  1138. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1139. // the label at the appropriate place in the identifier chain.
  1140. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1141. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1142. if (IDC == CurContext) {
  1143. if (!S->isDeclScope(*I))
  1144. continue;
  1145. } else if (IDC->Encloses(CurContext))
  1146. break;
  1147. }
  1148. IdResolver.InsertDeclAfter(I, D);
  1149. } else {
  1150. IdResolver.AddDecl(D);
  1151. }
  1152. }
  1153. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  1154. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  1155. TUScope->AddDecl(D);
  1156. }
  1157. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1158. bool AllowInlineNamespace) {
  1159. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1160. }
  1161. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1162. DeclContext *TargetDC = DC->getPrimaryContext();
  1163. do {
  1164. if (DeclContext *ScopeDC = S->getEntity())
  1165. if (ScopeDC->getPrimaryContext() == TargetDC)
  1166. return S;
  1167. } while ((S = S->getParent()));
  1168. return nullptr;
  1169. }
  1170. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1171. DeclContext*,
  1172. ASTContext&);
  1173. /// Filters out lookup results that don't fall within the given scope
  1174. /// as determined by isDeclInScope.
  1175. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1176. bool ConsiderLinkage,
  1177. bool AllowInlineNamespace) {
  1178. LookupResult::Filter F = R.makeFilter();
  1179. while (F.hasNext()) {
  1180. NamedDecl *D = F.next();
  1181. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1182. continue;
  1183. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1184. continue;
  1185. F.erase();
  1186. }
  1187. F.done();
  1188. }
  1189. static bool isUsingDecl(NamedDecl *D) {
  1190. return isa<UsingShadowDecl>(D) ||
  1191. isa<UnresolvedUsingTypenameDecl>(D) ||
  1192. isa<UnresolvedUsingValueDecl>(D);
  1193. }
  1194. /// Removes using shadow declarations from the lookup results.
  1195. static void RemoveUsingDecls(LookupResult &R) {
  1196. LookupResult::Filter F = R.makeFilter();
  1197. while (F.hasNext())
  1198. if (isUsingDecl(F.next()))
  1199. F.erase();
  1200. F.done();
  1201. }
  1202. /// \brief Check for this common pattern:
  1203. /// @code
  1204. /// class S {
  1205. /// S(const S&); // DO NOT IMPLEMENT
  1206. /// void operator=(const S&); // DO NOT IMPLEMENT
  1207. /// };
  1208. /// @endcode
  1209. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1210. // FIXME: Should check for private access too but access is set after we get
  1211. // the decl here.
  1212. if (D->doesThisDeclarationHaveABody())
  1213. return false;
  1214. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1215. return CD->isCopyConstructor();
  1216. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  1217. return Method->isCopyAssignmentOperator();
  1218. return false;
  1219. }
  1220. // We need this to handle
  1221. //
  1222. // typedef struct {
  1223. // void *foo() { return 0; }
  1224. // } A;
  1225. //
  1226. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1227. // for example. If 'A', foo will have external linkage. If we have '*A',
  1228. // foo will have no linkage. Since we can't know until we get to the end
  1229. // of the typedef, this function finds out if D might have non-external linkage.
  1230. // Callers should verify at the end of the TU if it D has external linkage or
  1231. // not.
  1232. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1233. const DeclContext *DC = D->getDeclContext();
  1234. while (!DC->isTranslationUnit()) {
  1235. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1236. if (!RD->hasNameForLinkage())
  1237. return true;
  1238. }
  1239. DC = DC->getParent();
  1240. }
  1241. return !D->isExternallyVisible();
  1242. }
  1243. // FIXME: This needs to be refactored; some other isInMainFile users want
  1244. // these semantics.
  1245. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1246. if (S.TUKind != TU_Complete)
  1247. return false;
  1248. return S.SourceMgr.isInMainFile(Loc);
  1249. }
  1250. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1251. assert(D);
  1252. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1253. return false;
  1254. // Ignore all entities declared within templates, and out-of-line definitions
  1255. // of members of class templates.
  1256. if (D->getDeclContext()->isDependentContext() ||
  1257. D->getLexicalDeclContext()->isDependentContext())
  1258. return false;
  1259. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1260. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1261. return false;
  1262. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1263. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1264. return false;
  1265. } else {
  1266. // 'static inline' functions are defined in headers; don't warn.
  1267. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1268. return false;
  1269. }
  1270. if (FD->doesThisDeclarationHaveABody() &&
  1271. Context.DeclMustBeEmitted(FD))
  1272. return false;
  1273. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1274. // Constants and utility variables are defined in headers with internal
  1275. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1276. // like "inline".)
  1277. if (!isMainFileLoc(*this, VD->getLocation()))
  1278. return false;
  1279. if (Context.DeclMustBeEmitted(VD))
  1280. return false;
  1281. if (VD->isStaticDataMember() &&
  1282. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1283. return false;
  1284. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1285. return false;
  1286. } else {
  1287. return false;
  1288. }
  1289. // Only warn for unused decls internal to the translation unit.
  1290. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1291. // for inline functions defined in the main source file, for instance.
  1292. return mightHaveNonExternalLinkage(D);
  1293. }
  1294. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1295. if (!D)
  1296. return;
  1297. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1298. const FunctionDecl *First = FD->getFirstDecl();
  1299. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1300. return; // First should already be in the vector.
  1301. }
  1302. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1303. const VarDecl *First = VD->getFirstDecl();
  1304. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1305. return; // First should already be in the vector.
  1306. }
  1307. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1308. UnusedFileScopedDecls.push_back(D);
  1309. }
  1310. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1311. if (D->isInvalidDecl())
  1312. return false;
  1313. if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
  1314. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1315. return false;
  1316. if (isa<LabelDecl>(D))
  1317. return true;
  1318. // Except for labels, we only care about unused decls that are local to
  1319. // functions.
  1320. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1321. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1322. // For dependent types, the diagnostic is deferred.
  1323. WithinFunction =
  1324. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1325. if (!WithinFunction)
  1326. return false;
  1327. if (isa<TypedefNameDecl>(D))
  1328. return true;
  1329. // White-list anything that isn't a local variable.
  1330. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1331. return false;
  1332. // Types of valid local variables should be complete, so this should succeed.
  1333. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1334. // White-list anything with an __attribute__((unused)) type.
  1335. const auto *Ty = VD->getType().getTypePtr();
  1336. // Only look at the outermost level of typedef.
  1337. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1338. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1339. return false;
  1340. }
  1341. // If we failed to complete the type for some reason, or if the type is
  1342. // dependent, don't diagnose the variable.
  1343. if (Ty->isIncompleteType() || Ty->isDependentType())
  1344. return false;
  1345. // Look at the element type to ensure that the warning behaviour is
  1346. // consistent for both scalars and arrays.
  1347. Ty = Ty->getBaseElementTypeUnsafe();
  1348. if (const TagType *TT = Ty->getAs<TagType>()) {
  1349. const TagDecl *Tag = TT->getDecl();
  1350. if (Tag->hasAttr<UnusedAttr>())
  1351. return false;
  1352. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1353. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1354. return false;
  1355. if (const Expr *Init = VD->getInit()) {
  1356. if (const ExprWithCleanups *Cleanups =
  1357. dyn_cast<ExprWithCleanups>(Init))
  1358. Init = Cleanups->getSubExpr();
  1359. const CXXConstructExpr *Construct =
  1360. dyn_cast<CXXConstructExpr>(Init);
  1361. if (Construct && !Construct->isElidable()) {
  1362. CXXConstructorDecl *CD = Construct->getConstructor();
  1363. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
  1364. return false;
  1365. }
  1366. }
  1367. }
  1368. }
  1369. // TODO: __attribute__((unused)) templates?
  1370. }
  1371. return true;
  1372. }
  1373. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1374. FixItHint &Hint) {
  1375. if (isa<LabelDecl>(D)) {
  1376. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1377. tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
  1378. if (AfterColon.isInvalid())
  1379. return;
  1380. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1381. getCharRange(D->getLocStart(), AfterColon));
  1382. }
  1383. }
  1384. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1385. if (D->getTypeForDecl()->isDependentType())
  1386. return;
  1387. for (auto *TmpD : D->decls()) {
  1388. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1389. DiagnoseUnusedDecl(T);
  1390. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1391. DiagnoseUnusedNestedTypedefs(R);
  1392. }
  1393. }
  1394. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1395. /// unless they are marked attr(unused).
  1396. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1397. if (!ShouldDiagnoseUnusedDecl(D))
  1398. return;
  1399. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1400. // typedefs can be referenced later on, so the diagnostics are emitted
  1401. // at end-of-translation-unit.
  1402. UnusedLocalTypedefNameCandidates.insert(TD);
  1403. return;
  1404. }
  1405. FixItHint Hint;
  1406. GenerateFixForUnusedDecl(D, Context, Hint);
  1407. unsigned DiagID;
  1408. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1409. DiagID = diag::warn_unused_exception_param;
  1410. else if (isa<LabelDecl>(D))
  1411. DiagID = diag::warn_unused_label;
  1412. else
  1413. DiagID = diag::warn_unused_variable;
  1414. Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
  1415. }
  1416. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1417. // Verify that we have no forward references left. If so, there was a goto
  1418. // or address of a label taken, but no definition of it. Label fwd
  1419. // definitions are indicated with a null substmt which is also not a resolved
  1420. // MS inline assembly label name.
  1421. bool Diagnose = false;
  1422. if (L->isMSAsmLabel())
  1423. Diagnose = !L->isResolvedMSAsmLabel();
  1424. else
  1425. Diagnose = L->getStmt() == nullptr;
  1426. if (Diagnose)
  1427. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1428. }
  1429. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1430. S->mergeNRVOIntoParent();
  1431. if (S->decl_empty()) return;
  1432. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1433. "Scope shouldn't contain decls!");
  1434. for (auto *TmpD : S->decls()) {
  1435. assert(TmpD && "This decl didn't get pushed??");
  1436. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1437. NamedDecl *D = cast<NamedDecl>(TmpD);
  1438. if (!D->getDeclName()) continue;
  1439. // Diagnose unused variables in this scope.
  1440. if (!S->hasUnrecoverableErrorOccurred()) {
  1441. DiagnoseUnusedDecl(D);
  1442. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1443. DiagnoseUnusedNestedTypedefs(RD);
  1444. }
  1445. // If this was a forward reference to a label, verify it was defined.
  1446. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1447. CheckPoppedLabel(LD, *this);
  1448. // Remove this name from our lexical scope, and warn on it if we haven't
  1449. // already.
  1450. IdResolver.RemoveDecl(D);
  1451. auto ShadowI = ShadowingDecls.find(D);
  1452. if (ShadowI != ShadowingDecls.end()) {
  1453. if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
  1454. Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
  1455. << D << FD << FD->getParent();
  1456. Diag(FD->getLocation(), diag::note_previous_declaration);
  1457. }
  1458. ShadowingDecls.erase(ShadowI);
  1459. }
  1460. }
  1461. }
  1462. /// \brief Look for an Objective-C class in the translation unit.
  1463. ///
  1464. /// \param Id The name of the Objective-C class we're looking for. If
  1465. /// typo-correction fixes this name, the Id will be updated
  1466. /// to the fixed name.
  1467. ///
  1468. /// \param IdLoc The location of the name in the translation unit.
  1469. ///
  1470. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1471. /// if there is no class with the given name.
  1472. ///
  1473. /// \returns The declaration of the named Objective-C class, or NULL if the
  1474. /// class could not be found.
  1475. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1476. SourceLocation IdLoc,
  1477. bool DoTypoCorrection) {
  1478. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1479. // creation from this context.
  1480. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1481. if (!IDecl && DoTypoCorrection) {
  1482. // Perform typo correction at the given location, but only if we
  1483. // find an Objective-C class name.
  1484. if (TypoCorrection C = CorrectTypo(
  1485. DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
  1486. llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
  1487. CTK_ErrorRecovery)) {
  1488. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1489. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1490. Id = IDecl->getIdentifier();
  1491. }
  1492. }
  1493. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1494. // This routine must always return a class definition, if any.
  1495. if (Def && Def->getDefinition())
  1496. Def = Def->getDefinition();
  1497. return Def;
  1498. }
  1499. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1500. /// from S, where a non-field would be declared. This routine copes
  1501. /// with the difference between C and C++ scoping rules in structs and
  1502. /// unions. For example, the following code is well-formed in C but
  1503. /// ill-formed in C++:
  1504. /// @code
  1505. /// struct S6 {
  1506. /// enum { BAR } e;
  1507. /// };
  1508. ///
  1509. /// void test_S6() {
  1510. /// struct S6 a;
  1511. /// a.e = BAR;
  1512. /// }
  1513. /// @endcode
  1514. /// For the declaration of BAR, this routine will return a different
  1515. /// scope. The scope S will be the scope of the unnamed enumeration
  1516. /// within S6. In C++, this routine will return the scope associated
  1517. /// with S6, because the enumeration's scope is a transparent
  1518. /// context but structures can contain non-field names. In C, this
  1519. /// routine will return the translation unit scope, since the
  1520. /// enumeration's scope is a transparent context and structures cannot
  1521. /// contain non-field names.
  1522. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1523. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1524. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1525. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1526. S = S->getParent();
  1527. return S;
  1528. }
  1529. /// \brief Looks up the declaration of "struct objc_super" and
  1530. /// saves it for later use in building builtin declaration of
  1531. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1532. /// pre-existing declaration exists no action takes place.
  1533. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1534. IdentifierInfo *II) {
  1535. if (!II->isStr("objc_msgSendSuper"))
  1536. return;
  1537. ASTContext &Context = ThisSema.Context;
  1538. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1539. SourceLocation(), Sema::LookupTagName);
  1540. ThisSema.LookupName(Result, S);
  1541. if (Result.getResultKind() == LookupResult::Found)
  1542. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1543. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1544. }
  1545. static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
  1546. switch (Error) {
  1547. case ASTContext::GE_None:
  1548. return "";
  1549. case ASTContext::GE_Missing_stdio:
  1550. return "stdio.h";
  1551. case ASTContext::GE_Missing_setjmp:
  1552. return "setjmp.h";
  1553. case ASTContext::GE_Missing_ucontext:
  1554. return "ucontext.h";
  1555. }
  1556. llvm_unreachable("unhandled error kind");
  1557. }
  1558. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1559. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1560. /// if we're creating this built-in in anticipation of redeclaring the
  1561. /// built-in.
  1562. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1563. Scope *S, bool ForRedeclaration,
  1564. SourceLocation Loc) {
  1565. LookupPredefedObjCSuperType(*this, S, II);
  1566. ASTContext::GetBuiltinTypeError Error;
  1567. QualType R = Context.GetBuiltinType(ID, Error);
  1568. if (Error) {
  1569. if (ForRedeclaration)
  1570. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1571. << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
  1572. return nullptr;
  1573. }
  1574. if (!ForRedeclaration &&
  1575. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1576. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1577. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1578. << Context.BuiltinInfo.getName(ID) << R;
  1579. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1580. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1581. Diag(Loc, diag::note_include_header_or_declare)
  1582. << Context.BuiltinInfo.getHeaderName(ID)
  1583. << Context.BuiltinInfo.getName(ID);
  1584. }
  1585. if (R.isNull())
  1586. return nullptr;
  1587. DeclContext *Parent = Context.getTranslationUnitDecl();
  1588. if (getLangOpts().CPlusPlus) {
  1589. LinkageSpecDecl *CLinkageDecl =
  1590. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1591. LinkageSpecDecl::lang_c, false);
  1592. CLinkageDecl->setImplicit();
  1593. Parent->addDecl(CLinkageDecl);
  1594. Parent = CLinkageDecl;
  1595. }
  1596. FunctionDecl *New = FunctionDecl::Create(Context,
  1597. Parent,
  1598. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1599. SC_Extern,
  1600. false,
  1601. R->isFunctionProtoType());
  1602. New->setImplicit();
  1603. // Create Decl objects for each parameter, adding them to the
  1604. // FunctionDecl.
  1605. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1606. SmallVector<ParmVarDecl*, 16> Params;
  1607. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1608. ParmVarDecl *parm =
  1609. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1610. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1611. SC_None, nullptr);
  1612. parm->setScopeInfo(0, i);
  1613. Params.push_back(parm);
  1614. }
  1615. New->setParams(Params);
  1616. }
  1617. AddKnownFunctionAttributes(New);
  1618. RegisterLocallyScopedExternCDecl(New, S);
  1619. // TUScope is the translation-unit scope to insert this function into.
  1620. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1621. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1622. // entirely, but we're not there yet.
  1623. DeclContext *SavedContext = CurContext;
  1624. CurContext = Parent;
  1625. PushOnScopeChains(New, TUScope);
  1626. CurContext = SavedContext;
  1627. return New;
  1628. }
  1629. /// Typedef declarations don't have linkage, but they still denote the same
  1630. /// entity if their types are the same.
  1631. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1632. /// isSameEntity.
  1633. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1634. TypedefNameDecl *Decl,
  1635. LookupResult &Previous) {
  1636. // This is only interesting when modules are enabled.
  1637. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1638. return;
  1639. // Empty sets are uninteresting.
  1640. if (Previous.empty())
  1641. return;
  1642. LookupResult::Filter Filter = Previous.makeFilter();
  1643. while (Filter.hasNext()) {
  1644. NamedDecl *Old = Filter.next();
  1645. // Non-hidden declarations are never ignored.
  1646. if (S.isVisible(Old))
  1647. continue;
  1648. // Declarations of the same entity are not ignored, even if they have
  1649. // different linkages.
  1650. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1651. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1652. Decl->getUnderlyingType()))
  1653. continue;
  1654. // If both declarations give a tag declaration a typedef name for linkage
  1655. // purposes, then they declare the same entity.
  1656. if (S.getLangOpts().CPlusPlus &&
  1657. OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1658. Decl->getAnonDeclWithTypedefName())
  1659. continue;
  1660. }
  1661. Filter.erase();
  1662. }
  1663. Filter.done();
  1664. }
  1665. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1666. QualType OldType;
  1667. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1668. OldType = OldTypedef->getUnderlyingType();
  1669. else
  1670. OldType = Context.getTypeDeclType(Old);
  1671. QualType NewType = New->getUnderlyingType();
  1672. if (NewType->isVariablyModifiedType()) {
  1673. // Must not redefine a typedef with a variably-modified type.
  1674. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1675. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1676. << Kind << NewType;
  1677. if (Old->getLocation().isValid())
  1678. Diag(Old->getLocation(), diag::note_previous_definition);
  1679. New->setInvalidDecl();
  1680. return true;
  1681. }
  1682. if (OldType != NewType &&
  1683. !OldType->isDependentType() &&
  1684. !NewType->isDependentType() &&
  1685. !Context.hasSameType(OldType, NewType)) {
  1686. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1687. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1688. << Kind << NewType << OldType;
  1689. if (Old->getLocation().isValid())
  1690. Diag(Old->getLocation(), diag::note_previous_definition);
  1691. New->setInvalidDecl();
  1692. return true;
  1693. }
  1694. return false;
  1695. }
  1696. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1697. /// same name and scope as a previous declaration 'Old'. Figure out
  1698. /// how to resolve this situation, merging decls or emitting
  1699. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1700. ///
  1701. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  1702. LookupResult &OldDecls) {
  1703. // If the new decl is known invalid already, don't bother doing any
  1704. // merging checks.
  1705. if (New->isInvalidDecl()) return;
  1706. // Allow multiple definitions for ObjC built-in typedefs.
  1707. // FIXME: Verify the underlying types are equivalent!
  1708. if (getLangOpts().ObjC1) {
  1709. const IdentifierInfo *TypeID = New->getIdentifier();
  1710. switch (TypeID->getLength()) {
  1711. default: break;
  1712. case 2:
  1713. {
  1714. if (!TypeID->isStr("id"))
  1715. break;
  1716. QualType T = New->getUnderlyingType();
  1717. if (!T->isPointerType())
  1718. break;
  1719. if (!T->isVoidPointerType()) {
  1720. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1721. if (!PT->isStructureType())
  1722. break;
  1723. }
  1724. Context.setObjCIdRedefinitionType(T);
  1725. // Install the built-in type for 'id', ignoring the current definition.
  1726. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1727. return;
  1728. }
  1729. case 5:
  1730. if (!TypeID->isStr("Class"))
  1731. break;
  1732. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1733. // Install the built-in type for 'Class', ignoring the current definition.
  1734. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1735. return;
  1736. case 3:
  1737. if (!TypeID->isStr("SEL"))
  1738. break;
  1739. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1740. // Install the built-in type for 'SEL', ignoring the current definition.
  1741. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1742. return;
  1743. }
  1744. // Fall through - the typedef name was not a builtin type.
  1745. }
  1746. // Verify the old decl was also a type.
  1747. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1748. if (!Old) {
  1749. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1750. << New->getDeclName();
  1751. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1752. if (OldD->getLocation().isValid())
  1753. Diag(OldD->getLocation(), diag::note_previous_definition);
  1754. return New->setInvalidDecl();
  1755. }
  1756. // If the old declaration is invalid, just give up here.
  1757. if (Old->isInvalidDecl())
  1758. return New->setInvalidDecl();
  1759. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1760. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1761. auto *NewTag = New->getAnonDeclWithTypedefName();
  1762. NamedDecl *Hidden = nullptr;
  1763. if (getLangOpts().CPlusPlus && OldTag && NewTag &&
  1764. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1765. !hasVisibleDefinition(OldTag, &Hidden)) {
  1766. // There is a definition of this tag, but it is not visible. Use it
  1767. // instead of our tag.
  1768. New->setTypeForDecl(OldTD->getTypeForDecl());
  1769. if (OldTD->isModed())
  1770. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1771. OldTD->getUnderlyingType());
  1772. else
  1773. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1774. // Make the old tag definition visible.
  1775. makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
  1776. // If this was an unscoped enumeration, yank all of its enumerators
  1777. // out of the scope.
  1778. if (isa<EnumDecl>(NewTag)) {
  1779. Scope *EnumScope = getNonFieldDeclScope(S);
  1780. for (auto *D : NewTag->decls()) {
  1781. auto *ED = cast<EnumConstantDecl>(D);
  1782. assert(EnumScope->isDeclScope(ED));
  1783. EnumScope->RemoveDecl(ED);
  1784. IdResolver.RemoveDecl(ED);
  1785. ED->getLexicalDeclContext()->removeDecl(ED);
  1786. }
  1787. }
  1788. }
  1789. }
  1790. // If the typedef types are not identical, reject them in all languages and
  1791. // with any extensions enabled.
  1792. if (isIncompatibleTypedef(Old, New))
  1793. return;
  1794. // The types match. Link up the redeclaration chain and merge attributes if
  1795. // the old declaration was a typedef.
  1796. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1797. New->setPreviousDecl(Typedef);
  1798. mergeDeclAttributes(New, Old);
  1799. }
  1800. if (getLangOpts().MicrosoftExt)
  1801. return;
  1802. if (getLangOpts().CPlusPlus) {
  1803. // C++ [dcl.typedef]p2:
  1804. // In a given non-class scope, a typedef specifier can be used to
  1805. // redefine the name of any type declared in that scope to refer
  1806. // to the type to which it already refers.
  1807. if (!isa<CXXRecordDecl>(CurContext))
  1808. return;
  1809. // C++0x [dcl.typedef]p4:
  1810. // In a given class scope, a typedef specifier can be used to redefine
  1811. // any class-name declared in that scope that is not also a typedef-name
  1812. // to refer to the type to which it already refers.
  1813. //
  1814. // This wording came in via DR424, which was a correction to the
  1815. // wording in DR56, which accidentally banned code like:
  1816. //
  1817. // struct S {
  1818. // typedef struct A { } A;
  1819. // };
  1820. //
  1821. // in the C++03 standard. We implement the C++0x semantics, which
  1822. // allow the above but disallow
  1823. //
  1824. // struct S {
  1825. // typedef int I;
  1826. // typedef int I;
  1827. // };
  1828. //
  1829. // since that was the intent of DR56.
  1830. if (!isa<TypedefNameDecl>(Old))
  1831. return;
  1832. Diag(New->getLocation(), diag::err_redefinition)
  1833. << New->getDeclName();
  1834. Diag(Old->getLocation(), diag::note_previous_definition);
  1835. return New->setInvalidDecl();
  1836. }
  1837. // Modules always permit redefinition of typedefs, as does C11.
  1838. if (getLangOpts().Modules || getLangOpts().C11)
  1839. return;
  1840. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1841. // is normally mapped to an error, but can be controlled with
  1842. // -Wtypedef-redefinition. If either the original or the redefinition is
  1843. // in a system header, don't emit this for compatibility with GCC.
  1844. if (getDiagnostics().getSuppressSystemWarnings() &&
  1845. (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1846. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1847. return;
  1848. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  1849. << New->getDeclName();
  1850. Diag(Old->getLocation(), diag::note_previous_definition);
  1851. }
  1852. /// DeclhasAttr - returns true if decl Declaration already has the target
  1853. /// attribute.
  1854. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  1855. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  1856. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  1857. for (const auto *i : D->attrs())
  1858. if (i->getKind() == A->getKind()) {
  1859. if (Ann) {
  1860. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  1861. return true;
  1862. continue;
  1863. }
  1864. // FIXME: Don't hardcode this check
  1865. if (OA && isa<OwnershipAttr>(i))
  1866. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  1867. return true;
  1868. }
  1869. return false;
  1870. }
  1871. static bool isAttributeTargetADefinition(Decl *D) {
  1872. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  1873. return VD->isThisDeclarationADefinition();
  1874. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  1875. return TD->isCompleteDefinition() || TD->isBeingDefined();
  1876. return true;
  1877. }
  1878. /// Merge alignment attributes from \p Old to \p New, taking into account the
  1879. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  1880. ///
  1881. /// \return \c true if any attributes were added to \p New.
  1882. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  1883. // Look for alignas attributes on Old, and pick out whichever attribute
  1884. // specifies the strictest alignment requirement.
  1885. AlignedAttr *OldAlignasAttr = nullptr;
  1886. AlignedAttr *OldStrictestAlignAttr = nullptr;
  1887. unsigned OldAlign = 0;
  1888. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  1889. // FIXME: We have no way of representing inherited dependent alignments
  1890. // in a case like:
  1891. // template<int A, int B> struct alignas(A) X;
  1892. // template<int A, int B> struct alignas(B) X {};
  1893. // For now, we just ignore any alignas attributes which are not on the
  1894. // definition in such a case.
  1895. if (I->isAlignmentDependent())
  1896. return false;
  1897. if (I->isAlignas())
  1898. OldAlignasAttr = I;
  1899. unsigned Align = I->getAlignment(S.Context);
  1900. if (Align > OldAlign) {
  1901. OldAlign = Align;
  1902. OldStrictestAlignAttr = I;
  1903. }
  1904. }
  1905. // Look for alignas attributes on New.
  1906. AlignedAttr *NewAlignasAttr = nullptr;
  1907. unsigned NewAlign = 0;
  1908. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  1909. if (I->isAlignmentDependent())
  1910. return false;
  1911. if (I->isAlignas())
  1912. NewAlignasAttr = I;
  1913. unsigned Align = I->getAlignment(S.Context);
  1914. if (Align > NewAlign)
  1915. NewAlign = Align;
  1916. }
  1917. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  1918. // Both declarations have 'alignas' attributes. We require them to match.
  1919. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  1920. // fall short. (If two declarations both have alignas, they must both match
  1921. // every definition, and so must match each other if there is a definition.)
  1922. // If either declaration only contains 'alignas(0)' specifiers, then it
  1923. // specifies the natural alignment for the type.
  1924. if (OldAlign == 0 || NewAlign == 0) {
  1925. QualType Ty;
  1926. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  1927. Ty = VD->getType();
  1928. else
  1929. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  1930. if (OldAlign == 0)
  1931. OldAlign = S.Context.getTypeAlign(Ty);
  1932. if (NewAlign == 0)
  1933. NewAlign = S.Context.getTypeAlign(Ty);
  1934. }
  1935. if (OldAlign != NewAlign) {
  1936. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  1937. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  1938. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  1939. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  1940. }
  1941. }
  1942. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  1943. // C++11 [dcl.align]p6:
  1944. // if any declaration of an entity has an alignment-specifier,
  1945. // every defining declaration of that entity shall specify an
  1946. // equivalent alignment.
  1947. // C11 6.7.5/7:
  1948. // If the definition of an object does not have an alignment
  1949. // specifier, any other declaration of that object shall also
  1950. // have no alignment specifier.
  1951. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  1952. << OldAlignasAttr;
  1953. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  1954. << OldAlignasAttr;
  1955. }
  1956. bool AnyAdded = false;
  1957. // Ensure we have an attribute representing the strictest alignment.
  1958. if (OldAlign > NewAlign) {
  1959. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  1960. Clone->setInherited(true);
  1961. New->addAttr(Clone);
  1962. AnyAdded = true;
  1963. }
  1964. // Ensure we have an alignas attribute if the old declaration had one.
  1965. if (OldAlignasAttr && !NewAlignasAttr &&
  1966. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  1967. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  1968. Clone->setInherited(true);
  1969. New->addAttr(Clone);
  1970. AnyAdded = true;
  1971. }
  1972. return AnyAdded;
  1973. }
  1974. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  1975. const InheritableAttr *Attr,
  1976. Sema::AvailabilityMergeKind AMK) {
  1977. // This function copies an attribute Attr from a previous declaration to the
  1978. // new declaration D if the new declaration doesn't itself have that attribute
  1979. // yet or if that attribute allows duplicates.
  1980. // If you're adding a new attribute that requires logic different from
  1981. // "use explicit attribute on decl if present, else use attribute from
  1982. // previous decl", for example if the attribute needs to be consistent
  1983. // between redeclarations, you need to call a custom merge function here.
  1984. InheritableAttr *NewAttr = nullptr;
  1985. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  1986. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  1987. NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
  1988. AA->isImplicit(), AA->getIntroduced(),
  1989. AA->getDeprecated(),
  1990. AA->getObsoleted(), AA->getUnavailable(),
  1991. AA->getMessage(), AA->getStrict(),
  1992. AA->getReplacement(), AMK,
  1993. AttrSpellingListIndex);
  1994. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  1995. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  1996. AttrSpellingListIndex);
  1997. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  1998. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  1999. AttrSpellingListIndex);
  2000. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2001. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  2002. AttrSpellingListIndex);
  2003. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2004. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  2005. AttrSpellingListIndex);
  2006. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2007. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  2008. FA->getFormatIdx(), FA->getFirstArg(),
  2009. AttrSpellingListIndex);
  2010. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2011. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  2012. AttrSpellingListIndex);
  2013. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2014. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  2015. AttrSpellingListIndex,
  2016. IA->getSemanticSpelling());
  2017. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2018. NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
  2019. &S.Context.Idents.get(AA->getSpelling()),
  2020. AttrSpellingListIndex);
  2021. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2022. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2023. isa<CUDAGlobalAttr>(Attr))) {
  2024. // CUDA target attributes are part of function signature for
  2025. // overloading purposes and must not be merged.
  2026. return false;
  2027. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2028. NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
  2029. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2030. NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
  2031. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2032. NewAttr = S.mergeInternalLinkageAttr(
  2033. D, InternalLinkageA->getRange(),
  2034. &S.Context.Idents.get(InternalLinkageA->getSpelling()),
  2035. AttrSpellingListIndex);
  2036. else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
  2037. NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
  2038. &S.Context.Idents.get(CommonA->getSpelling()),
  2039. AttrSpellingListIndex);
  2040. else if (isa<AlignedAttr>(Attr))
  2041. // AlignedAttrs are handled separately, because we need to handle all
  2042. // such attributes on a declaration at the same time.
  2043. NewAttr = nullptr;
  2044. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2045. (AMK == Sema::AMK_Override ||
  2046. AMK == Sema::AMK_ProtocolImplementation))
  2047. NewAttr = nullptr;
  2048. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2049. NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
  2050. UA->getGuid());
  2051. else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
  2052. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2053. if (NewAttr) {
  2054. NewAttr->setInherited(true);
  2055. D->addAttr(NewAttr);
  2056. if (isa<MSInheritanceAttr>(NewAttr))
  2057. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2058. return true;
  2059. }
  2060. return false;
  2061. }
  2062. static const Decl *getDefinition(const Decl *D) {
  2063. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2064. return TD->getDefinition();
  2065. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2066. const VarDecl *Def = VD->getDefinition();
  2067. if (Def)
  2068. return Def;
  2069. return VD->getActingDefinition();
  2070. }
  2071. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2072. return FD->getDefinition();
  2073. return nullptr;
  2074. }
  2075. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2076. for (const auto *Attribute : D->attrs())
  2077. if (Attribute->getKind() == Kind)
  2078. return true;
  2079. return false;
  2080. }
  2081. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2082. /// there are no new attributes in this declaration.
  2083. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2084. if (!New->hasAttrs())
  2085. return;
  2086. const Decl *Def = getDefinition(Old);
  2087. if (!Def || Def == New)
  2088. return;
  2089. AttrVec &NewAttributes = New->getAttrs();
  2090. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2091. const Attr *NewAttribute = NewAttributes[I];
  2092. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2093. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2094. Sema::SkipBodyInfo SkipBody;
  2095. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2096. // If we're skipping this definition, drop the "alias" attribute.
  2097. if (SkipBody.ShouldSkip) {
  2098. NewAttributes.erase(NewAttributes.begin() + I);
  2099. --E;
  2100. continue;
  2101. }
  2102. } else {
  2103. VarDecl *VD = cast<VarDecl>(New);
  2104. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2105. VarDecl::TentativeDefinition
  2106. ? diag::err_alias_after_tentative
  2107. : diag::err_redefinition;
  2108. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2109. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2110. VD->setInvalidDecl();
  2111. }
  2112. ++I;
  2113. continue;
  2114. }
  2115. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2116. // Tentative definitions are only interesting for the alias check above.
  2117. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2118. ++I;
  2119. continue;
  2120. }
  2121. }
  2122. if (hasAttribute(Def, NewAttribute->getKind())) {
  2123. ++I;
  2124. continue; // regular attr merging will take care of validating this.
  2125. }
  2126. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2127. // C's _Noreturn is allowed to be added to a function after it is defined.
  2128. ++I;
  2129. continue;
  2130. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2131. if (AA->isAlignas()) {
  2132. // C++11 [dcl.align]p6:
  2133. // if any declaration of an entity has an alignment-specifier,
  2134. // every defining declaration of that entity shall specify an
  2135. // equivalent alignment.
  2136. // C11 6.7.5/7:
  2137. // If the definition of an object does not have an alignment
  2138. // specifier, any other declaration of that object shall also
  2139. // have no alignment specifier.
  2140. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2141. << AA;
  2142. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2143. << AA;
  2144. NewAttributes.erase(NewAttributes.begin() + I);
  2145. --E;
  2146. continue;
  2147. }
  2148. }
  2149. S.Diag(NewAttribute->getLocation(),
  2150. diag::warn_attribute_precede_definition);
  2151. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2152. NewAttributes.erase(NewAttributes.begin() + I);
  2153. --E;
  2154. }
  2155. }
  2156. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2157. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2158. AvailabilityMergeKind AMK) {
  2159. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2160. UsedAttr *NewAttr = OldAttr->clone(Context);
  2161. NewAttr->setInherited(true);
  2162. New->addAttr(NewAttr);
  2163. }
  2164. if (!Old->hasAttrs() && !New->hasAttrs())
  2165. return;
  2166. // Attributes declared post-definition are currently ignored.
  2167. checkNewAttributesAfterDef(*this, New, Old);
  2168. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2169. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2170. if (OldA->getLabel() != NewA->getLabel()) {
  2171. // This redeclaration changes __asm__ label.
  2172. Diag(New->getLocation(), diag::err_different_asm_label);
  2173. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2174. }
  2175. } else if (Old->isUsed()) {
  2176. // This redeclaration adds an __asm__ label to a declaration that has
  2177. // already been ODR-used.
  2178. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2179. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2180. }
  2181. }
  2182. // Re-declaration cannot add abi_tag's.
  2183. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2184. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2185. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2186. if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
  2187. NewTag) == OldAbiTagAttr->tags_end()) {
  2188. Diag(NewAbiTagAttr->getLocation(),
  2189. diag::err_new_abi_tag_on_redeclaration)
  2190. << NewTag;
  2191. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2192. }
  2193. }
  2194. } else {
  2195. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2196. Diag(Old->getLocation(), diag::note_previous_declaration);
  2197. }
  2198. }
  2199. if (!Old->hasAttrs())
  2200. return;
  2201. bool foundAny = New->hasAttrs();
  2202. // Ensure that any moving of objects within the allocated map is done before
  2203. // we process them.
  2204. if (!foundAny) New->setAttrs(AttrVec());
  2205. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2206. // Ignore deprecated/unavailable/availability attributes if requested.
  2207. AvailabilityMergeKind LocalAMK = AMK_None;
  2208. if (isa<DeprecatedAttr>(I) ||
  2209. isa<UnavailableAttr>(I) ||
  2210. isa<AvailabilityAttr>(I)) {
  2211. switch (AMK) {
  2212. case AMK_None:
  2213. continue;
  2214. case AMK_Redeclaration:
  2215. case AMK_Override:
  2216. case AMK_ProtocolImplementation:
  2217. LocalAMK = AMK;
  2218. break;
  2219. }
  2220. }
  2221. // Already handled.
  2222. if (isa<UsedAttr>(I))
  2223. continue;
  2224. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2225. foundAny = true;
  2226. }
  2227. if (mergeAlignedAttrs(*this, New, Old))
  2228. foundAny = true;
  2229. if (!foundAny) New->dropAttrs();
  2230. }
  2231. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2232. /// to the new one.
  2233. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2234. const ParmVarDecl *oldDecl,
  2235. Sema &S) {
  2236. // C++11 [dcl.attr.depend]p2:
  2237. // The first declaration of a function shall specify the
  2238. // carries_dependency attribute for its declarator-id if any declaration
  2239. // of the function specifies the carries_dependency attribute.
  2240. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2241. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2242. S.Diag(CDA->getLocation(),
  2243. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2244. // Find the first declaration of the parameter.
  2245. // FIXME: Should we build redeclaration chains for function parameters?
  2246. const FunctionDecl *FirstFD =
  2247. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2248. const ParmVarDecl *FirstVD =
  2249. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2250. S.Diag(FirstVD->getLocation(),
  2251. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2252. }
  2253. if (!oldDecl->hasAttrs())
  2254. return;
  2255. bool foundAny = newDecl->hasAttrs();
  2256. // Ensure that any moving of objects within the allocated map is
  2257. // done before we process them.
  2258. if (!foundAny) newDecl->setAttrs(AttrVec());
  2259. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2260. if (!DeclHasAttr(newDecl, I)) {
  2261. InheritableAttr *newAttr =
  2262. cast<InheritableParamAttr>(I->clone(S.Context));
  2263. newAttr->setInherited(true);
  2264. newDecl->addAttr(newAttr);
  2265. foundAny = true;
  2266. }
  2267. }
  2268. if (!foundAny) newDecl->dropAttrs();
  2269. }
  2270. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2271. const ParmVarDecl *OldParam,
  2272. Sema &S) {
  2273. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2274. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2275. if (*Oldnullability != *Newnullability) {
  2276. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2277. << DiagNullabilityKind(
  2278. *Newnullability,
  2279. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2280. != 0))
  2281. << DiagNullabilityKind(
  2282. *Oldnullability,
  2283. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2284. != 0));
  2285. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2286. }
  2287. } else {
  2288. QualType NewT = NewParam->getType();
  2289. NewT = S.Context.getAttributedType(
  2290. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2291. NewT, NewT);
  2292. NewParam->setType(NewT);
  2293. }
  2294. }
  2295. }
  2296. namespace {
  2297. /// Used in MergeFunctionDecl to keep track of function parameters in
  2298. /// C.
  2299. struct GNUCompatibleParamWarning {
  2300. ParmVarDecl *OldParm;
  2301. ParmVarDecl *NewParm;
  2302. QualType PromotedType;
  2303. };
  2304. } // end anonymous namespace
  2305. /// getSpecialMember - get the special member enum for a method.
  2306. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2307. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2308. if (Ctor->isDefaultConstructor())
  2309. return Sema::CXXDefaultConstructor;
  2310. if (Ctor->isCopyConstructor())
  2311. return Sema::CXXCopyConstructor;
  2312. if (Ctor->isMoveConstructor())
  2313. return Sema::CXXMoveConstructor;
  2314. } else if (isa<CXXDestructorDecl>(MD)) {
  2315. return Sema::CXXDestructor;
  2316. } else if (MD->isCopyAssignmentOperator()) {
  2317. return Sema::CXXCopyAssignment;
  2318. } else if (MD->isMoveAssignmentOperator()) {
  2319. return Sema::CXXMoveAssignment;
  2320. }
  2321. return Sema::CXXInvalid;
  2322. }
  2323. // Determine whether the previous declaration was a definition, implicit
  2324. // declaration, or a declaration.
  2325. template <typename T>
  2326. static std::pair<diag::kind, SourceLocation>
  2327. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2328. diag::kind PrevDiag;
  2329. SourceLocation OldLocation = Old->getLocation();
  2330. if (Old->isThisDeclarationADefinition())
  2331. PrevDiag = diag::note_previous_definition;
  2332. else if (Old->isImplicit()) {
  2333. PrevDiag = diag::note_previous_implicit_declaration;
  2334. if (OldLocation.isInvalid())
  2335. OldLocation = New->getLocation();
  2336. } else
  2337. PrevDiag = diag::note_previous_declaration;
  2338. return std::make_pair(PrevDiag, OldLocation);
  2339. }
  2340. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2341. /// only extern inline functions can be redefined, and even then only in
  2342. /// GNU89 mode.
  2343. static bool canRedefineFunction(const FunctionDecl *FD,
  2344. const LangOptions& LangOpts) {
  2345. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2346. !LangOpts.CPlusPlus &&
  2347. FD->isInlineSpecified() &&
  2348. FD->getStorageClass() == SC_Extern);
  2349. }
  2350. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2351. const AttributedType *AT = T->getAs<AttributedType>();
  2352. while (AT && !AT->isCallingConv())
  2353. AT = AT->getModifiedType()->getAs<AttributedType>();
  2354. return AT;
  2355. }
  2356. template <typename T>
  2357. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2358. const DeclContext *DC = Old->getDeclContext();
  2359. if (DC->isRecord())
  2360. return false;
  2361. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2362. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2363. return true;
  2364. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2365. return true;
  2366. return false;
  2367. }
  2368. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2369. static bool isExternC(VarTemplateDecl *) { return false; }
  2370. /// \brief Check whether a redeclaration of an entity introduced by a
  2371. /// using-declaration is valid, given that we know it's not an overload
  2372. /// (nor a hidden tag declaration).
  2373. template<typename ExpectedDecl>
  2374. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2375. ExpectedDecl *New) {
  2376. // C++11 [basic.scope.declarative]p4:
  2377. // Given a set of declarations in a single declarative region, each of
  2378. // which specifies the same unqualified name,
  2379. // -- they shall all refer to the same entity, or all refer to functions
  2380. // and function templates; or
  2381. // -- exactly one declaration shall declare a class name or enumeration
  2382. // name that is not a typedef name and the other declarations shall all
  2383. // refer to the same variable or enumerator, or all refer to functions
  2384. // and function templates; in this case the class name or enumeration
  2385. // name is hidden (3.3.10).
  2386. // C++11 [namespace.udecl]p14:
  2387. // If a function declaration in namespace scope or block scope has the
  2388. // same name and the same parameter-type-list as a function introduced
  2389. // by a using-declaration, and the declarations do not declare the same
  2390. // function, the program is ill-formed.
  2391. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2392. if (Old &&
  2393. !Old->getDeclContext()->getRedeclContext()->Equals(
  2394. New->getDeclContext()->getRedeclContext()) &&
  2395. !(isExternC(Old) && isExternC(New)))
  2396. Old = nullptr;
  2397. if (!Old) {
  2398. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2399. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2400. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2401. return true;
  2402. }
  2403. return false;
  2404. }
  2405. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2406. const FunctionDecl *B) {
  2407. assert(A->getNumParams() == B->getNumParams());
  2408. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2409. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2410. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2411. if (AttrA == AttrB)
  2412. return true;
  2413. return AttrA && AttrB && AttrA->getType() == AttrB->getType();
  2414. };
  2415. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2416. }
  2417. /// MergeFunctionDecl - We just parsed a function 'New' from
  2418. /// declarator D which has the same name and scope as a previous
  2419. /// declaration 'Old'. Figure out how to resolve this situation,
  2420. /// merging decls or emitting diagnostics as appropriate.
  2421. ///
  2422. /// In C++, New and Old must be declarations that are not
  2423. /// overloaded. Use IsOverload to determine whether New and Old are
  2424. /// overloaded, and to select the Old declaration that New should be
  2425. /// merged with.
  2426. ///
  2427. /// Returns true if there was an error, false otherwise.
  2428. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2429. Scope *S, bool MergeTypeWithOld) {
  2430. // Verify the old decl was also a function.
  2431. FunctionDecl *Old = OldD->getAsFunction();
  2432. if (!Old) {
  2433. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2434. if (New->getFriendObjectKind()) {
  2435. Diag(New->getLocation(), diag::err_using_decl_friend);
  2436. Diag(Shadow->getTargetDecl()->getLocation(),
  2437. diag::note_using_decl_target);
  2438. Diag(Shadow->getUsingDecl()->getLocation(),
  2439. diag::note_using_decl) << 0;
  2440. return true;
  2441. }
  2442. // Check whether the two declarations might declare the same function.
  2443. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2444. return true;
  2445. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2446. } else {
  2447. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2448. << New->getDeclName();
  2449. Diag(OldD->getLocation(), diag::note_previous_definition);
  2450. return true;
  2451. }
  2452. }
  2453. // If the old declaration is invalid, just give up here.
  2454. if (Old->isInvalidDecl())
  2455. return true;
  2456. diag::kind PrevDiag;
  2457. SourceLocation OldLocation;
  2458. std::tie(PrevDiag, OldLocation) =
  2459. getNoteDiagForInvalidRedeclaration(Old, New);
  2460. // Don't complain about this if we're in GNU89 mode and the old function
  2461. // is an extern inline function.
  2462. // Don't complain about specializations. They are not supposed to have
  2463. // storage classes.
  2464. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2465. New->getStorageClass() == SC_Static &&
  2466. Old->hasExternalFormalLinkage() &&
  2467. !New->getTemplateSpecializationInfo() &&
  2468. !canRedefineFunction(Old, getLangOpts())) {
  2469. if (getLangOpts().MicrosoftExt) {
  2470. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2471. Diag(OldLocation, PrevDiag);
  2472. } else {
  2473. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2474. Diag(OldLocation, PrevDiag);
  2475. return true;
  2476. }
  2477. }
  2478. if (New->hasAttr<InternalLinkageAttr>() &&
  2479. !Old->hasAttr<InternalLinkageAttr>()) {
  2480. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  2481. << New->getDeclName();
  2482. Diag(Old->getLocation(), diag::note_previous_definition);
  2483. New->dropAttr<InternalLinkageAttr>();
  2484. }
  2485. // If a function is first declared with a calling convention, but is later
  2486. // declared or defined without one, all following decls assume the calling
  2487. // convention of the first.
  2488. //
  2489. // It's OK if a function is first declared without a calling convention,
  2490. // but is later declared or defined with the default calling convention.
  2491. //
  2492. // To test if either decl has an explicit calling convention, we look for
  2493. // AttributedType sugar nodes on the type as written. If they are missing or
  2494. // were canonicalized away, we assume the calling convention was implicit.
  2495. //
  2496. // Note also that we DO NOT return at this point, because we still have
  2497. // other tests to run.
  2498. QualType OldQType = Context.getCanonicalType(Old->getType());
  2499. QualType NewQType = Context.getCanonicalType(New->getType());
  2500. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2501. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2502. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2503. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2504. bool RequiresAdjustment = false;
  2505. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2506. FunctionDecl *First = Old->getFirstDecl();
  2507. const FunctionType *FT =
  2508. First->getType().getCanonicalType()->castAs<FunctionType>();
  2509. FunctionType::ExtInfo FI = FT->getExtInfo();
  2510. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2511. if (!NewCCExplicit) {
  2512. // Inherit the CC from the previous declaration if it was specified
  2513. // there but not here.
  2514. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2515. RequiresAdjustment = true;
  2516. } else {
  2517. // Calling conventions aren't compatible, so complain.
  2518. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2519. Diag(New->getLocation(), diag::err_cconv_change)
  2520. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2521. << !FirstCCExplicit
  2522. << (!FirstCCExplicit ? "" :
  2523. FunctionType::getNameForCallConv(FI.getCC()));
  2524. // Put the note on the first decl, since it is the one that matters.
  2525. Diag(First->getLocation(), diag::note_previous_declaration);
  2526. return true;
  2527. }
  2528. }
  2529. // FIXME: diagnose the other way around?
  2530. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2531. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2532. RequiresAdjustment = true;
  2533. }
  2534. // Merge regparm attribute.
  2535. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2536. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2537. if (NewTypeInfo.getHasRegParm()) {
  2538. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2539. << NewType->getRegParmType()
  2540. << OldType->getRegParmType();
  2541. Diag(OldLocation, diag::note_previous_declaration);
  2542. return true;
  2543. }
  2544. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2545. RequiresAdjustment = true;
  2546. }
  2547. // Merge ns_returns_retained attribute.
  2548. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2549. if (NewTypeInfo.getProducesResult()) {
  2550. Diag(New->getLocation(), diag::err_returns_retained_mismatch);
  2551. Diag(OldLocation, diag::note_previous_declaration);
  2552. return true;
  2553. }
  2554. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2555. RequiresAdjustment = true;
  2556. }
  2557. if (RequiresAdjustment) {
  2558. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2559. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2560. New->setType(QualType(AdjustedType, 0));
  2561. NewQType = Context.getCanonicalType(New->getType());
  2562. NewType = cast<FunctionType>(NewQType);
  2563. }
  2564. // If this redeclaration makes the function inline, we may need to add it to
  2565. // UndefinedButUsed.
  2566. if (!Old->isInlined() && New->isInlined() &&
  2567. !New->hasAttr<GNUInlineAttr>() &&
  2568. !getLangOpts().GNUInline &&
  2569. Old->isUsed(false) &&
  2570. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2571. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2572. SourceLocation()));
  2573. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2574. // about it.
  2575. if (New->hasAttr<GNUInlineAttr>() &&
  2576. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2577. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2578. }
  2579. // If pass_object_size params don't match up perfectly, this isn't a valid
  2580. // redeclaration.
  2581. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  2582. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  2583. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  2584. << New->getDeclName();
  2585. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2586. return true;
  2587. }
  2588. if (getLangOpts().CPlusPlus) {
  2589. // C++1z [over.load]p2
  2590. // Certain function declarations cannot be overloaded:
  2591. // -- Function declarations that differ only in the return type,
  2592. // the exception specification, or both cannot be overloaded.
  2593. // Check the exception specifications match. This may recompute the type of
  2594. // both Old and New if it resolved exception specifications, so grab the
  2595. // types again after this. Because this updates the type, we do this before
  2596. // any of the other checks below, which may update the "de facto" NewQType
  2597. // but do not necessarily update the type of New.
  2598. if (CheckEquivalentExceptionSpec(Old, New))
  2599. return true;
  2600. OldQType = Context.getCanonicalType(Old->getType());
  2601. NewQType = Context.getCanonicalType(New->getType());
  2602. // Go back to the type source info to compare the declared return types,
  2603. // per C++1y [dcl.type.auto]p13:
  2604. // Redeclarations or specializations of a function or function template
  2605. // with a declared return type that uses a placeholder type shall also
  2606. // use that placeholder, not a deduced type.
  2607. QualType OldDeclaredReturnType =
  2608. (Old->getTypeSourceInfo()
  2609. ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2610. : OldType)->getReturnType();
  2611. QualType NewDeclaredReturnType =
  2612. (New->getTypeSourceInfo()
  2613. ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2614. : NewType)->getReturnType();
  2615. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  2616. !((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2617. New->isLocalExternDecl())) {
  2618. QualType ResQT;
  2619. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  2620. OldDeclaredReturnType->isObjCObjectPointerType())
  2621. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  2622. if (ResQT.isNull()) {
  2623. if (New->isCXXClassMember() && New->isOutOfLine())
  2624. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  2625. << New << New->getReturnTypeSourceRange();
  2626. else
  2627. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  2628. << New->getReturnTypeSourceRange();
  2629. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  2630. << Old->getReturnTypeSourceRange();
  2631. return true;
  2632. }
  2633. else
  2634. NewQType = ResQT;
  2635. }
  2636. QualType OldReturnType = OldType->getReturnType();
  2637. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  2638. if (OldReturnType != NewReturnType) {
  2639. // If this function has a deduced return type and has already been
  2640. // defined, copy the deduced value from the old declaration.
  2641. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  2642. if (OldAT && OldAT->isDeduced()) {
  2643. New->setType(
  2644. SubstAutoType(New->getType(),
  2645. OldAT->isDependentType() ? Context.DependentTy
  2646. : OldAT->getDeducedType()));
  2647. NewQType = Context.getCanonicalType(
  2648. SubstAutoType(NewQType,
  2649. OldAT->isDependentType() ? Context.DependentTy
  2650. : OldAT->getDeducedType()));
  2651. }
  2652. }
  2653. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  2654. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  2655. if (OldMethod && NewMethod) {
  2656. // Preserve triviality.
  2657. NewMethod->setTrivial(OldMethod->isTrivial());
  2658. // MSVC allows explicit template specialization at class scope:
  2659. // 2 CXXMethodDecls referring to the same function will be injected.
  2660. // We don't want a redeclaration error.
  2661. bool IsClassScopeExplicitSpecialization =
  2662. OldMethod->isFunctionTemplateSpecialization() &&
  2663. NewMethod->isFunctionTemplateSpecialization();
  2664. bool isFriend = NewMethod->getFriendObjectKind();
  2665. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  2666. !IsClassScopeExplicitSpecialization) {
  2667. // -- Member function declarations with the same name and the
  2668. // same parameter types cannot be overloaded if any of them
  2669. // is a static member function declaration.
  2670. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  2671. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  2672. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2673. return true;
  2674. }
  2675. // C++ [class.mem]p1:
  2676. // [...] A member shall not be declared twice in the
  2677. // member-specification, except that a nested class or member
  2678. // class template can be declared and then later defined.
  2679. if (ActiveTemplateInstantiations.empty()) {
  2680. unsigned NewDiag;
  2681. if (isa<CXXConstructorDecl>(OldMethod))
  2682. NewDiag = diag::err_constructor_redeclared;
  2683. else if (isa<CXXDestructorDecl>(NewMethod))
  2684. NewDiag = diag::err_destructor_redeclared;
  2685. else if (isa<CXXConversionDecl>(NewMethod))
  2686. NewDiag = diag::err_conv_function_redeclared;
  2687. else
  2688. NewDiag = diag::err_member_redeclared;
  2689. Diag(New->getLocation(), NewDiag);
  2690. } else {
  2691. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2692. << New << New->getType();
  2693. }
  2694. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2695. return true;
  2696. // Complain if this is an explicit declaration of a special
  2697. // member that was initially declared implicitly.
  2698. //
  2699. // As an exception, it's okay to befriend such methods in order
  2700. // to permit the implicit constructor/destructor/operator calls.
  2701. } else if (OldMethod->isImplicit()) {
  2702. if (isFriend) {
  2703. NewMethod->setImplicit();
  2704. } else {
  2705. Diag(NewMethod->getLocation(),
  2706. diag::err_definition_of_implicitly_declared_member)
  2707. << New << getSpecialMember(OldMethod);
  2708. return true;
  2709. }
  2710. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  2711. Diag(NewMethod->getLocation(),
  2712. diag::err_definition_of_explicitly_defaulted_member)
  2713. << getSpecialMember(OldMethod);
  2714. return true;
  2715. }
  2716. }
  2717. // C++11 [dcl.attr.noreturn]p1:
  2718. // The first declaration of a function shall specify the noreturn
  2719. // attribute if any declaration of that function specifies the noreturn
  2720. // attribute.
  2721. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  2722. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  2723. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  2724. Diag(Old->getFirstDecl()->getLocation(),
  2725. diag::note_noreturn_missing_first_decl);
  2726. }
  2727. // C++11 [dcl.attr.depend]p2:
  2728. // The first declaration of a function shall specify the
  2729. // carries_dependency attribute for its declarator-id if any declaration
  2730. // of the function specifies the carries_dependency attribute.
  2731. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  2732. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  2733. Diag(CDA->getLocation(),
  2734. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  2735. Diag(Old->getFirstDecl()->getLocation(),
  2736. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  2737. }
  2738. // (C++98 8.3.5p3):
  2739. // All declarations for a function shall agree exactly in both the
  2740. // return type and the parameter-type-list.
  2741. // We also want to respect all the extended bits except noreturn.
  2742. // noreturn should now match unless the old type info didn't have it.
  2743. QualType OldQTypeForComparison = OldQType;
  2744. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  2745. auto *OldType = OldQType->castAs<FunctionProtoType>();
  2746. const FunctionType *OldTypeForComparison
  2747. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  2748. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  2749. assert(OldQTypeForComparison.isCanonical());
  2750. }
  2751. if (haveIncompatibleLanguageLinkages(Old, New)) {
  2752. // As a special case, retain the language linkage from previous
  2753. // declarations of a friend function as an extension.
  2754. //
  2755. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  2756. // and is useful because there's otherwise no way to specify language
  2757. // linkage within class scope.
  2758. //
  2759. // Check cautiously as the friend object kind isn't yet complete.
  2760. if (New->getFriendObjectKind() != Decl::FOK_None) {
  2761. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  2762. Diag(OldLocation, PrevDiag);
  2763. } else {
  2764. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  2765. Diag(OldLocation, PrevDiag);
  2766. return true;
  2767. }
  2768. }
  2769. if (OldQTypeForComparison == NewQType)
  2770. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2771. if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2772. New->isLocalExternDecl()) {
  2773. // It's OK if we couldn't merge types for a local function declaraton
  2774. // if either the old or new type is dependent. We'll merge the types
  2775. // when we instantiate the function.
  2776. return false;
  2777. }
  2778. // Fall through for conflicting redeclarations and redefinitions.
  2779. }
  2780. // C: Function types need to be compatible, not identical. This handles
  2781. // duplicate function decls like "void f(int); void f(enum X);" properly.
  2782. if (!getLangOpts().CPlusPlus &&
  2783. Context.typesAreCompatible(OldQType, NewQType)) {
  2784. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  2785. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  2786. const FunctionProtoType *OldProto = nullptr;
  2787. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  2788. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  2789. // The old declaration provided a function prototype, but the
  2790. // new declaration does not. Merge in the prototype.
  2791. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  2792. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  2793. NewQType =
  2794. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  2795. OldProto->getExtProtoInfo());
  2796. New->setType(NewQType);
  2797. New->setHasInheritedPrototype();
  2798. // Synthesize parameters with the same types.
  2799. SmallVector<ParmVarDecl*, 16> Params;
  2800. for (const auto &ParamType : OldProto->param_types()) {
  2801. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  2802. SourceLocation(), nullptr,
  2803. ParamType, /*TInfo=*/nullptr,
  2804. SC_None, nullptr);
  2805. Param->setScopeInfo(0, Params.size());
  2806. Param->setImplicit();
  2807. Params.push_back(Param);
  2808. }
  2809. New->setParams(Params);
  2810. }
  2811. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2812. }
  2813. // GNU C permits a K&R definition to follow a prototype declaration
  2814. // if the declared types of the parameters in the K&R definition
  2815. // match the types in the prototype declaration, even when the
  2816. // promoted types of the parameters from the K&R definition differ
  2817. // from the types in the prototype. GCC then keeps the types from
  2818. // the prototype.
  2819. //
  2820. // If a variadic prototype is followed by a non-variadic K&R definition,
  2821. // the K&R definition becomes variadic. This is sort of an edge case, but
  2822. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  2823. // C99 6.9.1p8.
  2824. if (!getLangOpts().CPlusPlus &&
  2825. Old->hasPrototype() && !New->hasPrototype() &&
  2826. New->getType()->getAs<FunctionProtoType>() &&
  2827. Old->getNumParams() == New->getNumParams()) {
  2828. SmallVector<QualType, 16> ArgTypes;
  2829. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  2830. const FunctionProtoType *OldProto
  2831. = Old->getType()->getAs<FunctionProtoType>();
  2832. const FunctionProtoType *NewProto
  2833. = New->getType()->getAs<FunctionProtoType>();
  2834. // Determine whether this is the GNU C extension.
  2835. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  2836. NewProto->getReturnType());
  2837. bool LooseCompatible = !MergedReturn.isNull();
  2838. for (unsigned Idx = 0, End = Old->getNumParams();
  2839. LooseCompatible && Idx != End; ++Idx) {
  2840. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  2841. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  2842. if (Context.typesAreCompatible(OldParm->getType(),
  2843. NewProto->getParamType(Idx))) {
  2844. ArgTypes.push_back(NewParm->getType());
  2845. } else if (Context.typesAreCompatible(OldParm->getType(),
  2846. NewParm->getType(),
  2847. /*CompareUnqualified=*/true)) {
  2848. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  2849. NewProto->getParamType(Idx) };
  2850. Warnings.push_back(Warn);
  2851. ArgTypes.push_back(NewParm->getType());
  2852. } else
  2853. LooseCompatible = false;
  2854. }
  2855. if (LooseCompatible) {
  2856. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  2857. Diag(Warnings[Warn].NewParm->getLocation(),
  2858. diag::ext_param_promoted_not_compatible_with_prototype)
  2859. << Warnings[Warn].PromotedType
  2860. << Warnings[Warn].OldParm->getType();
  2861. if (Warnings[Warn].OldParm->getLocation().isValid())
  2862. Diag(Warnings[Warn].OldParm->getLocation(),
  2863. diag::note_previous_declaration);
  2864. }
  2865. if (MergeTypeWithOld)
  2866. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  2867. OldProto->getExtProtoInfo()));
  2868. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2869. }
  2870. // Fall through to diagnose conflicting types.
  2871. }
  2872. // A function that has already been declared has been redeclared or
  2873. // defined with a different type; show an appropriate diagnostic.
  2874. // If the previous declaration was an implicitly-generated builtin
  2875. // declaration, then at the very least we should use a specialized note.
  2876. unsigned BuiltinID;
  2877. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  2878. // If it's actually a library-defined builtin function like 'malloc'
  2879. // or 'printf', just warn about the incompatible redeclaration.
  2880. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  2881. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  2882. Diag(OldLocation, diag::note_previous_builtin_declaration)
  2883. << Old << Old->getType();
  2884. // If this is a global redeclaration, just forget hereafter
  2885. // about the "builtin-ness" of the function.
  2886. //
  2887. // Doing this for local extern declarations is problematic. If
  2888. // the builtin declaration remains visible, a second invalid
  2889. // local declaration will produce a hard error; if it doesn't
  2890. // remain visible, a single bogus local redeclaration (which is
  2891. // actually only a warning) could break all the downstream code.
  2892. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  2893. New->getIdentifier()->revertBuiltin();
  2894. return false;
  2895. }
  2896. PrevDiag = diag::note_previous_builtin_declaration;
  2897. }
  2898. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  2899. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2900. return true;
  2901. }
  2902. /// \brief Completes the merge of two function declarations that are
  2903. /// known to be compatible.
  2904. ///
  2905. /// This routine handles the merging of attributes and other
  2906. /// properties of function declarations from the old declaration to
  2907. /// the new declaration, once we know that New is in fact a
  2908. /// redeclaration of Old.
  2909. ///
  2910. /// \returns false
  2911. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  2912. Scope *S, bool MergeTypeWithOld) {
  2913. // Merge the attributes
  2914. mergeDeclAttributes(New, Old);
  2915. // Merge "pure" flag.
  2916. if (Old->isPure())
  2917. New->setPure();
  2918. // Merge "used" flag.
  2919. if (Old->getMostRecentDecl()->isUsed(false))
  2920. New->setIsUsed();
  2921. // Merge attributes from the parameters. These can mismatch with K&R
  2922. // declarations.
  2923. if (New->getNumParams() == Old->getNumParams())
  2924. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  2925. ParmVarDecl *NewParam = New->getParamDecl(i);
  2926. ParmVarDecl *OldParam = Old->getParamDecl(i);
  2927. mergeParamDeclAttributes(NewParam, OldParam, *this);
  2928. mergeParamDeclTypes(NewParam, OldParam, *this);
  2929. }
  2930. if (getLangOpts().CPlusPlus)
  2931. return MergeCXXFunctionDecl(New, Old, S);
  2932. // Merge the function types so the we get the composite types for the return
  2933. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  2934. // was visible.
  2935. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  2936. if (!Merged.isNull() && MergeTypeWithOld)
  2937. New->setType(Merged);
  2938. return false;
  2939. }
  2940. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  2941. ObjCMethodDecl *oldMethod) {
  2942. // Merge the attributes, including deprecated/unavailable
  2943. AvailabilityMergeKind MergeKind =
  2944. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  2945. ? AMK_ProtocolImplementation
  2946. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  2947. : AMK_Override;
  2948. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  2949. // Merge attributes from the parameters.
  2950. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  2951. oe = oldMethod->param_end();
  2952. for (ObjCMethodDecl::param_iterator
  2953. ni = newMethod->param_begin(), ne = newMethod->param_end();
  2954. ni != ne && oi != oe; ++ni, ++oi)
  2955. mergeParamDeclAttributes(*ni, *oi, *this);
  2956. CheckObjCMethodOverride(newMethod, oldMethod);
  2957. }
  2958. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  2959. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  2960. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  2961. ? diag::err_redefinition_different_type
  2962. : diag::err_redeclaration_different_type)
  2963. << New->getDeclName() << New->getType() << Old->getType();
  2964. diag::kind PrevDiag;
  2965. SourceLocation OldLocation;
  2966. std::tie(PrevDiag, OldLocation)
  2967. = getNoteDiagForInvalidRedeclaration(Old, New);
  2968. S.Diag(OldLocation, PrevDiag);
  2969. New->setInvalidDecl();
  2970. }
  2971. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  2972. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  2973. /// emitting diagnostics as appropriate.
  2974. ///
  2975. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  2976. /// to here in AddInitializerToDecl. We can't check them before the initializer
  2977. /// is attached.
  2978. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  2979. bool MergeTypeWithOld) {
  2980. if (New->isInvalidDecl() || Old->isInvalidDecl())
  2981. return;
  2982. QualType MergedT;
  2983. if (getLangOpts().CPlusPlus) {
  2984. if (New->getType()->isUndeducedType()) {
  2985. // We don't know what the new type is until the initializer is attached.
  2986. return;
  2987. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  2988. // These could still be something that needs exception specs checked.
  2989. return MergeVarDeclExceptionSpecs(New, Old);
  2990. }
  2991. // C++ [basic.link]p10:
  2992. // [...] the types specified by all declarations referring to a given
  2993. // object or function shall be identical, except that declarations for an
  2994. // array object can specify array types that differ by the presence or
  2995. // absence of a major array bound (8.3.4).
  2996. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  2997. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  2998. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  2999. // We are merging a variable declaration New into Old. If it has an array
  3000. // bound, and that bound differs from Old's bound, we should diagnose the
  3001. // mismatch.
  3002. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3003. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3004. PrevVD = PrevVD->getPreviousDecl()) {
  3005. const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
  3006. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3007. continue;
  3008. if (!Context.hasSameType(NewArray, PrevVDTy))
  3009. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3010. }
  3011. }
  3012. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3013. if (Context.hasSameType(OldArray->getElementType(),
  3014. NewArray->getElementType()))
  3015. MergedT = New->getType();
  3016. }
  3017. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3018. // has no array bound, it should not inherit one from Old, if Old is not
  3019. // visible.
  3020. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3021. if (Context.hasSameType(OldArray->getElementType(),
  3022. NewArray->getElementType()))
  3023. MergedT = Old->getType();
  3024. }
  3025. }
  3026. else if (New->getType()->isObjCObjectPointerType() &&
  3027. Old->getType()->isObjCObjectPointerType()) {
  3028. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3029. Old->getType());
  3030. }
  3031. } else {
  3032. // C 6.2.7p2:
  3033. // All declarations that refer to the same object or function shall have
  3034. // compatible type.
  3035. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3036. }
  3037. if (MergedT.isNull()) {
  3038. // It's OK if we couldn't merge types if either type is dependent, for a
  3039. // block-scope variable. In other cases (static data members of class
  3040. // templates, variable templates, ...), we require the types to be
  3041. // equivalent.
  3042. // FIXME: The C++ standard doesn't say anything about this.
  3043. if ((New->getType()->isDependentType() ||
  3044. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3045. // If the old type was dependent, we can't merge with it, so the new type
  3046. // becomes dependent for now. We'll reproduce the original type when we
  3047. // instantiate the TypeSourceInfo for the variable.
  3048. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3049. New->setType(Context.DependentTy);
  3050. return;
  3051. }
  3052. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3053. }
  3054. // Don't actually update the type on the new declaration if the old
  3055. // declaration was an extern declaration in a different scope.
  3056. if (MergeTypeWithOld)
  3057. New->setType(MergedT);
  3058. }
  3059. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3060. LookupResult &Previous) {
  3061. // C11 6.2.7p4:
  3062. // For an identifier with internal or external linkage declared
  3063. // in a scope in which a prior declaration of that identifier is
  3064. // visible, if the prior declaration specifies internal or
  3065. // external linkage, the type of the identifier at the later
  3066. // declaration becomes the composite type.
  3067. //
  3068. // If the variable isn't visible, we do not merge with its type.
  3069. if (Previous.isShadowed())
  3070. return false;
  3071. if (S.getLangOpts().CPlusPlus) {
  3072. // C++11 [dcl.array]p3:
  3073. // If there is a preceding declaration of the entity in the same
  3074. // scope in which the bound was specified, an omitted array bound
  3075. // is taken to be the same as in that earlier declaration.
  3076. return NewVD->isPreviousDeclInSameBlockScope() ||
  3077. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3078. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3079. } else {
  3080. // If the old declaration was function-local, don't merge with its
  3081. // type unless we're in the same function.
  3082. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3083. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3084. }
  3085. }
  3086. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3087. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3088. /// situation, merging decls or emitting diagnostics as appropriate.
  3089. ///
  3090. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3091. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3092. /// definitions here, since the initializer hasn't been attached.
  3093. ///
  3094. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3095. // If the new decl is already invalid, don't do any other checking.
  3096. if (New->isInvalidDecl())
  3097. return;
  3098. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3099. return;
  3100. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3101. // Verify the old decl was also a variable or variable template.
  3102. VarDecl *Old = nullptr;
  3103. VarTemplateDecl *OldTemplate = nullptr;
  3104. if (Previous.isSingleResult()) {
  3105. if (NewTemplate) {
  3106. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3107. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3108. if (auto *Shadow =
  3109. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3110. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3111. return New->setInvalidDecl();
  3112. } else {
  3113. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3114. if (auto *Shadow =
  3115. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3116. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3117. return New->setInvalidDecl();
  3118. }
  3119. }
  3120. if (!Old) {
  3121. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3122. << New->getDeclName();
  3123. Diag(Previous.getRepresentativeDecl()->getLocation(),
  3124. diag::note_previous_definition);
  3125. return New->setInvalidDecl();
  3126. }
  3127. // Ensure the template parameters are compatible.
  3128. if (NewTemplate &&
  3129. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3130. OldTemplate->getTemplateParameters(),
  3131. /*Complain=*/true, TPL_TemplateMatch))
  3132. return New->setInvalidDecl();
  3133. // C++ [class.mem]p1:
  3134. // A member shall not be declared twice in the member-specification [...]
  3135. //
  3136. // Here, we need only consider static data members.
  3137. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3138. Diag(New->getLocation(), diag::err_duplicate_member)
  3139. << New->getIdentifier();
  3140. Diag(Old->getLocation(), diag::note_previous_declaration);
  3141. New->setInvalidDecl();
  3142. }
  3143. mergeDeclAttributes(New, Old);
  3144. // Warn if an already-declared variable is made a weak_import in a subsequent
  3145. // declaration
  3146. if (New->hasAttr<WeakImportAttr>() &&
  3147. Old->getStorageClass() == SC_None &&
  3148. !Old->hasAttr<WeakImportAttr>()) {
  3149. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3150. Diag(Old->getLocation(), diag::note_previous_definition);
  3151. // Remove weak_import attribute on new declaration.
  3152. New->dropAttr<WeakImportAttr>();
  3153. }
  3154. if (New->hasAttr<InternalLinkageAttr>() &&
  3155. !Old->hasAttr<InternalLinkageAttr>()) {
  3156. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  3157. << New->getDeclName();
  3158. Diag(Old->getLocation(), diag::note_previous_definition);
  3159. New->dropAttr<InternalLinkageAttr>();
  3160. }
  3161. // Merge the types.
  3162. VarDecl *MostRecent = Old->getMostRecentDecl();
  3163. if (MostRecent != Old) {
  3164. MergeVarDeclTypes(New, MostRecent,
  3165. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3166. if (New->isInvalidDecl())
  3167. return;
  3168. }
  3169. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3170. if (New->isInvalidDecl())
  3171. return;
  3172. diag::kind PrevDiag;
  3173. SourceLocation OldLocation;
  3174. std::tie(PrevDiag, OldLocation) =
  3175. getNoteDiagForInvalidRedeclaration(Old, New);
  3176. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3177. if (New->getStorageClass() == SC_Static &&
  3178. !New->isStaticDataMember() &&
  3179. Old->hasExternalFormalLinkage()) {
  3180. if (getLangOpts().MicrosoftExt) {
  3181. Diag(New->getLocation(), diag::ext_static_non_static)
  3182. << New->getDeclName();
  3183. Diag(OldLocation, PrevDiag);
  3184. } else {
  3185. Diag(New->getLocation(), diag::err_static_non_static)
  3186. << New->getDeclName();
  3187. Diag(OldLocation, PrevDiag);
  3188. return New->setInvalidDecl();
  3189. }
  3190. }
  3191. // C99 6.2.2p4:
  3192. // For an identifier declared with the storage-class specifier
  3193. // extern in a scope in which a prior declaration of that
  3194. // identifier is visible,23) if the prior declaration specifies
  3195. // internal or external linkage, the linkage of the identifier at
  3196. // the later declaration is the same as the linkage specified at
  3197. // the prior declaration. If no prior declaration is visible, or
  3198. // if the prior declaration specifies no linkage, then the
  3199. // identifier has external linkage.
  3200. if (New->hasExternalStorage() && Old->hasLinkage())
  3201. /* Okay */;
  3202. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3203. !New->isStaticDataMember() &&
  3204. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3205. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3206. Diag(OldLocation, PrevDiag);
  3207. return New->setInvalidDecl();
  3208. }
  3209. // Check if extern is followed by non-extern and vice-versa.
  3210. if (New->hasExternalStorage() &&
  3211. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3212. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3213. Diag(OldLocation, PrevDiag);
  3214. return New->setInvalidDecl();
  3215. }
  3216. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3217. !New->hasExternalStorage()) {
  3218. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3219. Diag(OldLocation, PrevDiag);
  3220. return New->setInvalidDecl();
  3221. }
  3222. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3223. // FIXME: The test for external storage here seems wrong? We still
  3224. // need to check for mismatches.
  3225. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3226. // Don't complain about out-of-line definitions of static members.
  3227. !(Old->getLexicalDeclContext()->isRecord() &&
  3228. !New->getLexicalDeclContext()->isRecord())) {
  3229. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3230. Diag(OldLocation, PrevDiag);
  3231. return New->setInvalidDecl();
  3232. }
  3233. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3234. if (VarDecl *Def = Old->getDefinition()) {
  3235. // C++1z [dcl.fcn.spec]p4:
  3236. // If the definition of a variable appears in a translation unit before
  3237. // its first declaration as inline, the program is ill-formed.
  3238. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3239. Diag(Def->getLocation(), diag::note_previous_definition);
  3240. }
  3241. }
  3242. // If this redeclaration makes the function inline, we may need to add it to
  3243. // UndefinedButUsed.
  3244. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3245. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3246. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3247. SourceLocation()));
  3248. if (New->getTLSKind() != Old->getTLSKind()) {
  3249. if (!Old->getTLSKind()) {
  3250. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3251. Diag(OldLocation, PrevDiag);
  3252. } else if (!New->getTLSKind()) {
  3253. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3254. Diag(OldLocation, PrevDiag);
  3255. } else {
  3256. // Do not allow redeclaration to change the variable between requiring
  3257. // static and dynamic initialization.
  3258. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3259. // declaration to determine the kind. Do we need to be compatible here?
  3260. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3261. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3262. Diag(OldLocation, PrevDiag);
  3263. }
  3264. }
  3265. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3266. if (getLangOpts().CPlusPlus &&
  3267. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3268. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3269. Old->getCanonicalDecl()->isConstexpr()) {
  3270. // This definition won't be a definition any more once it's been merged.
  3271. Diag(New->getLocation(),
  3272. diag::warn_deprecated_redundant_constexpr_static_def);
  3273. } else if (VarDecl *Def = Old->getDefinition()) {
  3274. if (checkVarDeclRedefinition(Def, New))
  3275. return;
  3276. }
  3277. }
  3278. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3279. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3280. Diag(OldLocation, PrevDiag);
  3281. New->setInvalidDecl();
  3282. return;
  3283. }
  3284. // Merge "used" flag.
  3285. if (Old->getMostRecentDecl()->isUsed(false))
  3286. New->setIsUsed();
  3287. // Keep a chain of previous declarations.
  3288. New->setPreviousDecl(Old);
  3289. if (NewTemplate)
  3290. NewTemplate->setPreviousDecl(OldTemplate);
  3291. // Inherit access appropriately.
  3292. New->setAccess(Old->getAccess());
  3293. if (NewTemplate)
  3294. NewTemplate->setAccess(New->getAccess());
  3295. if (Old->isInline())
  3296. New->setImplicitlyInline();
  3297. }
  3298. /// We've just determined that \p Old and \p New both appear to be definitions
  3299. /// of the same variable. Either diagnose or fix the problem.
  3300. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3301. if (!hasVisibleDefinition(Old) &&
  3302. (New->getFormalLinkage() == InternalLinkage ||
  3303. New->isInline() ||
  3304. New->getDescribedVarTemplate() ||
  3305. New->getNumTemplateParameterLists() ||
  3306. New->getDeclContext()->isDependentContext())) {
  3307. // The previous definition is hidden, and multiple definitions are
  3308. // permitted (in separate TUs). Demote this to a declaration.
  3309. New->demoteThisDefinitionToDeclaration();
  3310. // Make the canonical definition visible.
  3311. if (auto *OldTD = Old->getDescribedVarTemplate())
  3312. makeMergedDefinitionVisible(OldTD, New->getLocation());
  3313. makeMergedDefinitionVisible(Old, New->getLocation());
  3314. return false;
  3315. } else {
  3316. Diag(New->getLocation(), diag::err_redefinition) << New;
  3317. Diag(Old->getLocation(), diag::note_previous_definition);
  3318. New->setInvalidDecl();
  3319. return true;
  3320. }
  3321. }
  3322. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3323. /// no declarator (e.g. "struct foo;") is parsed.
  3324. Decl *
  3325. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3326. RecordDecl *&AnonRecord) {
  3327. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3328. AnonRecord);
  3329. }
  3330. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3331. // disambiguate entities defined in different scopes.
  3332. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3333. // compatibility.
  3334. // We will pick our mangling number depending on which version of MSVC is being
  3335. // targeted.
  3336. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3337. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3338. ? S->getMSCurManglingNumber()
  3339. : S->getMSLastManglingNumber();
  3340. }
  3341. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3342. if (!Context.getLangOpts().CPlusPlus)
  3343. return;
  3344. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3345. // If this tag is the direct child of a class, number it if
  3346. // it is anonymous.
  3347. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3348. return;
  3349. MangleNumberingContext &MCtx =
  3350. Context.getManglingNumberContext(Tag->getParent());
  3351. Context.setManglingNumber(
  3352. Tag, MCtx.getManglingNumber(
  3353. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3354. return;
  3355. }
  3356. // If this tag isn't a direct child of a class, number it if it is local.
  3357. Decl *ManglingContextDecl;
  3358. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3359. Tag->getDeclContext(), ManglingContextDecl)) {
  3360. Context.setManglingNumber(
  3361. Tag, MCtx->getManglingNumber(
  3362. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3363. }
  3364. }
  3365. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3366. TypedefNameDecl *NewTD) {
  3367. if (TagFromDeclSpec->isInvalidDecl())
  3368. return;
  3369. // Do nothing if the tag already has a name for linkage purposes.
  3370. if (TagFromDeclSpec->hasNameForLinkage())
  3371. return;
  3372. // A well-formed anonymous tag must always be a TUK_Definition.
  3373. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3374. // The type must match the tag exactly; no qualifiers allowed.
  3375. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3376. Context.getTagDeclType(TagFromDeclSpec))) {
  3377. if (getLangOpts().CPlusPlus)
  3378. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3379. return;
  3380. }
  3381. // If we've already computed linkage for the anonymous tag, then
  3382. // adding a typedef name for the anonymous decl can change that
  3383. // linkage, which might be a serious problem. Diagnose this as
  3384. // unsupported and ignore the typedef name. TODO: we should
  3385. // pursue this as a language defect and establish a formal rule
  3386. // for how to handle it.
  3387. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3388. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3389. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3390. tagLoc = getLocForEndOfToken(tagLoc);
  3391. llvm::SmallString<40> textToInsert;
  3392. textToInsert += ' ';
  3393. textToInsert += NewTD->getIdentifier()->getName();
  3394. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3395. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3396. return;
  3397. }
  3398. // Otherwise, set this is the anon-decl typedef for the tag.
  3399. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3400. }
  3401. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3402. switch (T) {
  3403. case DeclSpec::TST_class:
  3404. return 0;
  3405. case DeclSpec::TST_struct:
  3406. return 1;
  3407. case DeclSpec::TST_interface:
  3408. return 2;
  3409. case DeclSpec::TST_union:
  3410. return 3;
  3411. case DeclSpec::TST_enum:
  3412. return 4;
  3413. default:
  3414. llvm_unreachable("unexpected type specifier");
  3415. }
  3416. }
  3417. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3418. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3419. /// parameters to cope with template friend declarations.
  3420. Decl *
  3421. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3422. MultiTemplateParamsArg TemplateParams,
  3423. bool IsExplicitInstantiation,
  3424. RecordDecl *&AnonRecord) {
  3425. Decl *TagD = nullptr;
  3426. TagDecl *Tag = nullptr;
  3427. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3428. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3429. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3430. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3431. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3432. TagD = DS.getRepAsDecl();
  3433. if (!TagD) // We probably had an error
  3434. return nullptr;
  3435. // Note that the above type specs guarantee that the
  3436. // type rep is a Decl, whereas in many of the others
  3437. // it's a Type.
  3438. if (isa<TagDecl>(TagD))
  3439. Tag = cast<TagDecl>(TagD);
  3440. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3441. Tag = CTD->getTemplatedDecl();
  3442. }
  3443. if (Tag) {
  3444. handleTagNumbering(Tag, S);
  3445. Tag->setFreeStanding();
  3446. if (Tag->isInvalidDecl())
  3447. return Tag;
  3448. }
  3449. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3450. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3451. // or incomplete types shall not be restrict-qualified."
  3452. if (TypeQuals & DeclSpec::TQ_restrict)
  3453. Diag(DS.getRestrictSpecLoc(),
  3454. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3455. << DS.getSourceRange();
  3456. }
  3457. if (DS.isInlineSpecified())
  3458. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  3459. << getLangOpts().CPlusPlus1z;
  3460. if (DS.isConstexprSpecified()) {
  3461. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3462. // and definitions of functions and variables.
  3463. if (Tag)
  3464. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3465. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
  3466. else
  3467. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  3468. // Don't emit warnings after this error.
  3469. return TagD;
  3470. }
  3471. if (DS.isConceptSpecified()) {
  3472. // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
  3473. // either a function concept and its definition or a variable concept and
  3474. // its initializer.
  3475. Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
  3476. return TagD;
  3477. }
  3478. DiagnoseFunctionSpecifiers(DS);
  3479. if (DS.isFriendSpecified()) {
  3480. // If we're dealing with a decl but not a TagDecl, assume that
  3481. // whatever routines created it handled the friendship aspect.
  3482. if (TagD && !Tag)
  3483. return nullptr;
  3484. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3485. }
  3486. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3487. bool IsExplicitSpecialization =
  3488. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3489. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3490. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  3491. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  3492. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3493. // nested-name-specifier unless it is an explicit instantiation
  3494. // or an explicit specialization.
  3495. //
  3496. // FIXME: We allow class template partial specializations here too, per the
  3497. // obvious intent of DR1819.
  3498. //
  3499. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3500. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3501. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3502. return nullptr;
  3503. }
  3504. // Track whether this decl-specifier declares anything.
  3505. bool DeclaresAnything = true;
  3506. // Handle anonymous struct definitions.
  3507. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3508. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3509. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3510. if (getLangOpts().CPlusPlus ||
  3511. Record->getDeclContext()->isRecord()) {
  3512. // If CurContext is a DeclContext that can contain statements,
  3513. // RecursiveASTVisitor won't visit the decls that
  3514. // BuildAnonymousStructOrUnion() will put into CurContext.
  3515. // Also store them here so that they can be part of the
  3516. // DeclStmt that gets created in this case.
  3517. // FIXME: Also return the IndirectFieldDecls created by
  3518. // BuildAnonymousStructOr union, for the same reason?
  3519. if (CurContext->isFunctionOrMethod())
  3520. AnonRecord = Record;
  3521. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3522. Context.getPrintingPolicy());
  3523. }
  3524. DeclaresAnything = false;
  3525. }
  3526. }
  3527. // C11 6.7.2.1p2:
  3528. // A struct-declaration that does not declare an anonymous structure or
  3529. // anonymous union shall contain a struct-declarator-list.
  3530. //
  3531. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3532. // did not permit a struct-declaration without a struct-declarator-list.
  3533. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3534. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3535. // Check for Microsoft C extension: anonymous struct/union member.
  3536. // Handle 2 kinds of anonymous struct/union:
  3537. // struct STRUCT;
  3538. // union UNION;
  3539. // and
  3540. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3541. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3542. if ((Tag && Tag->getDeclName()) ||
  3543. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3544. RecordDecl *Record = nullptr;
  3545. if (Tag)
  3546. Record = dyn_cast<RecordDecl>(Tag);
  3547. else if (const RecordType *RT =
  3548. DS.getRepAsType().get()->getAsStructureType())
  3549. Record = RT->getDecl();
  3550. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3551. Record = UT->getDecl();
  3552. if (Record && getLangOpts().MicrosoftExt) {
  3553. Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
  3554. << Record->isUnion() << DS.getSourceRange();
  3555. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3556. }
  3557. DeclaresAnything = false;
  3558. }
  3559. }
  3560. // Skip all the checks below if we have a type error.
  3561. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3562. (TagD && TagD->isInvalidDecl()))
  3563. return TagD;
  3564. if (getLangOpts().CPlusPlus &&
  3565. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3566. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  3567. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  3568. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  3569. DeclaresAnything = false;
  3570. if (!DS.isMissingDeclaratorOk()) {
  3571. // Customize diagnostic for a typedef missing a name.
  3572. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  3573. Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
  3574. << DS.getSourceRange();
  3575. else
  3576. DeclaresAnything = false;
  3577. }
  3578. if (DS.isModulePrivateSpecified() &&
  3579. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  3580. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  3581. << Tag->getTagKind()
  3582. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  3583. ActOnDocumentableDecl(TagD);
  3584. // C 6.7/2:
  3585. // A declaration [...] shall declare at least a declarator [...], a tag,
  3586. // or the members of an enumeration.
  3587. // C++ [dcl.dcl]p3:
  3588. // [If there are no declarators], and except for the declaration of an
  3589. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  3590. // names into the program, or shall redeclare a name introduced by a
  3591. // previous declaration.
  3592. if (!DeclaresAnything) {
  3593. // In C, we allow this as a (popular) extension / bug. Don't bother
  3594. // producing further diagnostics for redundant qualifiers after this.
  3595. Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
  3596. return TagD;
  3597. }
  3598. // C++ [dcl.stc]p1:
  3599. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  3600. // init-declarator-list of the declaration shall not be empty.
  3601. // C++ [dcl.fct.spec]p1:
  3602. // If a cv-qualifier appears in a decl-specifier-seq, the
  3603. // init-declarator-list of the declaration shall not be empty.
  3604. //
  3605. // Spurious qualifiers here appear to be valid in C.
  3606. unsigned DiagID = diag::warn_standalone_specifier;
  3607. if (getLangOpts().CPlusPlus)
  3608. DiagID = diag::ext_standalone_specifier;
  3609. // Note that a linkage-specification sets a storage class, but
  3610. // 'extern "C" struct foo;' is actually valid and not theoretically
  3611. // useless.
  3612. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3613. if (SCS == DeclSpec::SCS_mutable)
  3614. // Since mutable is not a viable storage class specifier in C, there is
  3615. // no reason to treat it as an extension. Instead, diagnose as an error.
  3616. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  3617. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  3618. Diag(DS.getStorageClassSpecLoc(), DiagID)
  3619. << DeclSpec::getSpecifierName(SCS);
  3620. }
  3621. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  3622. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  3623. << DeclSpec::getSpecifierName(TSCS);
  3624. if (DS.getTypeQualifiers()) {
  3625. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3626. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  3627. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3628. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  3629. // Restrict is covered above.
  3630. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3631. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  3632. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  3633. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  3634. }
  3635. // Warn about ignored type attributes, for example:
  3636. // __attribute__((aligned)) struct A;
  3637. // Attributes should be placed after tag to apply to type declaration.
  3638. if (!DS.getAttributes().empty()) {
  3639. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  3640. if (TypeSpecType == DeclSpec::TST_class ||
  3641. TypeSpecType == DeclSpec::TST_struct ||
  3642. TypeSpecType == DeclSpec::TST_interface ||
  3643. TypeSpecType == DeclSpec::TST_union ||
  3644. TypeSpecType == DeclSpec::TST_enum) {
  3645. for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
  3646. attrs = attrs->getNext())
  3647. Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
  3648. << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  3649. }
  3650. }
  3651. return TagD;
  3652. }
  3653. /// We are trying to inject an anonymous member into the given scope;
  3654. /// check if there's an existing declaration that can't be overloaded.
  3655. ///
  3656. /// \return true if this is a forbidden redeclaration
  3657. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  3658. Scope *S,
  3659. DeclContext *Owner,
  3660. DeclarationName Name,
  3661. SourceLocation NameLoc,
  3662. bool IsUnion) {
  3663. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  3664. Sema::ForRedeclaration);
  3665. if (!SemaRef.LookupName(R, S)) return false;
  3666. // Pick a representative declaration.
  3667. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  3668. assert(PrevDecl && "Expected a non-null Decl");
  3669. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  3670. return false;
  3671. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  3672. << IsUnion << Name;
  3673. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  3674. return true;
  3675. }
  3676. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  3677. /// anonymous struct or union AnonRecord into the owning context Owner
  3678. /// and scope S. This routine will be invoked just after we realize
  3679. /// that an unnamed union or struct is actually an anonymous union or
  3680. /// struct, e.g.,
  3681. ///
  3682. /// @code
  3683. /// union {
  3684. /// int i;
  3685. /// float f;
  3686. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  3687. /// // f into the surrounding scope.x
  3688. /// @endcode
  3689. ///
  3690. /// This routine is recursive, injecting the names of nested anonymous
  3691. /// structs/unions into the owning context and scope as well.
  3692. static bool
  3693. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  3694. RecordDecl *AnonRecord, AccessSpecifier AS,
  3695. SmallVectorImpl<NamedDecl *> &Chaining) {
  3696. bool Invalid = false;
  3697. // Look every FieldDecl and IndirectFieldDecl with a name.
  3698. for (auto *D : AnonRecord->decls()) {
  3699. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  3700. cast<NamedDecl>(D)->getDeclName()) {
  3701. ValueDecl *VD = cast<ValueDecl>(D);
  3702. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  3703. VD->getLocation(),
  3704. AnonRecord->isUnion())) {
  3705. // C++ [class.union]p2:
  3706. // The names of the members of an anonymous union shall be
  3707. // distinct from the names of any other entity in the
  3708. // scope in which the anonymous union is declared.
  3709. Invalid = true;
  3710. } else {
  3711. // C++ [class.union]p2:
  3712. // For the purpose of name lookup, after the anonymous union
  3713. // definition, the members of the anonymous union are
  3714. // considered to have been defined in the scope in which the
  3715. // anonymous union is declared.
  3716. unsigned OldChainingSize = Chaining.size();
  3717. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  3718. Chaining.append(IF->chain_begin(), IF->chain_end());
  3719. else
  3720. Chaining.push_back(VD);
  3721. assert(Chaining.size() >= 2);
  3722. NamedDecl **NamedChain =
  3723. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  3724. for (unsigned i = 0; i < Chaining.size(); i++)
  3725. NamedChain[i] = Chaining[i];
  3726. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  3727. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  3728. VD->getType(), {NamedChain, Chaining.size()});
  3729. for (const auto *Attr : VD->attrs())
  3730. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  3731. IndirectField->setAccess(AS);
  3732. IndirectField->setImplicit();
  3733. SemaRef.PushOnScopeChains(IndirectField, S);
  3734. // That includes picking up the appropriate access specifier.
  3735. if (AS != AS_none) IndirectField->setAccess(AS);
  3736. Chaining.resize(OldChainingSize);
  3737. }
  3738. }
  3739. }
  3740. return Invalid;
  3741. }
  3742. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  3743. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  3744. /// illegal input values are mapped to SC_None.
  3745. static StorageClass
  3746. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  3747. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  3748. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  3749. "Parser allowed 'typedef' as storage class VarDecl.");
  3750. switch (StorageClassSpec) {
  3751. case DeclSpec::SCS_unspecified: return SC_None;
  3752. case DeclSpec::SCS_extern:
  3753. if (DS.isExternInLinkageSpec())
  3754. return SC_None;
  3755. return SC_Extern;
  3756. case DeclSpec::SCS_static: return SC_Static;
  3757. case DeclSpec::SCS_auto: return SC_Auto;
  3758. case DeclSpec::SCS_register: return SC_Register;
  3759. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  3760. // Illegal SCSs map to None: error reporting is up to the caller.
  3761. case DeclSpec::SCS_mutable: // Fall through.
  3762. case DeclSpec::SCS_typedef: return SC_None;
  3763. }
  3764. llvm_unreachable("unknown storage class specifier");
  3765. }
  3766. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  3767. assert(Record->hasInClassInitializer());
  3768. for (const auto *I : Record->decls()) {
  3769. const auto *FD = dyn_cast<FieldDecl>(I);
  3770. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  3771. FD = IFD->getAnonField();
  3772. if (FD && FD->hasInClassInitializer())
  3773. return FD->getLocation();
  3774. }
  3775. llvm_unreachable("couldn't find in-class initializer");
  3776. }
  3777. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3778. SourceLocation DefaultInitLoc) {
  3779. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3780. return;
  3781. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  3782. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  3783. }
  3784. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3785. CXXRecordDecl *AnonUnion) {
  3786. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3787. return;
  3788. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  3789. }
  3790. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  3791. /// anonymous structure or union. Anonymous unions are a C++ feature
  3792. /// (C++ [class.union]) and a C11 feature; anonymous structures
  3793. /// are a C11 feature and GNU C++ extension.
  3794. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  3795. AccessSpecifier AS,
  3796. RecordDecl *Record,
  3797. const PrintingPolicy &Policy) {
  3798. DeclContext *Owner = Record->getDeclContext();
  3799. // Diagnose whether this anonymous struct/union is an extension.
  3800. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  3801. Diag(Record->getLocation(), diag::ext_anonymous_union);
  3802. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  3803. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  3804. else if (!Record->isUnion() && !getLangOpts().C11)
  3805. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  3806. // C and C++ require different kinds of checks for anonymous
  3807. // structs/unions.
  3808. bool Invalid = false;
  3809. if (getLangOpts().CPlusPlus) {
  3810. const char *PrevSpec = nullptr;
  3811. unsigned DiagID;
  3812. if (Record->isUnion()) {
  3813. // C++ [class.union]p6:
  3814. // Anonymous unions declared in a named namespace or in the
  3815. // global namespace shall be declared static.
  3816. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  3817. (isa<TranslationUnitDecl>(Owner) ||
  3818. (isa<NamespaceDecl>(Owner) &&
  3819. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  3820. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  3821. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  3822. // Recover by adding 'static'.
  3823. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  3824. PrevSpec, DiagID, Policy);
  3825. }
  3826. // C++ [class.union]p6:
  3827. // A storage class is not allowed in a declaration of an
  3828. // anonymous union in a class scope.
  3829. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  3830. isa<RecordDecl>(Owner)) {
  3831. Diag(DS.getStorageClassSpecLoc(),
  3832. diag::err_anonymous_union_with_storage_spec)
  3833. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  3834. // Recover by removing the storage specifier.
  3835. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  3836. SourceLocation(),
  3837. PrevSpec, DiagID, Context.getPrintingPolicy());
  3838. }
  3839. }
  3840. // Ignore const/volatile/restrict qualifiers.
  3841. if (DS.getTypeQualifiers()) {
  3842. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3843. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  3844. << Record->isUnion() << "const"
  3845. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  3846. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3847. Diag(DS.getVolatileSpecLoc(),
  3848. diag::ext_anonymous_struct_union_qualified)
  3849. << Record->isUnion() << "volatile"
  3850. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  3851. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  3852. Diag(DS.getRestrictSpecLoc(),
  3853. diag::ext_anonymous_struct_union_qualified)
  3854. << Record->isUnion() << "restrict"
  3855. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  3856. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3857. Diag(DS.getAtomicSpecLoc(),
  3858. diag::ext_anonymous_struct_union_qualified)
  3859. << Record->isUnion() << "_Atomic"
  3860. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  3861. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  3862. Diag(DS.getUnalignedSpecLoc(),
  3863. diag::ext_anonymous_struct_union_qualified)
  3864. << Record->isUnion() << "__unaligned"
  3865. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  3866. DS.ClearTypeQualifiers();
  3867. }
  3868. // C++ [class.union]p2:
  3869. // The member-specification of an anonymous union shall only
  3870. // define non-static data members. [Note: nested types and
  3871. // functions cannot be declared within an anonymous union. ]
  3872. for (auto *Mem : Record->decls()) {
  3873. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  3874. // C++ [class.union]p3:
  3875. // An anonymous union shall not have private or protected
  3876. // members (clause 11).
  3877. assert(FD->getAccess() != AS_none);
  3878. if (FD->getAccess() != AS_public) {
  3879. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  3880. << Record->isUnion() << (FD->getAccess() == AS_protected);
  3881. Invalid = true;
  3882. }
  3883. // C++ [class.union]p1
  3884. // An object of a class with a non-trivial constructor, a non-trivial
  3885. // copy constructor, a non-trivial destructor, or a non-trivial copy
  3886. // assignment operator cannot be a member of a union, nor can an
  3887. // array of such objects.
  3888. if (CheckNontrivialField(FD))
  3889. Invalid = true;
  3890. } else if (Mem->isImplicit()) {
  3891. // Any implicit members are fine.
  3892. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  3893. // This is a type that showed up in an
  3894. // elaborated-type-specifier inside the anonymous struct or
  3895. // union, but which actually declares a type outside of the
  3896. // anonymous struct or union. It's okay.
  3897. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  3898. if (!MemRecord->isAnonymousStructOrUnion() &&
  3899. MemRecord->getDeclName()) {
  3900. // Visual C++ allows type definition in anonymous struct or union.
  3901. if (getLangOpts().MicrosoftExt)
  3902. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  3903. << Record->isUnion();
  3904. else {
  3905. // This is a nested type declaration.
  3906. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  3907. << Record->isUnion();
  3908. Invalid = true;
  3909. }
  3910. } else {
  3911. // This is an anonymous type definition within another anonymous type.
  3912. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  3913. // not part of standard C++.
  3914. Diag(MemRecord->getLocation(),
  3915. diag::ext_anonymous_record_with_anonymous_type)
  3916. << Record->isUnion();
  3917. }
  3918. } else if (isa<AccessSpecDecl>(Mem)) {
  3919. // Any access specifier is fine.
  3920. } else if (isa<StaticAssertDecl>(Mem)) {
  3921. // In C++1z, static_assert declarations are also fine.
  3922. } else {
  3923. // We have something that isn't a non-static data
  3924. // member. Complain about it.
  3925. unsigned DK = diag::err_anonymous_record_bad_member;
  3926. if (isa<TypeDecl>(Mem))
  3927. DK = diag::err_anonymous_record_with_type;
  3928. else if (isa<FunctionDecl>(Mem))
  3929. DK = diag::err_anonymous_record_with_function;
  3930. else if (isa<VarDecl>(Mem))
  3931. DK = diag::err_anonymous_record_with_static;
  3932. // Visual C++ allows type definition in anonymous struct or union.
  3933. if (getLangOpts().MicrosoftExt &&
  3934. DK == diag::err_anonymous_record_with_type)
  3935. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  3936. << Record->isUnion();
  3937. else {
  3938. Diag(Mem->getLocation(), DK) << Record->isUnion();
  3939. Invalid = true;
  3940. }
  3941. }
  3942. }
  3943. // C++11 [class.union]p8 (DR1460):
  3944. // At most one variant member of a union may have a
  3945. // brace-or-equal-initializer.
  3946. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  3947. Owner->isRecord())
  3948. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  3949. cast<CXXRecordDecl>(Record));
  3950. }
  3951. if (!Record->isUnion() && !Owner->isRecord()) {
  3952. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  3953. << getLangOpts().CPlusPlus;
  3954. Invalid = true;
  3955. }
  3956. // Mock up a declarator.
  3957. Declarator Dc(DS, Declarator::MemberContext);
  3958. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  3959. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  3960. // Create a declaration for this anonymous struct/union.
  3961. NamedDecl *Anon = nullptr;
  3962. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  3963. Anon = FieldDecl::Create(Context, OwningClass,
  3964. DS.getLocStart(),
  3965. Record->getLocation(),
  3966. /*IdentifierInfo=*/nullptr,
  3967. Context.getTypeDeclType(Record),
  3968. TInfo,
  3969. /*BitWidth=*/nullptr, /*Mutable=*/false,
  3970. /*InitStyle=*/ICIS_NoInit);
  3971. Anon->setAccess(AS);
  3972. if (getLangOpts().CPlusPlus)
  3973. FieldCollector->Add(cast<FieldDecl>(Anon));
  3974. } else {
  3975. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  3976. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  3977. if (SCSpec == DeclSpec::SCS_mutable) {
  3978. // mutable can only appear on non-static class members, so it's always
  3979. // an error here
  3980. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  3981. Invalid = true;
  3982. SC = SC_None;
  3983. }
  3984. Anon = VarDecl::Create(Context, Owner,
  3985. DS.getLocStart(),
  3986. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  3987. Context.getTypeDeclType(Record),
  3988. TInfo, SC);
  3989. // Default-initialize the implicit variable. This initialization will be
  3990. // trivial in almost all cases, except if a union member has an in-class
  3991. // initializer:
  3992. // union { int n = 0; };
  3993. ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
  3994. }
  3995. Anon->setImplicit();
  3996. // Mark this as an anonymous struct/union type.
  3997. Record->setAnonymousStructOrUnion(true);
  3998. // Add the anonymous struct/union object to the current
  3999. // context. We'll be referencing this object when we refer to one of
  4000. // its members.
  4001. Owner->addDecl(Anon);
  4002. // Inject the members of the anonymous struct/union into the owning
  4003. // context and into the identifier resolver chain for name lookup
  4004. // purposes.
  4005. SmallVector<NamedDecl*, 2> Chain;
  4006. Chain.push_back(Anon);
  4007. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4008. Invalid = true;
  4009. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4010. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4011. Decl *ManglingContextDecl;
  4012. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  4013. NewVD->getDeclContext(), ManglingContextDecl)) {
  4014. Context.setManglingNumber(
  4015. NewVD, MCtx->getManglingNumber(
  4016. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4017. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4018. }
  4019. }
  4020. }
  4021. if (Invalid)
  4022. Anon->setInvalidDecl();
  4023. return Anon;
  4024. }
  4025. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4026. /// Microsoft C anonymous structure.
  4027. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4028. /// Example:
  4029. ///
  4030. /// struct A { int a; };
  4031. /// struct B { struct A; int b; };
  4032. ///
  4033. /// void foo() {
  4034. /// B var;
  4035. /// var.a = 3;
  4036. /// }
  4037. ///
  4038. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4039. RecordDecl *Record) {
  4040. assert(Record && "expected a record!");
  4041. // Mock up a declarator.
  4042. Declarator Dc(DS, Declarator::TypeNameContext);
  4043. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4044. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4045. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4046. QualType RecTy = Context.getTypeDeclType(Record);
  4047. // Create a declaration for this anonymous struct.
  4048. NamedDecl *Anon = FieldDecl::Create(Context,
  4049. ParentDecl,
  4050. DS.getLocStart(),
  4051. DS.getLocStart(),
  4052. /*IdentifierInfo=*/nullptr,
  4053. RecTy,
  4054. TInfo,
  4055. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4056. /*InitStyle=*/ICIS_NoInit);
  4057. Anon->setImplicit();
  4058. // Add the anonymous struct object to the current context.
  4059. CurContext->addDecl(Anon);
  4060. // Inject the members of the anonymous struct into the current
  4061. // context and into the identifier resolver chain for name lookup
  4062. // purposes.
  4063. SmallVector<NamedDecl*, 2> Chain;
  4064. Chain.push_back(Anon);
  4065. RecordDecl *RecordDef = Record->getDefinition();
  4066. if (RequireCompleteType(Anon->getLocation(), RecTy,
  4067. diag::err_field_incomplete) ||
  4068. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4069. AS_none, Chain)) {
  4070. Anon->setInvalidDecl();
  4071. ParentDecl->setInvalidDecl();
  4072. }
  4073. return Anon;
  4074. }
  4075. /// GetNameForDeclarator - Determine the full declaration name for the
  4076. /// given Declarator.
  4077. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4078. return GetNameFromUnqualifiedId(D.getName());
  4079. }
  4080. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  4081. DeclarationNameInfo
  4082. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4083. DeclarationNameInfo NameInfo;
  4084. NameInfo.setLoc(Name.StartLocation);
  4085. switch (Name.getKind()) {
  4086. case UnqualifiedId::IK_ImplicitSelfParam:
  4087. case UnqualifiedId::IK_Identifier:
  4088. NameInfo.setName(Name.Identifier);
  4089. NameInfo.setLoc(Name.StartLocation);
  4090. return NameInfo;
  4091. case UnqualifiedId::IK_OperatorFunctionId:
  4092. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4093. Name.OperatorFunctionId.Operator));
  4094. NameInfo.setLoc(Name.StartLocation);
  4095. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  4096. = Name.OperatorFunctionId.SymbolLocations[0];
  4097. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  4098. = Name.EndLocation.getRawEncoding();
  4099. return NameInfo;
  4100. case UnqualifiedId::IK_LiteralOperatorId:
  4101. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4102. Name.Identifier));
  4103. NameInfo.setLoc(Name.StartLocation);
  4104. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4105. return NameInfo;
  4106. case UnqualifiedId::IK_ConversionFunctionId: {
  4107. TypeSourceInfo *TInfo;
  4108. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4109. if (Ty.isNull())
  4110. return DeclarationNameInfo();
  4111. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4112. Context.getCanonicalType(Ty)));
  4113. NameInfo.setLoc(Name.StartLocation);
  4114. NameInfo.setNamedTypeInfo(TInfo);
  4115. return NameInfo;
  4116. }
  4117. case UnqualifiedId::IK_ConstructorName: {
  4118. TypeSourceInfo *TInfo;
  4119. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4120. if (Ty.isNull())
  4121. return DeclarationNameInfo();
  4122. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4123. Context.getCanonicalType(Ty)));
  4124. NameInfo.setLoc(Name.StartLocation);
  4125. NameInfo.setNamedTypeInfo(TInfo);
  4126. return NameInfo;
  4127. }
  4128. case UnqualifiedId::IK_ConstructorTemplateId: {
  4129. // In well-formed code, we can only have a constructor
  4130. // template-id that refers to the current context, so go there
  4131. // to find the actual type being constructed.
  4132. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4133. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4134. return DeclarationNameInfo();
  4135. // Determine the type of the class being constructed.
  4136. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4137. // FIXME: Check two things: that the template-id names the same type as
  4138. // CurClassType, and that the template-id does not occur when the name
  4139. // was qualified.
  4140. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4141. Context.getCanonicalType(CurClassType)));
  4142. NameInfo.setLoc(Name.StartLocation);
  4143. // FIXME: should we retrieve TypeSourceInfo?
  4144. NameInfo.setNamedTypeInfo(nullptr);
  4145. return NameInfo;
  4146. }
  4147. case UnqualifiedId::IK_DestructorName: {
  4148. TypeSourceInfo *TInfo;
  4149. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4150. if (Ty.isNull())
  4151. return DeclarationNameInfo();
  4152. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4153. Context.getCanonicalType(Ty)));
  4154. NameInfo.setLoc(Name.StartLocation);
  4155. NameInfo.setNamedTypeInfo(TInfo);
  4156. return NameInfo;
  4157. }
  4158. case UnqualifiedId::IK_TemplateId: {
  4159. TemplateName TName = Name.TemplateId->Template.get();
  4160. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4161. return Context.getNameForTemplate(TName, TNameLoc);
  4162. }
  4163. } // switch (Name.getKind())
  4164. llvm_unreachable("Unknown name kind");
  4165. }
  4166. static QualType getCoreType(QualType Ty) {
  4167. do {
  4168. if (Ty->isPointerType() || Ty->isReferenceType())
  4169. Ty = Ty->getPointeeType();
  4170. else if (Ty->isArrayType())
  4171. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4172. else
  4173. return Ty.withoutLocalFastQualifiers();
  4174. } while (true);
  4175. }
  4176. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4177. /// and Definition have "nearly" matching parameters. This heuristic is
  4178. /// used to improve diagnostics in the case where an out-of-line function
  4179. /// definition doesn't match any declaration within the class or namespace.
  4180. /// Also sets Params to the list of indices to the parameters that differ
  4181. /// between the declaration and the definition. If hasSimilarParameters
  4182. /// returns true and Params is empty, then all of the parameters match.
  4183. static bool hasSimilarParameters(ASTContext &Context,
  4184. FunctionDecl *Declaration,
  4185. FunctionDecl *Definition,
  4186. SmallVectorImpl<unsigned> &Params) {
  4187. Params.clear();
  4188. if (Declaration->param_size() != Definition->param_size())
  4189. return false;
  4190. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4191. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4192. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4193. // The parameter types are identical
  4194. if (Context.hasSameType(DefParamTy, DeclParamTy))
  4195. continue;
  4196. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4197. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4198. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4199. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4200. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4201. (DeclTyName && DeclTyName == DefTyName))
  4202. Params.push_back(Idx);
  4203. else // The two parameters aren't even close
  4204. return false;
  4205. }
  4206. return true;
  4207. }
  4208. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4209. /// declarator needs to be rebuilt in the current instantiation.
  4210. /// Any bits of declarator which appear before the name are valid for
  4211. /// consideration here. That's specifically the type in the decl spec
  4212. /// and the base type in any member-pointer chunks.
  4213. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4214. DeclarationName Name) {
  4215. // The types we specifically need to rebuild are:
  4216. // - typenames, typeofs, and decltypes
  4217. // - types which will become injected class names
  4218. // Of course, we also need to rebuild any type referencing such a
  4219. // type. It's safest to just say "dependent", but we call out a
  4220. // few cases here.
  4221. DeclSpec &DS = D.getMutableDeclSpec();
  4222. switch (DS.getTypeSpecType()) {
  4223. case DeclSpec::TST_typename:
  4224. case DeclSpec::TST_typeofType:
  4225. case DeclSpec::TST_underlyingType:
  4226. case DeclSpec::TST_atomic: {
  4227. // Grab the type from the parser.
  4228. TypeSourceInfo *TSI = nullptr;
  4229. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4230. if (T.isNull() || !T->isDependentType()) break;
  4231. // Make sure there's a type source info. This isn't really much
  4232. // of a waste; most dependent types should have type source info
  4233. // attached already.
  4234. if (!TSI)
  4235. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4236. // Rebuild the type in the current instantiation.
  4237. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4238. if (!TSI) return true;
  4239. // Store the new type back in the decl spec.
  4240. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4241. DS.UpdateTypeRep(LocType);
  4242. break;
  4243. }
  4244. case DeclSpec::TST_decltype:
  4245. case DeclSpec::TST_typeofExpr: {
  4246. Expr *E = DS.getRepAsExpr();
  4247. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4248. if (Result.isInvalid()) return true;
  4249. DS.UpdateExprRep(Result.get());
  4250. break;
  4251. }
  4252. default:
  4253. // Nothing to do for these decl specs.
  4254. break;
  4255. }
  4256. // It doesn't matter what order we do this in.
  4257. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4258. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4259. // The only type information in the declarator which can come
  4260. // before the declaration name is the base type of a member
  4261. // pointer.
  4262. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4263. continue;
  4264. // Rebuild the scope specifier in-place.
  4265. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4266. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4267. return true;
  4268. }
  4269. return false;
  4270. }
  4271. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4272. D.setFunctionDefinitionKind(FDK_Declaration);
  4273. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4274. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4275. Dcl && Dcl->getDeclContext()->isFileContext())
  4276. Dcl->setTopLevelDeclInObjCContainer();
  4277. return Dcl;
  4278. }
  4279. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4280. /// If T is the name of a class, then each of the following shall have a
  4281. /// name different from T:
  4282. /// - every static data member of class T;
  4283. /// - every member function of class T
  4284. /// - every member of class T that is itself a type;
  4285. /// \returns true if the declaration name violates these rules.
  4286. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4287. DeclarationNameInfo NameInfo) {
  4288. DeclarationName Name = NameInfo.getName();
  4289. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  4290. while (Record && Record->isAnonymousStructOrUnion())
  4291. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  4292. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  4293. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4294. return true;
  4295. }
  4296. return false;
  4297. }
  4298. /// \brief Diagnose a declaration whose declarator-id has the given
  4299. /// nested-name-specifier.
  4300. ///
  4301. /// \param SS The nested-name-specifier of the declarator-id.
  4302. ///
  4303. /// \param DC The declaration context to which the nested-name-specifier
  4304. /// resolves.
  4305. ///
  4306. /// \param Name The name of the entity being declared.
  4307. ///
  4308. /// \param Loc The location of the name of the entity being declared.
  4309. ///
  4310. /// \returns true if we cannot safely recover from this error, false otherwise.
  4311. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4312. DeclarationName Name,
  4313. SourceLocation Loc) {
  4314. DeclContext *Cur = CurContext;
  4315. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4316. Cur = Cur->getParent();
  4317. // If the user provided a superfluous scope specifier that refers back to the
  4318. // class in which the entity is already declared, diagnose and ignore it.
  4319. //
  4320. // class X {
  4321. // void X::f();
  4322. // };
  4323. //
  4324. // Note, it was once ill-formed to give redundant qualification in all
  4325. // contexts, but that rule was removed by DR482.
  4326. if (Cur->Equals(DC)) {
  4327. if (Cur->isRecord()) {
  4328. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4329. : diag::err_member_extra_qualification)
  4330. << Name << FixItHint::CreateRemoval(SS.getRange());
  4331. SS.clear();
  4332. } else {
  4333. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4334. }
  4335. return false;
  4336. }
  4337. // Check whether the qualifying scope encloses the scope of the original
  4338. // declaration.
  4339. if (!Cur->Encloses(DC)) {
  4340. if (Cur->isRecord())
  4341. Diag(Loc, diag::err_member_qualification)
  4342. << Name << SS.getRange();
  4343. else if (isa<TranslationUnitDecl>(DC))
  4344. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4345. << Name << SS.getRange();
  4346. else if (isa<FunctionDecl>(Cur))
  4347. Diag(Loc, diag::err_invalid_declarator_in_function)
  4348. << Name << SS.getRange();
  4349. else if (isa<BlockDecl>(Cur))
  4350. Diag(Loc, diag::err_invalid_declarator_in_block)
  4351. << Name << SS.getRange();
  4352. else
  4353. Diag(Loc, diag::err_invalid_declarator_scope)
  4354. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4355. return true;
  4356. }
  4357. if (Cur->isRecord()) {
  4358. // Cannot qualify members within a class.
  4359. Diag(Loc, diag::err_member_qualification)
  4360. << Name << SS.getRange();
  4361. SS.clear();
  4362. // C++ constructors and destructors with incorrect scopes can break
  4363. // our AST invariants by having the wrong underlying types. If
  4364. // that's the case, then drop this declaration entirely.
  4365. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4366. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4367. !Context.hasSameType(Name.getCXXNameType(),
  4368. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4369. return true;
  4370. return false;
  4371. }
  4372. // C++11 [dcl.meaning]p1:
  4373. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4374. // not begin with a decltype-specifer"
  4375. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4376. while (SpecLoc.getPrefix())
  4377. SpecLoc = SpecLoc.getPrefix();
  4378. if (dyn_cast_or_null<DecltypeType>(
  4379. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4380. Diag(Loc, diag::err_decltype_in_declarator)
  4381. << SpecLoc.getTypeLoc().getSourceRange();
  4382. return false;
  4383. }
  4384. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4385. MultiTemplateParamsArg TemplateParamLists) {
  4386. // TODO: consider using NameInfo for diagnostic.
  4387. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4388. DeclarationName Name = NameInfo.getName();
  4389. // All of these full declarators require an identifier. If it doesn't have
  4390. // one, the ParsedFreeStandingDeclSpec action should be used.
  4391. if (D.isDecompositionDeclarator()) {
  4392. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  4393. } else if (!Name) {
  4394. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4395. Diag(D.getDeclSpec().getLocStart(),
  4396. diag::err_declarator_need_ident)
  4397. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4398. return nullptr;
  4399. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4400. return nullptr;
  4401. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4402. // we find one that is.
  4403. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4404. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4405. S = S->getParent();
  4406. DeclContext *DC = CurContext;
  4407. if (D.getCXXScopeSpec().isInvalid())
  4408. D.setInvalidType();
  4409. else if (D.getCXXScopeSpec().isSet()) {
  4410. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4411. UPPC_DeclarationQualifier))
  4412. return nullptr;
  4413. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4414. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4415. if (!DC || isa<EnumDecl>(DC)) {
  4416. // If we could not compute the declaration context, it's because the
  4417. // declaration context is dependent but does not refer to a class,
  4418. // class template, or class template partial specialization. Complain
  4419. // and return early, to avoid the coming semantic disaster.
  4420. Diag(D.getIdentifierLoc(),
  4421. diag::err_template_qualified_declarator_no_match)
  4422. << D.getCXXScopeSpec().getScopeRep()
  4423. << D.getCXXScopeSpec().getRange();
  4424. return nullptr;
  4425. }
  4426. bool IsDependentContext = DC->isDependentContext();
  4427. if (!IsDependentContext &&
  4428. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4429. return nullptr;
  4430. // If a class is incomplete, do not parse entities inside it.
  4431. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4432. Diag(D.getIdentifierLoc(),
  4433. diag::err_member_def_undefined_record)
  4434. << Name << DC << D.getCXXScopeSpec().getRange();
  4435. return nullptr;
  4436. }
  4437. if (!D.getDeclSpec().isFriendSpecified()) {
  4438. if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
  4439. Name, D.getIdentifierLoc())) {
  4440. if (DC->isRecord())
  4441. return nullptr;
  4442. D.setInvalidType();
  4443. }
  4444. }
  4445. // Check whether we need to rebuild the type of the given
  4446. // declaration in the current instantiation.
  4447. if (EnteringContext && IsDependentContext &&
  4448. TemplateParamLists.size() != 0) {
  4449. ContextRAII SavedContext(*this, DC);
  4450. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4451. D.setInvalidType();
  4452. }
  4453. }
  4454. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4455. QualType R = TInfo->getType();
  4456. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4457. // If this is a typedef, we'll end up spewing multiple diagnostics.
  4458. // Just return early; it's safer. If this is a function, let the
  4459. // "constructor cannot have a return type" diagnostic handle it.
  4460. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4461. return nullptr;
  4462. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4463. UPPC_DeclarationType))
  4464. D.setInvalidType();
  4465. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4466. ForRedeclaration);
  4467. // See if this is a redefinition of a variable in the same scope.
  4468. if (!D.getCXXScopeSpec().isSet()) {
  4469. bool IsLinkageLookup = false;
  4470. bool CreateBuiltins = false;
  4471. // If the declaration we're planning to build will be a function
  4472. // or object with linkage, then look for another declaration with
  4473. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4474. //
  4475. // If the declaration we're planning to build will be declared with
  4476. // external linkage in the translation unit, create any builtin with
  4477. // the same name.
  4478. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4479. /* Do nothing*/;
  4480. else if (CurContext->isFunctionOrMethod() &&
  4481. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4482. R->isFunctionType())) {
  4483. IsLinkageLookup = true;
  4484. CreateBuiltins =
  4485. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4486. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4487. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4488. CreateBuiltins = true;
  4489. if (IsLinkageLookup)
  4490. Previous.clear(LookupRedeclarationWithLinkage);
  4491. LookupName(Previous, S, CreateBuiltins);
  4492. } else { // Something like "int foo::x;"
  4493. LookupQualifiedName(Previous, DC);
  4494. // C++ [dcl.meaning]p1:
  4495. // When the declarator-id is qualified, the declaration shall refer to a
  4496. // previously declared member of the class or namespace to which the
  4497. // qualifier refers (or, in the case of a namespace, of an element of the
  4498. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4499. // thereof; [...]
  4500. //
  4501. // Note that we already checked the context above, and that we do not have
  4502. // enough information to make sure that Previous contains the declaration
  4503. // we want to match. For example, given:
  4504. //
  4505. // class X {
  4506. // void f();
  4507. // void f(float);
  4508. // };
  4509. //
  4510. // void X::f(int) { } // ill-formed
  4511. //
  4512. // In this case, Previous will point to the overload set
  4513. // containing the two f's declared in X, but neither of them
  4514. // matches.
  4515. // C++ [dcl.meaning]p1:
  4516. // [...] the member shall not merely have been introduced by a
  4517. // using-declaration in the scope of the class or namespace nominated by
  4518. // the nested-name-specifier of the declarator-id.
  4519. RemoveUsingDecls(Previous);
  4520. }
  4521. if (Previous.isSingleResult() &&
  4522. Previous.getFoundDecl()->isTemplateParameter()) {
  4523. // Maybe we will complain about the shadowed template parameter.
  4524. if (!D.isInvalidType())
  4525. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4526. Previous.getFoundDecl());
  4527. // Just pretend that we didn't see the previous declaration.
  4528. Previous.clear();
  4529. }
  4530. // In C++, the previous declaration we find might be a tag type
  4531. // (class or enum). In this case, the new declaration will hide the
  4532. // tag type. Note that this does does not apply if we're declaring a
  4533. // typedef (C++ [dcl.typedef]p4).
  4534. if (Previous.isSingleTagDecl() &&
  4535. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
  4536. Previous.clear();
  4537. // Check that there are no default arguments other than in the parameters
  4538. // of a function declaration (C++ only).
  4539. if (getLangOpts().CPlusPlus)
  4540. CheckExtraCXXDefaultArguments(D);
  4541. if (D.getDeclSpec().isConceptSpecified()) {
  4542. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  4543. // applied only to the definition of a function template or variable
  4544. // template, declared in namespace scope
  4545. if (!TemplateParamLists.size()) {
  4546. Diag(D.getDeclSpec().getConceptSpecLoc(),
  4547. diag:: err_concept_wrong_decl_kind);
  4548. return nullptr;
  4549. }
  4550. if (!DC->getRedeclContext()->isFileContext()) {
  4551. Diag(D.getIdentifierLoc(),
  4552. diag::err_concept_decls_may_only_appear_in_namespace_scope);
  4553. return nullptr;
  4554. }
  4555. }
  4556. NamedDecl *New;
  4557. bool AddToScope = true;
  4558. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  4559. if (TemplateParamLists.size()) {
  4560. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  4561. return nullptr;
  4562. }
  4563. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  4564. } else if (R->isFunctionType()) {
  4565. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  4566. TemplateParamLists,
  4567. AddToScope);
  4568. } else {
  4569. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  4570. AddToScope);
  4571. }
  4572. if (!New)
  4573. return nullptr;
  4574. // If this has an identifier and is not a function template specialization,
  4575. // add it to the scope stack.
  4576. if (New->getDeclName() && AddToScope) {
  4577. // Only make a locally-scoped extern declaration visible if it is the first
  4578. // declaration of this entity. Qualified lookup for such an entity should
  4579. // only find this declaration if there is no visible declaration of it.
  4580. bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
  4581. PushOnScopeChains(New, S, AddToContext);
  4582. if (!AddToContext)
  4583. CurContext->addHiddenDecl(New);
  4584. }
  4585. if (isInOpenMPDeclareTargetContext())
  4586. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  4587. return New;
  4588. }
  4589. /// Helper method to turn variable array types into constant array
  4590. /// types in certain situations which would otherwise be errors (for
  4591. /// GCC compatibility).
  4592. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  4593. ASTContext &Context,
  4594. bool &SizeIsNegative,
  4595. llvm::APSInt &Oversized) {
  4596. // This method tries to turn a variable array into a constant
  4597. // array even when the size isn't an ICE. This is necessary
  4598. // for compatibility with code that depends on gcc's buggy
  4599. // constant expression folding, like struct {char x[(int)(char*)2];}
  4600. SizeIsNegative = false;
  4601. Oversized = 0;
  4602. if (T->isDependentType())
  4603. return QualType();
  4604. QualifierCollector Qs;
  4605. const Type *Ty = Qs.strip(T);
  4606. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  4607. QualType Pointee = PTy->getPointeeType();
  4608. QualType FixedType =
  4609. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  4610. Oversized);
  4611. if (FixedType.isNull()) return FixedType;
  4612. FixedType = Context.getPointerType(FixedType);
  4613. return Qs.apply(Context, FixedType);
  4614. }
  4615. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  4616. QualType Inner = PTy->getInnerType();
  4617. QualType FixedType =
  4618. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  4619. Oversized);
  4620. if (FixedType.isNull()) return FixedType;
  4621. FixedType = Context.getParenType(FixedType);
  4622. return Qs.apply(Context, FixedType);
  4623. }
  4624. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  4625. if (!VLATy)
  4626. return QualType();
  4627. // FIXME: We should probably handle this case
  4628. if (VLATy->getElementType()->isVariablyModifiedType())
  4629. return QualType();
  4630. llvm::APSInt Res;
  4631. if (!VLATy->getSizeExpr() ||
  4632. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  4633. return QualType();
  4634. // Check whether the array size is negative.
  4635. if (Res.isSigned() && Res.isNegative()) {
  4636. SizeIsNegative = true;
  4637. return QualType();
  4638. }
  4639. // Check whether the array is too large to be addressed.
  4640. unsigned ActiveSizeBits
  4641. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  4642. Res);
  4643. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  4644. Oversized = Res;
  4645. return QualType();
  4646. }
  4647. return Context.getConstantArrayType(VLATy->getElementType(),
  4648. Res, ArrayType::Normal, 0);
  4649. }
  4650. static void
  4651. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  4652. SrcTL = SrcTL.getUnqualifiedLoc();
  4653. DstTL = DstTL.getUnqualifiedLoc();
  4654. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  4655. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  4656. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  4657. DstPTL.getPointeeLoc());
  4658. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  4659. return;
  4660. }
  4661. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  4662. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  4663. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  4664. DstPTL.getInnerLoc());
  4665. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  4666. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  4667. return;
  4668. }
  4669. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  4670. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  4671. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  4672. TypeLoc DstElemTL = DstATL.getElementLoc();
  4673. DstElemTL.initializeFullCopy(SrcElemTL);
  4674. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  4675. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  4676. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  4677. }
  4678. /// Helper method to turn variable array types into constant array
  4679. /// types in certain situations which would otherwise be errors (for
  4680. /// GCC compatibility).
  4681. static TypeSourceInfo*
  4682. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  4683. ASTContext &Context,
  4684. bool &SizeIsNegative,
  4685. llvm::APSInt &Oversized) {
  4686. QualType FixedTy
  4687. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  4688. SizeIsNegative, Oversized);
  4689. if (FixedTy.isNull())
  4690. return nullptr;
  4691. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  4692. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  4693. FixedTInfo->getTypeLoc());
  4694. return FixedTInfo;
  4695. }
  4696. /// \brief Register the given locally-scoped extern "C" declaration so
  4697. /// that it can be found later for redeclarations. We include any extern "C"
  4698. /// declaration that is not visible in the translation unit here, not just
  4699. /// function-scope declarations.
  4700. void
  4701. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  4702. if (!getLangOpts().CPlusPlus &&
  4703. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  4704. // Don't need to track declarations in the TU in C.
  4705. return;
  4706. // Note that we have a locally-scoped external with this name.
  4707. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  4708. }
  4709. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  4710. // FIXME: We can have multiple results via __attribute__((overloadable)).
  4711. auto Result = Context.getExternCContextDecl()->lookup(Name);
  4712. return Result.empty() ? nullptr : *Result.begin();
  4713. }
  4714. /// \brief Diagnose function specifiers on a declaration of an identifier that
  4715. /// does not identify a function.
  4716. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  4717. // FIXME: We should probably indicate the identifier in question to avoid
  4718. // confusion for constructs like "virtual int a(), b;"
  4719. if (DS.isVirtualSpecified())
  4720. Diag(DS.getVirtualSpecLoc(),
  4721. diag::err_virtual_non_function);
  4722. if (DS.isExplicitSpecified())
  4723. Diag(DS.getExplicitSpecLoc(),
  4724. diag::err_explicit_non_function);
  4725. if (DS.isNoreturnSpecified())
  4726. Diag(DS.getNoreturnSpecLoc(),
  4727. diag::err_noreturn_non_function);
  4728. }
  4729. NamedDecl*
  4730. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  4731. TypeSourceInfo *TInfo, LookupResult &Previous) {
  4732. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  4733. if (D.getCXXScopeSpec().isSet()) {
  4734. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  4735. << D.getCXXScopeSpec().getRange();
  4736. D.setInvalidType();
  4737. // Pretend we didn't see the scope specifier.
  4738. DC = CurContext;
  4739. Previous.clear();
  4740. }
  4741. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  4742. if (D.getDeclSpec().isInlineSpecified())
  4743. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  4744. << getLangOpts().CPlusPlus1z;
  4745. if (D.getDeclSpec().isConstexprSpecified())
  4746. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  4747. << 1;
  4748. if (D.getDeclSpec().isConceptSpecified())
  4749. Diag(D.getDeclSpec().getConceptSpecLoc(),
  4750. diag::err_concept_wrong_decl_kind);
  4751. if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
  4752. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  4753. << D.getName().getSourceRange();
  4754. return nullptr;
  4755. }
  4756. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  4757. if (!NewTD) return nullptr;
  4758. // Handle attributes prior to checking for duplicates in MergeVarDecl
  4759. ProcessDeclAttributes(S, NewTD, D);
  4760. CheckTypedefForVariablyModifiedType(S, NewTD);
  4761. bool Redeclaration = D.isRedeclaration();
  4762. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  4763. D.setRedeclaration(Redeclaration);
  4764. return ND;
  4765. }
  4766. void
  4767. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  4768. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  4769. // then it shall have block scope.
  4770. // Note that variably modified types must be fixed before merging the decl so
  4771. // that redeclarations will match.
  4772. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  4773. QualType T = TInfo->getType();
  4774. if (T->isVariablyModifiedType()) {
  4775. getCurFunction()->setHasBranchProtectedScope();
  4776. if (S->getFnParent() == nullptr) {
  4777. bool SizeIsNegative;
  4778. llvm::APSInt Oversized;
  4779. TypeSourceInfo *FixedTInfo =
  4780. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  4781. SizeIsNegative,
  4782. Oversized);
  4783. if (FixedTInfo) {
  4784. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  4785. NewTD->setTypeSourceInfo(FixedTInfo);
  4786. } else {
  4787. if (SizeIsNegative)
  4788. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  4789. else if (T->isVariableArrayType())
  4790. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  4791. else if (Oversized.getBoolValue())
  4792. Diag(NewTD->getLocation(), diag::err_array_too_large)
  4793. << Oversized.toString(10);
  4794. else
  4795. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  4796. NewTD->setInvalidDecl();
  4797. }
  4798. }
  4799. }
  4800. }
  4801. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  4802. /// declares a typedef-name, either using the 'typedef' type specifier or via
  4803. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  4804. NamedDecl*
  4805. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  4806. LookupResult &Previous, bool &Redeclaration) {
  4807. // Merge the decl with the existing one if appropriate. If the decl is
  4808. // in an outer scope, it isn't the same thing.
  4809. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  4810. /*AllowInlineNamespace*/false);
  4811. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  4812. if (!Previous.empty()) {
  4813. Redeclaration = true;
  4814. MergeTypedefNameDecl(S, NewTD, Previous);
  4815. }
  4816. // If this is the C FILE type, notify the AST context.
  4817. if (IdentifierInfo *II = NewTD->getIdentifier())
  4818. if (!NewTD->isInvalidDecl() &&
  4819. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  4820. if (II->isStr("FILE"))
  4821. Context.setFILEDecl(NewTD);
  4822. else if (II->isStr("jmp_buf"))
  4823. Context.setjmp_bufDecl(NewTD);
  4824. else if (II->isStr("sigjmp_buf"))
  4825. Context.setsigjmp_bufDecl(NewTD);
  4826. else if (II->isStr("ucontext_t"))
  4827. Context.setucontext_tDecl(NewTD);
  4828. }
  4829. return NewTD;
  4830. }
  4831. /// \brief Determines whether the given declaration is an out-of-scope
  4832. /// previous declaration.
  4833. ///
  4834. /// This routine should be invoked when name lookup has found a
  4835. /// previous declaration (PrevDecl) that is not in the scope where a
  4836. /// new declaration by the same name is being introduced. If the new
  4837. /// declaration occurs in a local scope, previous declarations with
  4838. /// linkage may still be considered previous declarations (C99
  4839. /// 6.2.2p4-5, C++ [basic.link]p6).
  4840. ///
  4841. /// \param PrevDecl the previous declaration found by name
  4842. /// lookup
  4843. ///
  4844. /// \param DC the context in which the new declaration is being
  4845. /// declared.
  4846. ///
  4847. /// \returns true if PrevDecl is an out-of-scope previous declaration
  4848. /// for a new delcaration with the same name.
  4849. static bool
  4850. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  4851. ASTContext &Context) {
  4852. if (!PrevDecl)
  4853. return false;
  4854. if (!PrevDecl->hasLinkage())
  4855. return false;
  4856. if (Context.getLangOpts().CPlusPlus) {
  4857. // C++ [basic.link]p6:
  4858. // If there is a visible declaration of an entity with linkage
  4859. // having the same name and type, ignoring entities declared
  4860. // outside the innermost enclosing namespace scope, the block
  4861. // scope declaration declares that same entity and receives the
  4862. // linkage of the previous declaration.
  4863. DeclContext *OuterContext = DC->getRedeclContext();
  4864. if (!OuterContext->isFunctionOrMethod())
  4865. // This rule only applies to block-scope declarations.
  4866. return false;
  4867. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  4868. if (PrevOuterContext->isRecord())
  4869. // We found a member function: ignore it.
  4870. return false;
  4871. // Find the innermost enclosing namespace for the new and
  4872. // previous declarations.
  4873. OuterContext = OuterContext->getEnclosingNamespaceContext();
  4874. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  4875. // The previous declaration is in a different namespace, so it
  4876. // isn't the same function.
  4877. if (!OuterContext->Equals(PrevOuterContext))
  4878. return false;
  4879. }
  4880. return true;
  4881. }
  4882. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  4883. CXXScopeSpec &SS = D.getCXXScopeSpec();
  4884. if (!SS.isSet()) return;
  4885. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  4886. }
  4887. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  4888. QualType type = decl->getType();
  4889. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  4890. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  4891. // Various kinds of declaration aren't allowed to be __autoreleasing.
  4892. unsigned kind = -1U;
  4893. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  4894. if (var->hasAttr<BlocksAttr>())
  4895. kind = 0; // __block
  4896. else if (!var->hasLocalStorage())
  4897. kind = 1; // global
  4898. } else if (isa<ObjCIvarDecl>(decl)) {
  4899. kind = 3; // ivar
  4900. } else if (isa<FieldDecl>(decl)) {
  4901. kind = 2; // field
  4902. }
  4903. if (kind != -1U) {
  4904. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  4905. << kind;
  4906. }
  4907. } else if (lifetime == Qualifiers::OCL_None) {
  4908. // Try to infer lifetime.
  4909. if (!type->isObjCLifetimeType())
  4910. return false;
  4911. lifetime = type->getObjCARCImplicitLifetime();
  4912. type = Context.getLifetimeQualifiedType(type, lifetime);
  4913. decl->setType(type);
  4914. }
  4915. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  4916. // Thread-local variables cannot have lifetime.
  4917. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  4918. var->getTLSKind()) {
  4919. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  4920. << var->getType();
  4921. return true;
  4922. }
  4923. }
  4924. return false;
  4925. }
  4926. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  4927. // Ensure that an auto decl is deduced otherwise the checks below might cache
  4928. // the wrong linkage.
  4929. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  4930. // 'weak' only applies to declarations with external linkage.
  4931. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  4932. if (!ND.isExternallyVisible()) {
  4933. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  4934. ND.dropAttr<WeakAttr>();
  4935. }
  4936. }
  4937. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  4938. if (ND.isExternallyVisible()) {
  4939. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  4940. ND.dropAttr<WeakRefAttr>();
  4941. ND.dropAttr<AliasAttr>();
  4942. }
  4943. }
  4944. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  4945. if (VD->hasInit()) {
  4946. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  4947. assert(VD->isThisDeclarationADefinition() &&
  4948. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  4949. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  4950. VD->dropAttr<AliasAttr>();
  4951. }
  4952. }
  4953. }
  4954. // 'selectany' only applies to externally visible variable declarations.
  4955. // It does not apply to functions.
  4956. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  4957. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  4958. S.Diag(Attr->getLocation(),
  4959. diag::err_attribute_selectany_non_extern_data);
  4960. ND.dropAttr<SelectAnyAttr>();
  4961. }
  4962. }
  4963. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  4964. // dll attributes require external linkage. Static locals may have external
  4965. // linkage but still cannot be explicitly imported or exported.
  4966. auto *VD = dyn_cast<VarDecl>(&ND);
  4967. if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
  4968. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  4969. << &ND << Attr;
  4970. ND.setInvalidDecl();
  4971. }
  4972. }
  4973. // Virtual functions cannot be marked as 'notail'.
  4974. if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
  4975. if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
  4976. if (MD->isVirtual()) {
  4977. S.Diag(ND.getLocation(),
  4978. diag::err_invalid_attribute_on_virtual_function)
  4979. << Attr;
  4980. ND.dropAttr<NotTailCalledAttr>();
  4981. }
  4982. }
  4983. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  4984. NamedDecl *NewDecl,
  4985. bool IsSpecialization,
  4986. bool IsDefinition) {
  4987. if (OldDecl->isInvalidDecl())
  4988. return;
  4989. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  4990. OldDecl = OldTD->getTemplatedDecl();
  4991. if (!IsSpecialization)
  4992. IsDefinition = false;
  4993. }
  4994. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
  4995. NewDecl = NewTD->getTemplatedDecl();
  4996. if (!OldDecl || !NewDecl)
  4997. return;
  4998. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  4999. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5000. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5001. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5002. // dllimport and dllexport are inheritable attributes so we have to exclude
  5003. // inherited attribute instances.
  5004. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5005. (NewExportAttr && !NewExportAttr->isInherited());
  5006. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5007. // the only exception being explicit specializations.
  5008. // Implicitly generated declarations are also excluded for now because there
  5009. // is no other way to switch these to use dllimport or dllexport.
  5010. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5011. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5012. // Allow with a warning for free functions and global variables.
  5013. bool JustWarn = false;
  5014. if (!OldDecl->isCXXClassMember()) {
  5015. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5016. if (VD && !VD->getDescribedVarTemplate())
  5017. JustWarn = true;
  5018. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5019. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5020. JustWarn = true;
  5021. }
  5022. // We cannot change a declaration that's been used because IR has already
  5023. // been emitted. Dllimported functions will still work though (modulo
  5024. // address equality) as they can use the thunk.
  5025. if (OldDecl->isUsed())
  5026. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5027. JustWarn = false;
  5028. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5029. : diag::err_attribute_dll_redeclaration;
  5030. S.Diag(NewDecl->getLocation(), DiagID)
  5031. << NewDecl
  5032. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5033. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5034. if (!JustWarn) {
  5035. NewDecl->setInvalidDecl();
  5036. return;
  5037. }
  5038. }
  5039. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5040. // exceptions being inline function definitions, local extern declarations,
  5041. // qualified friend declarations or special MSVC extension: in the last case,
  5042. // the declaration is treated as if it were marked dllexport.
  5043. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5044. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5045. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5046. // Ignore static data because out-of-line definitions are diagnosed
  5047. // separately.
  5048. IsStaticDataMember = VD->isStaticDataMember();
  5049. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5050. VarDecl::DeclarationOnly;
  5051. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5052. IsInline = FD->isInlined();
  5053. IsQualifiedFriend = FD->getQualifier() &&
  5054. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5055. }
  5056. if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
  5057. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5058. if (IsMicrosoft && IsDefinition) {
  5059. S.Diag(NewDecl->getLocation(),
  5060. diag::warn_redeclaration_without_import_attribute)
  5061. << NewDecl;
  5062. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5063. NewDecl->dropAttr<DLLImportAttr>();
  5064. NewDecl->addAttr(::new (S.Context) DLLExportAttr(
  5065. NewImportAttr->getRange(), S.Context,
  5066. NewImportAttr->getSpellingListIndex()));
  5067. } else {
  5068. S.Diag(NewDecl->getLocation(),
  5069. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5070. << NewDecl << OldImportAttr;
  5071. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5072. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5073. OldDecl->dropAttr<DLLImportAttr>();
  5074. NewDecl->dropAttr<DLLImportAttr>();
  5075. }
  5076. } else if (IsInline && OldImportAttr && !IsMicrosoft) {
  5077. // In MinGW, seeing a function declared inline drops the dllimport attribute.
  5078. OldDecl->dropAttr<DLLImportAttr>();
  5079. NewDecl->dropAttr<DLLImportAttr>();
  5080. S.Diag(NewDecl->getLocation(),
  5081. diag::warn_dllimport_dropped_from_inline_function)
  5082. << NewDecl << OldImportAttr;
  5083. }
  5084. }
  5085. /// Given that we are within the definition of the given function,
  5086. /// will that definition behave like C99's 'inline', where the
  5087. /// definition is discarded except for optimization purposes?
  5088. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  5089. // Try to avoid calling GetGVALinkageForFunction.
  5090. // All cases of this require the 'inline' keyword.
  5091. if (!FD->isInlined()) return false;
  5092. // This is only possible in C++ with the gnu_inline attribute.
  5093. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  5094. return false;
  5095. // Okay, go ahead and call the relatively-more-expensive function.
  5096. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  5097. }
  5098. /// Determine whether a variable is extern "C" prior to attaching
  5099. /// an initializer. We can't just call isExternC() here, because that
  5100. /// will also compute and cache whether the declaration is externally
  5101. /// visible, which might change when we attach the initializer.
  5102. ///
  5103. /// This can only be used if the declaration is known to not be a
  5104. /// redeclaration of an internal linkage declaration.
  5105. ///
  5106. /// For instance:
  5107. ///
  5108. /// auto x = []{};
  5109. ///
  5110. /// Attaching the initializer here makes this declaration not externally
  5111. /// visible, because its type has internal linkage.
  5112. ///
  5113. /// FIXME: This is a hack.
  5114. template<typename T>
  5115. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  5116. if (S.getLangOpts().CPlusPlus) {
  5117. // In C++, the overloadable attribute negates the effects of extern "C".
  5118. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  5119. return false;
  5120. // So do CUDA's host/device attributes.
  5121. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  5122. D->template hasAttr<CUDAHostAttr>()))
  5123. return false;
  5124. }
  5125. return D->isExternC();
  5126. }
  5127. static bool shouldConsiderLinkage(const VarDecl *VD) {
  5128. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  5129. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
  5130. return VD->hasExternalStorage();
  5131. if (DC->isFileContext())
  5132. return true;
  5133. if (DC->isRecord())
  5134. return false;
  5135. llvm_unreachable("Unexpected context");
  5136. }
  5137. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  5138. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  5139. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  5140. isa<OMPDeclareReductionDecl>(DC))
  5141. return true;
  5142. if (DC->isRecord())
  5143. return false;
  5144. llvm_unreachable("Unexpected context");
  5145. }
  5146. static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
  5147. AttributeList::Kind Kind) {
  5148. for (const AttributeList *L = AttrList; L; L = L->getNext())
  5149. if (L->getKind() == Kind)
  5150. return true;
  5151. return false;
  5152. }
  5153. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  5154. AttributeList::Kind Kind) {
  5155. // Check decl attributes on the DeclSpec.
  5156. if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
  5157. return true;
  5158. // Walk the declarator structure, checking decl attributes that were in a type
  5159. // position to the decl itself.
  5160. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  5161. if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
  5162. return true;
  5163. }
  5164. // Finally, check attributes on the decl itself.
  5165. return hasParsedAttr(S, PD.getAttributes(), Kind);
  5166. }
  5167. /// Adjust the \c DeclContext for a function or variable that might be a
  5168. /// function-local external declaration.
  5169. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  5170. if (!DC->isFunctionOrMethod())
  5171. return false;
  5172. // If this is a local extern function or variable declared within a function
  5173. // template, don't add it into the enclosing namespace scope until it is
  5174. // instantiated; it might have a dependent type right now.
  5175. if (DC->isDependentContext())
  5176. return true;
  5177. // C++11 [basic.link]p7:
  5178. // When a block scope declaration of an entity with linkage is not found to
  5179. // refer to some other declaration, then that entity is a member of the
  5180. // innermost enclosing namespace.
  5181. //
  5182. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  5183. // semantically-enclosing namespace, not a lexically-enclosing one.
  5184. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  5185. DC = DC->getParent();
  5186. return true;
  5187. }
  5188. /// \brief Returns true if given declaration has external C language linkage.
  5189. static bool isDeclExternC(const Decl *D) {
  5190. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  5191. return FD->isExternC();
  5192. if (const auto *VD = dyn_cast<VarDecl>(D))
  5193. return VD->isExternC();
  5194. llvm_unreachable("Unknown type of decl!");
  5195. }
  5196. NamedDecl *Sema::ActOnVariableDeclarator(
  5197. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  5198. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  5199. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  5200. QualType R = TInfo->getType();
  5201. DeclarationName Name = GetNameForDeclarator(D).getName();
  5202. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5203. if (D.isDecompositionDeclarator()) {
  5204. AddToScope = false;
  5205. // Take the name of the first declarator as our name for diagnostic
  5206. // purposes.
  5207. auto &Decomp = D.getDecompositionDeclarator();
  5208. if (!Decomp.bindings().empty()) {
  5209. II = Decomp.bindings()[0].Name;
  5210. Name = II;
  5211. }
  5212. } else if (!II) {
  5213. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
  5214. << Name;
  5215. return nullptr;
  5216. }
  5217. if (getLangOpts().OpenCL) {
  5218. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  5219. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  5220. // argument.
  5221. if (R->isImageType() || R->isPipeType()) {
  5222. Diag(D.getIdentifierLoc(),
  5223. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  5224. << R;
  5225. D.setInvalidType();
  5226. return nullptr;
  5227. }
  5228. // OpenCL v1.2 s6.9.r:
  5229. // The event type cannot be used to declare a program scope variable.
  5230. // OpenCL v2.0 s6.9.q:
  5231. // The clk_event_t and reserve_id_t types cannot be declared in program scope.
  5232. if (NULL == S->getParent()) {
  5233. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  5234. Diag(D.getIdentifierLoc(),
  5235. diag::err_invalid_type_for_program_scope_var) << R;
  5236. D.setInvalidType();
  5237. return nullptr;
  5238. }
  5239. }
  5240. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  5241. QualType NR = R;
  5242. while (NR->isPointerType()) {
  5243. if (NR->isFunctionPointerType()) {
  5244. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
  5245. D.setInvalidType();
  5246. break;
  5247. }
  5248. NR = NR->getPointeeType();
  5249. }
  5250. if (!getOpenCLOptions().cl_khr_fp16) {
  5251. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5252. // half array type (unless the cl_khr_fp16 extension is enabled).
  5253. if (Context.getBaseElementType(R)->isHalfType()) {
  5254. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5255. D.setInvalidType();
  5256. }
  5257. }
  5258. // OpenCL v1.2 s6.9.b p4:
  5259. // The sampler type cannot be used with the __local and __global address
  5260. // space qualifiers.
  5261. if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
  5262. R.getAddressSpace() == LangAS::opencl_global)) {
  5263. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5264. }
  5265. // OpenCL v1.2 s6.9.r:
  5266. // The event type cannot be used with the __local, __constant and __global
  5267. // address space qualifiers.
  5268. if (R->isEventT()) {
  5269. if (R.getAddressSpace()) {
  5270. Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
  5271. D.setInvalidType();
  5272. }
  5273. }
  5274. }
  5275. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  5276. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  5277. // dllimport globals without explicit storage class are treated as extern. We
  5278. // have to change the storage class this early to get the right DeclContext.
  5279. if (SC == SC_None && !DC->isRecord() &&
  5280. hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
  5281. !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
  5282. SC = SC_Extern;
  5283. DeclContext *OriginalDC = DC;
  5284. bool IsLocalExternDecl = SC == SC_Extern &&
  5285. adjustContextForLocalExternDecl(DC);
  5286. if (SCSpec == DeclSpec::SCS_mutable) {
  5287. // mutable can only appear on non-static class members, so it's always
  5288. // an error here
  5289. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5290. D.setInvalidType();
  5291. SC = SC_None;
  5292. }
  5293. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5294. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5295. D.getDeclSpec().getStorageClassSpecLoc())) {
  5296. // In C++11, the 'register' storage class specifier is deprecated.
  5297. // Suppress the warning in system macros, it's used in macros in some
  5298. // popular C system headers, such as in glibc's htonl() macro.
  5299. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5300. getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
  5301. : diag::warn_deprecated_register)
  5302. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5303. }
  5304. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5305. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5306. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5307. // appear in the declaration specifiers in an external declaration.
  5308. // Global Register+Asm is a GNU extension we support.
  5309. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5310. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5311. D.setInvalidType();
  5312. }
  5313. }
  5314. bool IsExplicitSpecialization = false;
  5315. bool IsVariableTemplateSpecialization = false;
  5316. bool IsPartialSpecialization = false;
  5317. bool IsVariableTemplate = false;
  5318. VarDecl *NewVD = nullptr;
  5319. VarTemplateDecl *NewTemplate = nullptr;
  5320. TemplateParameterList *TemplateParams = nullptr;
  5321. if (!getLangOpts().CPlusPlus) {
  5322. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5323. D.getIdentifierLoc(), II,
  5324. R, TInfo, SC);
  5325. if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
  5326. ParsingInitForAutoVars.insert(NewVD);
  5327. if (D.isInvalidType())
  5328. NewVD->setInvalidDecl();
  5329. } else {
  5330. bool Invalid = false;
  5331. if (DC->isRecord() && !CurContext->isRecord()) {
  5332. // This is an out-of-line definition of a static data member.
  5333. switch (SC) {
  5334. case SC_None:
  5335. break;
  5336. case SC_Static:
  5337. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5338. diag::err_static_out_of_line)
  5339. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5340. break;
  5341. case SC_Auto:
  5342. case SC_Register:
  5343. case SC_Extern:
  5344. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5345. // to names of variables declared in a block or to function parameters.
  5346. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5347. // of class members
  5348. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5349. diag::err_storage_class_for_static_member)
  5350. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5351. break;
  5352. case SC_PrivateExtern:
  5353. llvm_unreachable("C storage class in c++!");
  5354. }
  5355. }
  5356. if (SC == SC_Static && CurContext->isRecord()) {
  5357. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5358. if (RD->isLocalClass())
  5359. Diag(D.getIdentifierLoc(),
  5360. diag::err_static_data_member_not_allowed_in_local_class)
  5361. << Name << RD->getDeclName();
  5362. // C++98 [class.union]p1: If a union contains a static data member,
  5363. // the program is ill-formed. C++11 drops this restriction.
  5364. if (RD->isUnion())
  5365. Diag(D.getIdentifierLoc(),
  5366. getLangOpts().CPlusPlus11
  5367. ? diag::warn_cxx98_compat_static_data_member_in_union
  5368. : diag::ext_static_data_member_in_union) << Name;
  5369. // We conservatively disallow static data members in anonymous structs.
  5370. else if (!RD->getDeclName())
  5371. Diag(D.getIdentifierLoc(),
  5372. diag::err_static_data_member_not_allowed_in_anon_struct)
  5373. << Name << RD->isUnion();
  5374. }
  5375. }
  5376. // Match up the template parameter lists with the scope specifier, then
  5377. // determine whether we have a template or a template specialization.
  5378. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5379. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  5380. D.getCXXScopeSpec(),
  5381. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  5382. ? D.getName().TemplateId
  5383. : nullptr,
  5384. TemplateParamLists,
  5385. /*never a friend*/ false, IsExplicitSpecialization, Invalid);
  5386. if (TemplateParams) {
  5387. if (!TemplateParams->size() &&
  5388. D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  5389. // There is an extraneous 'template<>' for this variable. Complain
  5390. // about it, but allow the declaration of the variable.
  5391. Diag(TemplateParams->getTemplateLoc(),
  5392. diag::err_template_variable_noparams)
  5393. << II
  5394. << SourceRange(TemplateParams->getTemplateLoc(),
  5395. TemplateParams->getRAngleLoc());
  5396. TemplateParams = nullptr;
  5397. } else {
  5398. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  5399. // This is an explicit specialization or a partial specialization.
  5400. // FIXME: Check that we can declare a specialization here.
  5401. IsVariableTemplateSpecialization = true;
  5402. IsPartialSpecialization = TemplateParams->size() > 0;
  5403. } else { // if (TemplateParams->size() > 0)
  5404. // This is a template declaration.
  5405. IsVariableTemplate = true;
  5406. // Check that we can declare a template here.
  5407. if (CheckTemplateDeclScope(S, TemplateParams))
  5408. return nullptr;
  5409. // Only C++1y supports variable templates (N3651).
  5410. Diag(D.getIdentifierLoc(),
  5411. getLangOpts().CPlusPlus14
  5412. ? diag::warn_cxx11_compat_variable_template
  5413. : diag::ext_variable_template);
  5414. }
  5415. }
  5416. } else {
  5417. assert(
  5418. (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
  5419. "should have a 'template<>' for this decl");
  5420. }
  5421. if (IsVariableTemplateSpecialization) {
  5422. SourceLocation TemplateKWLoc =
  5423. TemplateParamLists.size() > 0
  5424. ? TemplateParamLists[0]->getTemplateLoc()
  5425. : SourceLocation();
  5426. DeclResult Res = ActOnVarTemplateSpecialization(
  5427. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5428. IsPartialSpecialization);
  5429. if (Res.isInvalid())
  5430. return nullptr;
  5431. NewVD = cast<VarDecl>(Res.get());
  5432. AddToScope = false;
  5433. } else if (D.isDecompositionDeclarator()) {
  5434. NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
  5435. D.getIdentifierLoc(), R, TInfo, SC,
  5436. Bindings);
  5437. } else
  5438. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5439. D.getIdentifierLoc(), II, R, TInfo, SC);
  5440. // If this is supposed to be a variable template, create it as such.
  5441. if (IsVariableTemplate) {
  5442. NewTemplate =
  5443. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5444. TemplateParams, NewVD);
  5445. NewVD->setDescribedVarTemplate(NewTemplate);
  5446. }
  5447. // If this decl has an auto type in need of deduction, make a note of the
  5448. // Decl so we can diagnose uses of it in its own initializer.
  5449. if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
  5450. ParsingInitForAutoVars.insert(NewVD);
  5451. if (D.isInvalidType() || Invalid) {
  5452. NewVD->setInvalidDecl();
  5453. if (NewTemplate)
  5454. NewTemplate->setInvalidDecl();
  5455. }
  5456. SetNestedNameSpecifier(NewVD, D);
  5457. // If we have any template parameter lists that don't directly belong to
  5458. // the variable (matching the scope specifier), store them.
  5459. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5460. if (TemplateParamLists.size() > VDTemplateParamLists)
  5461. NewVD->setTemplateParameterListsInfo(
  5462. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  5463. if (D.getDeclSpec().isConstexprSpecified()) {
  5464. NewVD->setConstexpr(true);
  5465. // C++1z [dcl.spec.constexpr]p1:
  5466. // A static data member declared with the constexpr specifier is
  5467. // implicitly an inline variable.
  5468. if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
  5469. NewVD->setImplicitlyInline();
  5470. }
  5471. if (D.getDeclSpec().isConceptSpecified()) {
  5472. if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
  5473. VTD->setConcept();
  5474. // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
  5475. // be declared with the thread_local, inline, friend, or constexpr
  5476. // specifiers, [...]
  5477. if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
  5478. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5479. diag::err_concept_decl_invalid_specifiers)
  5480. << 0 << 0;
  5481. NewVD->setInvalidDecl(true);
  5482. }
  5483. if (D.getDeclSpec().isConstexprSpecified()) {
  5484. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  5485. diag::err_concept_decl_invalid_specifiers)
  5486. << 0 << 3;
  5487. NewVD->setInvalidDecl(true);
  5488. }
  5489. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  5490. // applied only to the definition of a function template or variable
  5491. // template, declared in namespace scope.
  5492. if (IsVariableTemplateSpecialization) {
  5493. Diag(D.getDeclSpec().getConceptSpecLoc(),
  5494. diag::err_concept_specified_specialization)
  5495. << (IsPartialSpecialization ? 2 : 1);
  5496. }
  5497. // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
  5498. // following restrictions:
  5499. // - The declared type shall have the type bool.
  5500. if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
  5501. !NewVD->isInvalidDecl()) {
  5502. Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
  5503. NewVD->setInvalidDecl(true);
  5504. }
  5505. }
  5506. }
  5507. if (D.getDeclSpec().isInlineSpecified()) {
  5508. if (!getLangOpts().CPlusPlus) {
  5509. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5510. << 0;
  5511. } else if (CurContext->isFunctionOrMethod()) {
  5512. // 'inline' is not allowed on block scope variable declaration.
  5513. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5514. diag::err_inline_declaration_block_scope) << Name
  5515. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  5516. } else {
  5517. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5518. getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
  5519. : diag::ext_inline_variable);
  5520. NewVD->setInlineSpecified();
  5521. }
  5522. }
  5523. // Set the lexical context. If the declarator has a C++ scope specifier, the
  5524. // lexical context will be different from the semantic context.
  5525. NewVD->setLexicalDeclContext(CurContext);
  5526. if (NewTemplate)
  5527. NewTemplate->setLexicalDeclContext(CurContext);
  5528. if (IsLocalExternDecl) {
  5529. if (D.isDecompositionDeclarator())
  5530. for (auto *B : Bindings)
  5531. B->setLocalExternDecl();
  5532. else
  5533. NewVD->setLocalExternDecl();
  5534. }
  5535. bool EmitTLSUnsupportedError = false;
  5536. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  5537. // C++11 [dcl.stc]p4:
  5538. // When thread_local is applied to a variable of block scope the
  5539. // storage-class-specifier static is implied if it does not appear
  5540. // explicitly.
  5541. // Core issue: 'static' is not implied if the variable is declared
  5542. // 'extern'.
  5543. if (NewVD->hasLocalStorage() &&
  5544. (SCSpec != DeclSpec::SCS_unspecified ||
  5545. TSCS != DeclSpec::TSCS_thread_local ||
  5546. !DC->isFunctionOrMethod()))
  5547. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5548. diag::err_thread_non_global)
  5549. << DeclSpec::getSpecifierName(TSCS);
  5550. else if (!Context.getTargetInfo().isTLSSupported()) {
  5551. if (getLangOpts().CUDA) {
  5552. // Postpone error emission until we've collected attributes required to
  5553. // figure out whether it's a host or device variable and whether the
  5554. // error should be ignored.
  5555. EmitTLSUnsupportedError = true;
  5556. // We still need to mark the variable as TLS so it shows up in AST with
  5557. // proper storage class for other tools to use even if we're not going
  5558. // to emit any code for it.
  5559. NewVD->setTSCSpec(TSCS);
  5560. } else
  5561. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5562. diag::err_thread_unsupported);
  5563. } else
  5564. NewVD->setTSCSpec(TSCS);
  5565. }
  5566. // C99 6.7.4p3
  5567. // An inline definition of a function with external linkage shall
  5568. // not contain a definition of a modifiable object with static or
  5569. // thread storage duration...
  5570. // We only apply this when the function is required to be defined
  5571. // elsewhere, i.e. when the function is not 'extern inline'. Note
  5572. // that a local variable with thread storage duration still has to
  5573. // be marked 'static'. Also note that it's possible to get these
  5574. // semantics in C++ using __attribute__((gnu_inline)).
  5575. if (SC == SC_Static && S->getFnParent() != nullptr &&
  5576. !NewVD->getType().isConstQualified()) {
  5577. FunctionDecl *CurFD = getCurFunctionDecl();
  5578. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  5579. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5580. diag::warn_static_local_in_extern_inline);
  5581. MaybeSuggestAddingStaticToDecl(CurFD);
  5582. }
  5583. }
  5584. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5585. if (IsVariableTemplateSpecialization)
  5586. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5587. << (IsPartialSpecialization ? 1 : 0)
  5588. << FixItHint::CreateRemoval(
  5589. D.getDeclSpec().getModulePrivateSpecLoc());
  5590. else if (IsExplicitSpecialization)
  5591. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5592. << 2
  5593. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5594. else if (NewVD->hasLocalStorage())
  5595. Diag(NewVD->getLocation(), diag::err_module_private_local)
  5596. << 0 << NewVD->getDeclName()
  5597. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5598. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5599. else {
  5600. NewVD->setModulePrivate();
  5601. if (NewTemplate)
  5602. NewTemplate->setModulePrivate();
  5603. for (auto *B : Bindings)
  5604. B->setModulePrivate();
  5605. }
  5606. }
  5607. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5608. ProcessDeclAttributes(S, NewVD, D);
  5609. if (getLangOpts().CUDA) {
  5610. if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
  5611. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5612. diag::err_thread_unsupported);
  5613. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  5614. // storage [duration]."
  5615. if (SC == SC_None && S->getFnParent() != nullptr &&
  5616. (NewVD->hasAttr<CUDASharedAttr>() ||
  5617. NewVD->hasAttr<CUDAConstantAttr>())) {
  5618. NewVD->setStorageClass(SC_Static);
  5619. }
  5620. }
  5621. // Ensure that dllimport globals without explicit storage class are treated as
  5622. // extern. The storage class is set above using parsed attributes. Now we can
  5623. // check the VarDecl itself.
  5624. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  5625. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  5626. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  5627. // In auto-retain/release, infer strong retension for variables of
  5628. // retainable type.
  5629. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  5630. NewVD->setInvalidDecl();
  5631. // Handle GNU asm-label extension (encoded as an attribute).
  5632. if (Expr *E = (Expr*)D.getAsmLabel()) {
  5633. // The parser guarantees this is a string.
  5634. StringLiteral *SE = cast<StringLiteral>(E);
  5635. StringRef Label = SE->getString();
  5636. if (S->getFnParent() != nullptr) {
  5637. switch (SC) {
  5638. case SC_None:
  5639. case SC_Auto:
  5640. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  5641. break;
  5642. case SC_Register:
  5643. // Local Named register
  5644. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  5645. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  5646. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5647. break;
  5648. case SC_Static:
  5649. case SC_Extern:
  5650. case SC_PrivateExtern:
  5651. break;
  5652. }
  5653. } else if (SC == SC_Register) {
  5654. // Global Named register
  5655. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  5656. const auto &TI = Context.getTargetInfo();
  5657. bool HasSizeMismatch;
  5658. if (!TI.isValidGCCRegisterName(Label))
  5659. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5660. else if (!TI.validateGlobalRegisterVariable(Label,
  5661. Context.getTypeSize(R),
  5662. HasSizeMismatch))
  5663. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  5664. else if (HasSizeMismatch)
  5665. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  5666. }
  5667. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  5668. Diag(D.getLocStart(), diag::err_asm_bad_register_type);
  5669. NewVD->setInvalidDecl(true);
  5670. }
  5671. }
  5672. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  5673. Context, Label, 0));
  5674. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  5675. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  5676. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  5677. if (I != ExtnameUndeclaredIdentifiers.end()) {
  5678. if (isDeclExternC(NewVD)) {
  5679. NewVD->addAttr(I->second);
  5680. ExtnameUndeclaredIdentifiers.erase(I);
  5681. } else
  5682. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  5683. << /*Variable*/1 << NewVD;
  5684. }
  5685. }
  5686. // Diagnose shadowed variables before filtering for scope.
  5687. if (D.getCXXScopeSpec().isEmpty())
  5688. CheckShadow(S, NewVD, Previous);
  5689. // Don't consider existing declarations that are in a different
  5690. // scope and are out-of-semantic-context declarations (if the new
  5691. // declaration has linkage).
  5692. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  5693. D.getCXXScopeSpec().isNotEmpty() ||
  5694. IsExplicitSpecialization ||
  5695. IsVariableTemplateSpecialization);
  5696. // Check whether the previous declaration is in the same block scope. This
  5697. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  5698. if (getLangOpts().CPlusPlus &&
  5699. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  5700. NewVD->setPreviousDeclInSameBlockScope(
  5701. Previous.isSingleResult() && !Previous.isShadowed() &&
  5702. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  5703. if (!getLangOpts().CPlusPlus) {
  5704. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  5705. } else {
  5706. // If this is an explicit specialization of a static data member, check it.
  5707. if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
  5708. CheckMemberSpecialization(NewVD, Previous))
  5709. NewVD->setInvalidDecl();
  5710. // Merge the decl with the existing one if appropriate.
  5711. if (!Previous.empty()) {
  5712. if (Previous.isSingleResult() &&
  5713. isa<FieldDecl>(Previous.getFoundDecl()) &&
  5714. D.getCXXScopeSpec().isSet()) {
  5715. // The user tried to define a non-static data member
  5716. // out-of-line (C++ [dcl.meaning]p1).
  5717. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  5718. << D.getCXXScopeSpec().getRange();
  5719. Previous.clear();
  5720. NewVD->setInvalidDecl();
  5721. }
  5722. } else if (D.getCXXScopeSpec().isSet()) {
  5723. // No previous declaration in the qualifying scope.
  5724. Diag(D.getIdentifierLoc(), diag::err_no_member)
  5725. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  5726. << D.getCXXScopeSpec().getRange();
  5727. NewVD->setInvalidDecl();
  5728. }
  5729. if (!IsVariableTemplateSpecialization)
  5730. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  5731. // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
  5732. // an explicit specialization (14.8.3) or a partial specialization of a
  5733. // concept definition.
  5734. if (IsVariableTemplateSpecialization &&
  5735. !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
  5736. Previous.isSingleResult()) {
  5737. NamedDecl *PreviousDecl = Previous.getFoundDecl();
  5738. if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
  5739. if (VarTmpl->isConcept()) {
  5740. Diag(NewVD->getLocation(), diag::err_concept_specialized)
  5741. << 1 /*variable*/
  5742. << (IsPartialSpecialization ? 2 /*partially specialized*/
  5743. : 1 /*explicitly specialized*/);
  5744. Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
  5745. NewVD->setInvalidDecl();
  5746. }
  5747. }
  5748. }
  5749. if (NewTemplate) {
  5750. VarTemplateDecl *PrevVarTemplate =
  5751. NewVD->getPreviousDecl()
  5752. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  5753. : nullptr;
  5754. // Check the template parameter list of this declaration, possibly
  5755. // merging in the template parameter list from the previous variable
  5756. // template declaration.
  5757. if (CheckTemplateParameterList(
  5758. TemplateParams,
  5759. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  5760. : nullptr,
  5761. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  5762. DC->isDependentContext())
  5763. ? TPC_ClassTemplateMember
  5764. : TPC_VarTemplate))
  5765. NewVD->setInvalidDecl();
  5766. // If we are providing an explicit specialization of a static variable
  5767. // template, make a note of that.
  5768. if (PrevVarTemplate &&
  5769. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  5770. PrevVarTemplate->setMemberSpecialization();
  5771. }
  5772. }
  5773. ProcessPragmaWeak(S, NewVD);
  5774. // If this is the first declaration of an extern C variable, update
  5775. // the map of such variables.
  5776. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  5777. isIncompleteDeclExternC(*this, NewVD))
  5778. RegisterLocallyScopedExternCDecl(NewVD, S);
  5779. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  5780. Decl *ManglingContextDecl;
  5781. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  5782. NewVD->getDeclContext(), ManglingContextDecl)) {
  5783. Context.setManglingNumber(
  5784. NewVD, MCtx->getManglingNumber(
  5785. NewVD, getMSManglingNumber(getLangOpts(), S)));
  5786. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  5787. }
  5788. }
  5789. // Special handling of variable named 'main'.
  5790. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  5791. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  5792. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  5793. // C++ [basic.start.main]p3
  5794. // A program that declares a variable main at global scope is ill-formed.
  5795. if (getLangOpts().CPlusPlus)
  5796. Diag(D.getLocStart(), diag::err_main_global_variable);
  5797. // In C, and external-linkage variable named main results in undefined
  5798. // behavior.
  5799. else if (NewVD->hasExternalFormalLinkage())
  5800. Diag(D.getLocStart(), diag::warn_main_redefined);
  5801. }
  5802. if (D.isRedeclaration() && !Previous.empty()) {
  5803. checkDLLAttributeRedeclaration(
  5804. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
  5805. IsExplicitSpecialization, D.isFunctionDefinition());
  5806. }
  5807. if (NewTemplate) {
  5808. if (NewVD->isInvalidDecl())
  5809. NewTemplate->setInvalidDecl();
  5810. ActOnDocumentableDecl(NewTemplate);
  5811. return NewTemplate;
  5812. }
  5813. return NewVD;
  5814. }
  5815. /// Enum describing the %select options in diag::warn_decl_shadow.
  5816. enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
  5817. /// Determine what kind of declaration we're shadowing.
  5818. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  5819. const DeclContext *OldDC) {
  5820. if (isa<RecordDecl>(OldDC))
  5821. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  5822. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  5823. }
  5824. /// Return the location of the capture if the given lambda captures the given
  5825. /// variable \p VD, or an invalid source location otherwise.
  5826. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  5827. const VarDecl *VD) {
  5828. for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
  5829. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  5830. return Capture.getLocation();
  5831. }
  5832. return SourceLocation();
  5833. }
  5834. /// \brief Diagnose variable or built-in function shadowing. Implements
  5835. /// -Wshadow.
  5836. ///
  5837. /// This method is called whenever a VarDecl is added to a "useful"
  5838. /// scope.
  5839. ///
  5840. /// \param S the scope in which the shadowing name is being declared
  5841. /// \param R the lookup of the name
  5842. ///
  5843. void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
  5844. // Return if warning is ignored.
  5845. if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
  5846. return;
  5847. // Don't diagnose declarations at file scope.
  5848. if (D->hasGlobalStorage())
  5849. return;
  5850. DeclContext *NewDC = D->getDeclContext();
  5851. // Only diagnose if we're shadowing an unambiguous field or variable.
  5852. if (R.getResultKind() != LookupResult::Found)
  5853. return;
  5854. NamedDecl* ShadowedDecl = R.getFoundDecl();
  5855. if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
  5856. return;
  5857. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  5858. // Fields are not shadowed by variables in C++ static methods.
  5859. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  5860. if (MD->isStatic())
  5861. return;
  5862. // Fields shadowed by constructor parameters are a special case. Usually
  5863. // the constructor initializes the field with the parameter.
  5864. if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
  5865. // Remember that this was shadowed so we can either warn about its
  5866. // modification or its existence depending on warning settings.
  5867. D = D->getCanonicalDecl();
  5868. ShadowingDecls.insert({D, FD});
  5869. return;
  5870. }
  5871. }
  5872. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  5873. if (shadowedVar->isExternC()) {
  5874. // For shadowing external vars, make sure that we point to the global
  5875. // declaration, not a locally scoped extern declaration.
  5876. for (auto I : shadowedVar->redecls())
  5877. if (I->isFileVarDecl()) {
  5878. ShadowedDecl = I;
  5879. break;
  5880. }
  5881. }
  5882. DeclContext *OldDC = ShadowedDecl->getDeclContext();
  5883. unsigned WarningDiag = diag::warn_decl_shadow;
  5884. SourceLocation CaptureLoc;
  5885. if (isa<VarDecl>(ShadowedDecl) && NewDC && isa<CXXMethodDecl>(NewDC)) {
  5886. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  5887. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  5888. if (RD->getLambdaCaptureDefault() == LCD_None) {
  5889. // Try to avoid warnings for lambdas with an explicit capture list.
  5890. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  5891. // Warn only when the lambda captures the shadowed decl explicitly.
  5892. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  5893. if (CaptureLoc.isInvalid())
  5894. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  5895. } else {
  5896. // Remember that this was shadowed so we can avoid the warning if the
  5897. // shadowed decl isn't captured and the warning settings allow it.
  5898. cast<LambdaScopeInfo>(getCurFunction())
  5899. ->ShadowingDecls.push_back({D, cast<VarDecl>(ShadowedDecl)});
  5900. return;
  5901. }
  5902. }
  5903. }
  5904. }
  5905. // Only warn about certain kinds of shadowing for class members.
  5906. if (NewDC && NewDC->isRecord()) {
  5907. // In particular, don't warn about shadowing non-class members.
  5908. if (!OldDC->isRecord())
  5909. return;
  5910. // TODO: should we warn about static data members shadowing
  5911. // static data members from base classes?
  5912. // TODO: don't diagnose for inaccessible shadowed members.
  5913. // This is hard to do perfectly because we might friend the
  5914. // shadowing context, but that's just a false negative.
  5915. }
  5916. DeclarationName Name = R.getLookupName();
  5917. // Emit warning and note.
  5918. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  5919. return;
  5920. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  5921. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  5922. if (!CaptureLoc.isInvalid())
  5923. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  5924. << Name << /*explicitly*/ 1;
  5925. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  5926. }
  5927. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  5928. /// when these variables are captured by the lambda.
  5929. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  5930. for (const auto &Shadow : LSI->ShadowingDecls) {
  5931. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  5932. // Try to avoid the warning when the shadowed decl isn't captured.
  5933. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  5934. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  5935. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  5936. ? diag::warn_decl_shadow_uncaptured_local
  5937. : diag::warn_decl_shadow)
  5938. << Shadow.VD->getDeclName()
  5939. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  5940. if (!CaptureLoc.isInvalid())
  5941. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  5942. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  5943. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  5944. }
  5945. }
  5946. /// \brief Check -Wshadow without the advantage of a previous lookup.
  5947. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  5948. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  5949. return;
  5950. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  5951. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  5952. LookupName(R, S);
  5953. CheckShadow(S, D, R);
  5954. }
  5955. /// Check if 'E', which is an expression that is about to be modified, refers
  5956. /// to a constructor parameter that shadows a field.
  5957. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  5958. // Quickly ignore expressions that can't be shadowing ctor parameters.
  5959. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  5960. return;
  5961. E = E->IgnoreParenImpCasts();
  5962. auto *DRE = dyn_cast<DeclRefExpr>(E);
  5963. if (!DRE)
  5964. return;
  5965. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  5966. auto I = ShadowingDecls.find(D);
  5967. if (I == ShadowingDecls.end())
  5968. return;
  5969. const NamedDecl *ShadowedDecl = I->second;
  5970. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  5971. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  5972. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  5973. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  5974. // Avoid issuing multiple warnings about the same decl.
  5975. ShadowingDecls.erase(I);
  5976. }
  5977. /// Check for conflict between this global or extern "C" declaration and
  5978. /// previous global or extern "C" declarations. This is only used in C++.
  5979. template<typename T>
  5980. static bool checkGlobalOrExternCConflict(
  5981. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  5982. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  5983. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  5984. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  5985. // The common case: this global doesn't conflict with any extern "C"
  5986. // declaration.
  5987. return false;
  5988. }
  5989. if (Prev) {
  5990. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  5991. // Both the old and new declarations have C language linkage. This is a
  5992. // redeclaration.
  5993. Previous.clear();
  5994. Previous.addDecl(Prev);
  5995. return true;
  5996. }
  5997. // This is a global, non-extern "C" declaration, and there is a previous
  5998. // non-global extern "C" declaration. Diagnose if this is a variable
  5999. // declaration.
  6000. if (!isa<VarDecl>(ND))
  6001. return false;
  6002. } else {
  6003. // The declaration is extern "C". Check for any declaration in the
  6004. // translation unit which might conflict.
  6005. if (IsGlobal) {
  6006. // We have already performed the lookup into the translation unit.
  6007. IsGlobal = false;
  6008. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6009. I != E; ++I) {
  6010. if (isa<VarDecl>(*I)) {
  6011. Prev = *I;
  6012. break;
  6013. }
  6014. }
  6015. } else {
  6016. DeclContext::lookup_result R =
  6017. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  6018. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  6019. I != E; ++I) {
  6020. if (isa<VarDecl>(*I)) {
  6021. Prev = *I;
  6022. break;
  6023. }
  6024. // FIXME: If we have any other entity with this name in global scope,
  6025. // the declaration is ill-formed, but that is a defect: it breaks the
  6026. // 'stat' hack, for instance. Only variables can have mangled name
  6027. // clashes with extern "C" declarations, so only they deserve a
  6028. // diagnostic.
  6029. }
  6030. }
  6031. if (!Prev)
  6032. return false;
  6033. }
  6034. // Use the first declaration's location to ensure we point at something which
  6035. // is lexically inside an extern "C" linkage-spec.
  6036. assert(Prev && "should have found a previous declaration to diagnose");
  6037. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  6038. Prev = FD->getFirstDecl();
  6039. else
  6040. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  6041. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  6042. << IsGlobal << ND;
  6043. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  6044. << IsGlobal;
  6045. return false;
  6046. }
  6047. /// Apply special rules for handling extern "C" declarations. Returns \c true
  6048. /// if we have found that this is a redeclaration of some prior entity.
  6049. ///
  6050. /// Per C++ [dcl.link]p6:
  6051. /// Two declarations [for a function or variable] with C language linkage
  6052. /// with the same name that appear in different scopes refer to the same
  6053. /// [entity]. An entity with C language linkage shall not be declared with
  6054. /// the same name as an entity in global scope.
  6055. template<typename T>
  6056. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  6057. LookupResult &Previous) {
  6058. if (!S.getLangOpts().CPlusPlus) {
  6059. // In C, when declaring a global variable, look for a corresponding 'extern'
  6060. // variable declared in function scope. We don't need this in C++, because
  6061. // we find local extern decls in the surrounding file-scope DeclContext.
  6062. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6063. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  6064. Previous.clear();
  6065. Previous.addDecl(Prev);
  6066. return true;
  6067. }
  6068. }
  6069. return false;
  6070. }
  6071. // A declaration in the translation unit can conflict with an extern "C"
  6072. // declaration.
  6073. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  6074. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  6075. // An extern "C" declaration can conflict with a declaration in the
  6076. // translation unit or can be a redeclaration of an extern "C" declaration
  6077. // in another scope.
  6078. if (isIncompleteDeclExternC(S,ND))
  6079. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  6080. // Neither global nor extern "C": nothing to do.
  6081. return false;
  6082. }
  6083. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  6084. // If the decl is already known invalid, don't check it.
  6085. if (NewVD->isInvalidDecl())
  6086. return;
  6087. TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
  6088. QualType T = TInfo->getType();
  6089. // Defer checking an 'auto' type until its initializer is attached.
  6090. if (T->isUndeducedType())
  6091. return;
  6092. if (NewVD->hasAttrs())
  6093. CheckAlignasUnderalignment(NewVD);
  6094. if (T->isObjCObjectType()) {
  6095. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  6096. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  6097. T = Context.getObjCObjectPointerType(T);
  6098. NewVD->setType(T);
  6099. }
  6100. // Emit an error if an address space was applied to decl with local storage.
  6101. // This includes arrays of objects with address space qualifiers, but not
  6102. // automatic variables that point to other address spaces.
  6103. // ISO/IEC TR 18037 S5.1.2
  6104. if (!getLangOpts().OpenCL
  6105. && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
  6106. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
  6107. NewVD->setInvalidDecl();
  6108. return;
  6109. }
  6110. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  6111. // scope.
  6112. if (getLangOpts().OpenCLVersion == 120 &&
  6113. !getOpenCLOptions().cl_clang_storage_class_specifiers &&
  6114. NewVD->isStaticLocal()) {
  6115. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  6116. NewVD->setInvalidDecl();
  6117. return;
  6118. }
  6119. if (getLangOpts().OpenCL) {
  6120. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  6121. if (NewVD->hasAttr<BlocksAttr>()) {
  6122. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  6123. return;
  6124. }
  6125. if (T->isBlockPointerType()) {
  6126. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  6127. // can't use 'extern' storage class.
  6128. if (!T.isConstQualified()) {
  6129. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  6130. << 0 /*const*/;
  6131. NewVD->setInvalidDecl();
  6132. return;
  6133. }
  6134. if (NewVD->hasExternalStorage()) {
  6135. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  6136. NewVD->setInvalidDecl();
  6137. return;
  6138. }
  6139. }
  6140. // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
  6141. // __constant address space.
  6142. // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
  6143. // variables inside a function can also be declared in the global
  6144. // address space.
  6145. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  6146. NewVD->hasExternalStorage()) {
  6147. if (!T->isSamplerT() &&
  6148. !(T.getAddressSpace() == LangAS::opencl_constant ||
  6149. (T.getAddressSpace() == LangAS::opencl_global &&
  6150. getLangOpts().OpenCLVersion == 200))) {
  6151. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  6152. if (getLangOpts().OpenCLVersion == 200)
  6153. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6154. << Scope << "global or constant";
  6155. else
  6156. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6157. << Scope << "constant";
  6158. NewVD->setInvalidDecl();
  6159. return;
  6160. }
  6161. } else {
  6162. if (T.getAddressSpace() == LangAS::opencl_global) {
  6163. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6164. << 1 /*is any function*/ << "global";
  6165. NewVD->setInvalidDecl();
  6166. return;
  6167. }
  6168. // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
  6169. // in functions.
  6170. if (T.getAddressSpace() == LangAS::opencl_constant ||
  6171. T.getAddressSpace() == LangAS::opencl_local) {
  6172. FunctionDecl *FD = getCurFunctionDecl();
  6173. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  6174. if (T.getAddressSpace() == LangAS::opencl_constant)
  6175. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6176. << 0 /*non-kernel only*/ << "constant";
  6177. else
  6178. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6179. << 0 /*non-kernel only*/ << "local";
  6180. NewVD->setInvalidDecl();
  6181. return;
  6182. }
  6183. }
  6184. }
  6185. }
  6186. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  6187. && !NewVD->hasAttr<BlocksAttr>()) {
  6188. if (getLangOpts().getGC() != LangOptions::NonGC)
  6189. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  6190. else {
  6191. assert(!getLangOpts().ObjCAutoRefCount);
  6192. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  6193. }
  6194. }
  6195. bool isVM = T->isVariablyModifiedType();
  6196. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  6197. NewVD->hasAttr<BlocksAttr>())
  6198. getCurFunction()->setHasBranchProtectedScope();
  6199. if ((isVM && NewVD->hasLinkage()) ||
  6200. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  6201. bool SizeIsNegative;
  6202. llvm::APSInt Oversized;
  6203. TypeSourceInfo *FixedTInfo =
  6204. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  6205. SizeIsNegative, Oversized);
  6206. if (!FixedTInfo && T->isVariableArrayType()) {
  6207. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  6208. // FIXME: This won't give the correct result for
  6209. // int a[10][n];
  6210. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  6211. if (NewVD->isFileVarDecl())
  6212. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  6213. << SizeRange;
  6214. else if (NewVD->isStaticLocal())
  6215. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  6216. << SizeRange;
  6217. else
  6218. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  6219. << SizeRange;
  6220. NewVD->setInvalidDecl();
  6221. return;
  6222. }
  6223. if (!FixedTInfo) {
  6224. if (NewVD->isFileVarDecl())
  6225. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  6226. else
  6227. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  6228. NewVD->setInvalidDecl();
  6229. return;
  6230. }
  6231. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  6232. NewVD->setType(FixedTInfo->getType());
  6233. NewVD->setTypeSourceInfo(FixedTInfo);
  6234. }
  6235. if (T->isVoidType()) {
  6236. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  6237. // of objects and functions.
  6238. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  6239. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  6240. << T;
  6241. NewVD->setInvalidDecl();
  6242. return;
  6243. }
  6244. }
  6245. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  6246. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  6247. NewVD->setInvalidDecl();
  6248. return;
  6249. }
  6250. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  6251. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  6252. NewVD->setInvalidDecl();
  6253. return;
  6254. }
  6255. if (NewVD->isConstexpr() && !T->isDependentType() &&
  6256. RequireLiteralType(NewVD->getLocation(), T,
  6257. diag::err_constexpr_var_non_literal)) {
  6258. NewVD->setInvalidDecl();
  6259. return;
  6260. }
  6261. }
  6262. /// \brief Perform semantic checking on a newly-created variable
  6263. /// declaration.
  6264. ///
  6265. /// This routine performs all of the type-checking required for a
  6266. /// variable declaration once it has been built. It is used both to
  6267. /// check variables after they have been parsed and their declarators
  6268. /// have been translated into a declaration, and to check variables
  6269. /// that have been instantiated from a template.
  6270. ///
  6271. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  6272. ///
  6273. /// Returns true if the variable declaration is a redeclaration.
  6274. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  6275. CheckVariableDeclarationType(NewVD);
  6276. // If the decl is already known invalid, don't check it.
  6277. if (NewVD->isInvalidDecl())
  6278. return false;
  6279. // If we did not find anything by this name, look for a non-visible
  6280. // extern "C" declaration with the same name.
  6281. if (Previous.empty() &&
  6282. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  6283. Previous.setShadowed();
  6284. if (!Previous.empty()) {
  6285. MergeVarDecl(NewVD, Previous);
  6286. return true;
  6287. }
  6288. return false;
  6289. }
  6290. namespace {
  6291. struct FindOverriddenMethod {
  6292. Sema *S;
  6293. CXXMethodDecl *Method;
  6294. /// Member lookup function that determines whether a given C++
  6295. /// method overrides a method in a base class, to be used with
  6296. /// CXXRecordDecl::lookupInBases().
  6297. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6298. RecordDecl *BaseRecord =
  6299. Specifier->getType()->getAs<RecordType>()->getDecl();
  6300. DeclarationName Name = Method->getDeclName();
  6301. // FIXME: Do we care about other names here too?
  6302. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6303. // We really want to find the base class destructor here.
  6304. QualType T = S->Context.getTypeDeclType(BaseRecord);
  6305. CanQualType CT = S->Context.getCanonicalType(T);
  6306. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  6307. }
  6308. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6309. Path.Decls = Path.Decls.slice(1)) {
  6310. NamedDecl *D = Path.Decls.front();
  6311. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6312. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  6313. return true;
  6314. }
  6315. }
  6316. return false;
  6317. }
  6318. };
  6319. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  6320. } // end anonymous namespace
  6321. /// \brief Report an error regarding overriding, along with any relevant
  6322. /// overriden methods.
  6323. ///
  6324. /// \param DiagID the primary error to report.
  6325. /// \param MD the overriding method.
  6326. /// \param OEK which overrides to include as notes.
  6327. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  6328. OverrideErrorKind OEK = OEK_All) {
  6329. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  6330. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  6331. E = MD->end_overridden_methods();
  6332. I != E; ++I) {
  6333. // This check (& the OEK parameter) could be replaced by a predicate, but
  6334. // without lambdas that would be overkill. This is still nicer than writing
  6335. // out the diag loop 3 times.
  6336. if ((OEK == OEK_All) ||
  6337. (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
  6338. (OEK == OEK_Deleted && (*I)->isDeleted()))
  6339. S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
  6340. }
  6341. }
  6342. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  6343. /// and if so, check that it's a valid override and remember it.
  6344. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  6345. // Look for methods in base classes that this method might override.
  6346. CXXBasePaths Paths;
  6347. FindOverriddenMethod FOM;
  6348. FOM.Method = MD;
  6349. FOM.S = this;
  6350. bool hasDeletedOverridenMethods = false;
  6351. bool hasNonDeletedOverridenMethods = false;
  6352. bool AddedAny = false;
  6353. if (DC->lookupInBases(FOM, Paths)) {
  6354. for (auto *I : Paths.found_decls()) {
  6355. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  6356. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  6357. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  6358. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  6359. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  6360. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  6361. hasDeletedOverridenMethods |= OldMD->isDeleted();
  6362. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  6363. AddedAny = true;
  6364. }
  6365. }
  6366. }
  6367. }
  6368. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  6369. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  6370. }
  6371. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  6372. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  6373. }
  6374. return AddedAny;
  6375. }
  6376. namespace {
  6377. // Struct for holding all of the extra arguments needed by
  6378. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  6379. struct ActOnFDArgs {
  6380. Scope *S;
  6381. Declarator &D;
  6382. MultiTemplateParamsArg TemplateParamLists;
  6383. bool AddToScope;
  6384. };
  6385. } // end anonymous namespace
  6386. namespace {
  6387. // Callback to only accept typo corrections that have a non-zero edit distance.
  6388. // Also only accept corrections that have the same parent decl.
  6389. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  6390. public:
  6391. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  6392. CXXRecordDecl *Parent)
  6393. : Context(Context), OriginalFD(TypoFD),
  6394. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  6395. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6396. if (candidate.getEditDistance() == 0)
  6397. return false;
  6398. SmallVector<unsigned, 1> MismatchedParams;
  6399. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  6400. CDeclEnd = candidate.end();
  6401. CDecl != CDeclEnd; ++CDecl) {
  6402. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6403. if (FD && !FD->hasBody() &&
  6404. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  6405. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  6406. CXXRecordDecl *Parent = MD->getParent();
  6407. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  6408. return true;
  6409. } else if (!ExpectedParent) {
  6410. return true;
  6411. }
  6412. }
  6413. }
  6414. return false;
  6415. }
  6416. private:
  6417. ASTContext &Context;
  6418. FunctionDecl *OriginalFD;
  6419. CXXRecordDecl *ExpectedParent;
  6420. };
  6421. } // end anonymous namespace
  6422. /// \brief Generate diagnostics for an invalid function redeclaration.
  6423. ///
  6424. /// This routine handles generating the diagnostic messages for an invalid
  6425. /// function redeclaration, including finding possible similar declarations
  6426. /// or performing typo correction if there are no previous declarations with
  6427. /// the same name.
  6428. ///
  6429. /// Returns a NamedDecl iff typo correction was performed and substituting in
  6430. /// the new declaration name does not cause new errors.
  6431. static NamedDecl *DiagnoseInvalidRedeclaration(
  6432. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  6433. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  6434. DeclarationName Name = NewFD->getDeclName();
  6435. DeclContext *NewDC = NewFD->getDeclContext();
  6436. SmallVector<unsigned, 1> MismatchedParams;
  6437. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  6438. TypoCorrection Correction;
  6439. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  6440. unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
  6441. : diag::err_member_decl_does_not_match;
  6442. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  6443. IsLocalFriend ? Sema::LookupLocalFriendName
  6444. : Sema::LookupOrdinaryName,
  6445. Sema::ForRedeclaration);
  6446. NewFD->setInvalidDecl();
  6447. if (IsLocalFriend)
  6448. SemaRef.LookupName(Prev, S);
  6449. else
  6450. SemaRef.LookupQualifiedName(Prev, NewDC);
  6451. assert(!Prev.isAmbiguous() &&
  6452. "Cannot have an ambiguity in previous-declaration lookup");
  6453. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  6454. if (!Prev.empty()) {
  6455. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  6456. Func != FuncEnd; ++Func) {
  6457. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  6458. if (FD &&
  6459. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6460. // Add 1 to the index so that 0 can mean the mismatch didn't
  6461. // involve a parameter
  6462. unsigned ParamNum =
  6463. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  6464. NearMatches.push_back(std::make_pair(FD, ParamNum));
  6465. }
  6466. }
  6467. // If the qualified name lookup yielded nothing, try typo correction
  6468. } else if ((Correction = SemaRef.CorrectTypo(
  6469. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  6470. &ExtraArgs.D.getCXXScopeSpec(),
  6471. llvm::make_unique<DifferentNameValidatorCCC>(
  6472. SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
  6473. Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
  6474. // Set up everything for the call to ActOnFunctionDeclarator
  6475. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  6476. ExtraArgs.D.getIdentifierLoc());
  6477. Previous.clear();
  6478. Previous.setLookupName(Correction.getCorrection());
  6479. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  6480. CDeclEnd = Correction.end();
  6481. CDecl != CDeclEnd; ++CDecl) {
  6482. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6483. if (FD && !FD->hasBody() &&
  6484. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6485. Previous.addDecl(FD);
  6486. }
  6487. }
  6488. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  6489. NamedDecl *Result;
  6490. // Retry building the function declaration with the new previous
  6491. // declarations, and with errors suppressed.
  6492. {
  6493. // Trap errors.
  6494. Sema::SFINAETrap Trap(SemaRef);
  6495. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  6496. // pieces need to verify the typo-corrected C++ declaration and hopefully
  6497. // eliminate the need for the parameter pack ExtraArgs.
  6498. Result = SemaRef.ActOnFunctionDeclarator(
  6499. ExtraArgs.S, ExtraArgs.D,
  6500. Correction.getCorrectionDecl()->getDeclContext(),
  6501. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  6502. ExtraArgs.AddToScope);
  6503. if (Trap.hasErrorOccurred())
  6504. Result = nullptr;
  6505. }
  6506. if (Result) {
  6507. // Determine which correction we picked.
  6508. Decl *Canonical = Result->getCanonicalDecl();
  6509. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6510. I != E; ++I)
  6511. if ((*I)->getCanonicalDecl() == Canonical)
  6512. Correction.setCorrectionDecl(*I);
  6513. SemaRef.diagnoseTypo(
  6514. Correction,
  6515. SemaRef.PDiag(IsLocalFriend
  6516. ? diag::err_no_matching_local_friend_suggest
  6517. : diag::err_member_decl_does_not_match_suggest)
  6518. << Name << NewDC << IsDefinition);
  6519. return Result;
  6520. }
  6521. // Pretend the typo correction never occurred
  6522. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  6523. ExtraArgs.D.getIdentifierLoc());
  6524. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  6525. Previous.clear();
  6526. Previous.setLookupName(Name);
  6527. }
  6528. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  6529. << Name << NewDC << IsDefinition << NewFD->getLocation();
  6530. bool NewFDisConst = false;
  6531. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  6532. NewFDisConst = NewMD->isConst();
  6533. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  6534. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  6535. NearMatch != NearMatchEnd; ++NearMatch) {
  6536. FunctionDecl *FD = NearMatch->first;
  6537. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6538. bool FDisConst = MD && MD->isConst();
  6539. bool IsMember = MD || !IsLocalFriend;
  6540. // FIXME: These notes are poorly worded for the local friend case.
  6541. if (unsigned Idx = NearMatch->second) {
  6542. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  6543. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  6544. if (Loc.isInvalid()) Loc = FD->getLocation();
  6545. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  6546. : diag::note_local_decl_close_param_match)
  6547. << Idx << FDParam->getType()
  6548. << NewFD->getParamDecl(Idx - 1)->getType();
  6549. } else if (FDisConst != NewFDisConst) {
  6550. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  6551. << NewFDisConst << FD->getSourceRange().getEnd();
  6552. } else
  6553. SemaRef.Diag(FD->getLocation(),
  6554. IsMember ? diag::note_member_def_close_match
  6555. : diag::note_local_decl_close_match);
  6556. }
  6557. return nullptr;
  6558. }
  6559. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  6560. switch (D.getDeclSpec().getStorageClassSpec()) {
  6561. default: llvm_unreachable("Unknown storage class!");
  6562. case DeclSpec::SCS_auto:
  6563. case DeclSpec::SCS_register:
  6564. case DeclSpec::SCS_mutable:
  6565. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6566. diag::err_typecheck_sclass_func);
  6567. D.setInvalidType();
  6568. break;
  6569. case DeclSpec::SCS_unspecified: break;
  6570. case DeclSpec::SCS_extern:
  6571. if (D.getDeclSpec().isExternInLinkageSpec())
  6572. return SC_None;
  6573. return SC_Extern;
  6574. case DeclSpec::SCS_static: {
  6575. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  6576. // C99 6.7.1p5:
  6577. // The declaration of an identifier for a function that has
  6578. // block scope shall have no explicit storage-class specifier
  6579. // other than extern
  6580. // See also (C++ [dcl.stc]p4).
  6581. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6582. diag::err_static_block_func);
  6583. break;
  6584. } else
  6585. return SC_Static;
  6586. }
  6587. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  6588. }
  6589. // No explicit storage class has already been returned
  6590. return SC_None;
  6591. }
  6592. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  6593. DeclContext *DC, QualType &R,
  6594. TypeSourceInfo *TInfo,
  6595. StorageClass SC,
  6596. bool &IsVirtualOkay) {
  6597. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  6598. DeclarationName Name = NameInfo.getName();
  6599. FunctionDecl *NewFD = nullptr;
  6600. bool isInline = D.getDeclSpec().isInlineSpecified();
  6601. if (!SemaRef.getLangOpts().CPlusPlus) {
  6602. // Determine whether the function was written with a
  6603. // prototype. This true when:
  6604. // - there is a prototype in the declarator, or
  6605. // - the type R of the function is some kind of typedef or other reference
  6606. // to a type name (which eventually refers to a function type).
  6607. bool HasPrototype =
  6608. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  6609. (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
  6610. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  6611. D.getLocStart(), NameInfo, R,
  6612. TInfo, SC, isInline,
  6613. HasPrototype, false);
  6614. if (D.isInvalidType())
  6615. NewFD->setInvalidDecl();
  6616. return NewFD;
  6617. }
  6618. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  6619. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  6620. // Check that the return type is not an abstract class type.
  6621. // For record types, this is done by the AbstractClassUsageDiagnoser once
  6622. // the class has been completely parsed.
  6623. if (!DC->isRecord() &&
  6624. SemaRef.RequireNonAbstractType(
  6625. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  6626. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  6627. D.setInvalidType();
  6628. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  6629. // This is a C++ constructor declaration.
  6630. assert(DC->isRecord() &&
  6631. "Constructors can only be declared in a member context");
  6632. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  6633. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  6634. D.getLocStart(), NameInfo,
  6635. R, TInfo, isExplicit, isInline,
  6636. /*isImplicitlyDeclared=*/false,
  6637. isConstexpr);
  6638. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6639. // This is a C++ destructor declaration.
  6640. if (DC->isRecord()) {
  6641. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  6642. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  6643. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  6644. SemaRef.Context, Record,
  6645. D.getLocStart(),
  6646. NameInfo, R, TInfo, isInline,
  6647. /*isImplicitlyDeclared=*/false);
  6648. // If the class is complete, then we now create the implicit exception
  6649. // specification. If the class is incomplete or dependent, we can't do
  6650. // it yet.
  6651. if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
  6652. Record->getDefinition() && !Record->isBeingDefined() &&
  6653. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  6654. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  6655. }
  6656. IsVirtualOkay = true;
  6657. return NewDD;
  6658. } else {
  6659. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  6660. D.setInvalidType();
  6661. // Create a FunctionDecl to satisfy the function definition parsing
  6662. // code path.
  6663. return FunctionDecl::Create(SemaRef.Context, DC,
  6664. D.getLocStart(),
  6665. D.getIdentifierLoc(), Name, R, TInfo,
  6666. SC, isInline,
  6667. /*hasPrototype=*/true, isConstexpr);
  6668. }
  6669. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  6670. if (!DC->isRecord()) {
  6671. SemaRef.Diag(D.getIdentifierLoc(),
  6672. diag::err_conv_function_not_member);
  6673. return nullptr;
  6674. }
  6675. SemaRef.CheckConversionDeclarator(D, R, SC);
  6676. IsVirtualOkay = true;
  6677. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  6678. D.getLocStart(), NameInfo,
  6679. R, TInfo, isInline, isExplicit,
  6680. isConstexpr, SourceLocation());
  6681. } else if (DC->isRecord()) {
  6682. // If the name of the function is the same as the name of the record,
  6683. // then this must be an invalid constructor that has a return type.
  6684. // (The parser checks for a return type and makes the declarator a
  6685. // constructor if it has no return type).
  6686. if (Name.getAsIdentifierInfo() &&
  6687. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  6688. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  6689. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  6690. << SourceRange(D.getIdentifierLoc());
  6691. return nullptr;
  6692. }
  6693. // This is a C++ method declaration.
  6694. CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
  6695. cast<CXXRecordDecl>(DC),
  6696. D.getLocStart(), NameInfo, R,
  6697. TInfo, SC, isInline,
  6698. isConstexpr, SourceLocation());
  6699. IsVirtualOkay = !Ret->isStatic();
  6700. return Ret;
  6701. } else {
  6702. bool isFriend =
  6703. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  6704. if (!isFriend && SemaRef.CurContext->isRecord())
  6705. return nullptr;
  6706. // Determine whether the function was written with a
  6707. // prototype. This true when:
  6708. // - we're in C++ (where every function has a prototype),
  6709. return FunctionDecl::Create(SemaRef.Context, DC,
  6710. D.getLocStart(),
  6711. NameInfo, R, TInfo, SC, isInline,
  6712. true/*HasPrototype*/, isConstexpr);
  6713. }
  6714. }
  6715. enum OpenCLParamType {
  6716. ValidKernelParam,
  6717. PtrPtrKernelParam,
  6718. PtrKernelParam,
  6719. PrivatePtrKernelParam,
  6720. InvalidKernelParam,
  6721. RecordKernelParam
  6722. };
  6723. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  6724. if (PT->isPointerType()) {
  6725. QualType PointeeType = PT->getPointeeType();
  6726. if (PointeeType->isPointerType())
  6727. return PtrPtrKernelParam;
  6728. return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
  6729. : PtrKernelParam;
  6730. }
  6731. // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
  6732. // be used as builtin types.
  6733. if (PT->isImageType())
  6734. return PtrKernelParam;
  6735. if (PT->isBooleanType())
  6736. return InvalidKernelParam;
  6737. if (PT->isEventT())
  6738. return InvalidKernelParam;
  6739. // OpenCL extension spec v1.2 s9.5:
  6740. // This extension adds support for half scalar and vector types as built-in
  6741. // types that can be used for arithmetic operations, conversions etc.
  6742. if (!S.getOpenCLOptions().cl_khr_fp16 && PT->isHalfType())
  6743. return InvalidKernelParam;
  6744. if (PT->isRecordType())
  6745. return RecordKernelParam;
  6746. return ValidKernelParam;
  6747. }
  6748. static void checkIsValidOpenCLKernelParameter(
  6749. Sema &S,
  6750. Declarator &D,
  6751. ParmVarDecl *Param,
  6752. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  6753. QualType PT = Param->getType();
  6754. // Cache the valid types we encounter to avoid rechecking structs that are
  6755. // used again
  6756. if (ValidTypes.count(PT.getTypePtr()))
  6757. return;
  6758. switch (getOpenCLKernelParameterType(S, PT)) {
  6759. case PtrPtrKernelParam:
  6760. // OpenCL v1.2 s6.9.a:
  6761. // A kernel function argument cannot be declared as a
  6762. // pointer to a pointer type.
  6763. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  6764. D.setInvalidType();
  6765. return;
  6766. case PrivatePtrKernelParam:
  6767. // OpenCL v1.2 s6.9.a:
  6768. // A kernel function argument cannot be declared as a
  6769. // pointer to the private address space.
  6770. S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
  6771. D.setInvalidType();
  6772. return;
  6773. // OpenCL v1.2 s6.9.k:
  6774. // Arguments to kernel functions in a program cannot be declared with the
  6775. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  6776. // uintptr_t or a struct and/or union that contain fields declared to be
  6777. // one of these built-in scalar types.
  6778. case InvalidKernelParam:
  6779. // OpenCL v1.2 s6.8 n:
  6780. // A kernel function argument cannot be declared
  6781. // of event_t type.
  6782. // Do not diagnose half type since it is diagnosed as invalid argument
  6783. // type for any function elsewhere.
  6784. if (!PT->isHalfType())
  6785. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  6786. D.setInvalidType();
  6787. return;
  6788. case PtrKernelParam:
  6789. case ValidKernelParam:
  6790. ValidTypes.insert(PT.getTypePtr());
  6791. return;
  6792. case RecordKernelParam:
  6793. break;
  6794. }
  6795. // Track nested structs we will inspect
  6796. SmallVector<const Decl *, 4> VisitStack;
  6797. // Track where we are in the nested structs. Items will migrate from
  6798. // VisitStack to HistoryStack as we do the DFS for bad field.
  6799. SmallVector<const FieldDecl *, 4> HistoryStack;
  6800. HistoryStack.push_back(nullptr);
  6801. const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
  6802. VisitStack.push_back(PD);
  6803. assert(VisitStack.back() && "First decl null?");
  6804. do {
  6805. const Decl *Next = VisitStack.pop_back_val();
  6806. if (!Next) {
  6807. assert(!HistoryStack.empty());
  6808. // Found a marker, we have gone up a level
  6809. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  6810. ValidTypes.insert(Hist->getType().getTypePtr());
  6811. continue;
  6812. }
  6813. // Adds everything except the original parameter declaration (which is not a
  6814. // field itself) to the history stack.
  6815. const RecordDecl *RD;
  6816. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  6817. HistoryStack.push_back(Field);
  6818. RD = Field->getType()->castAs<RecordType>()->getDecl();
  6819. } else {
  6820. RD = cast<RecordDecl>(Next);
  6821. }
  6822. // Add a null marker so we know when we've gone back up a level
  6823. VisitStack.push_back(nullptr);
  6824. for (const auto *FD : RD->fields()) {
  6825. QualType QT = FD->getType();
  6826. if (ValidTypes.count(QT.getTypePtr()))
  6827. continue;
  6828. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  6829. if (ParamType == ValidKernelParam)
  6830. continue;
  6831. if (ParamType == RecordKernelParam) {
  6832. VisitStack.push_back(FD);
  6833. continue;
  6834. }
  6835. // OpenCL v1.2 s6.9.p:
  6836. // Arguments to kernel functions that are declared to be a struct or union
  6837. // do not allow OpenCL objects to be passed as elements of the struct or
  6838. // union.
  6839. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  6840. ParamType == PrivatePtrKernelParam) {
  6841. S.Diag(Param->getLocation(),
  6842. diag::err_record_with_pointers_kernel_param)
  6843. << PT->isUnionType()
  6844. << PT;
  6845. } else {
  6846. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  6847. }
  6848. S.Diag(PD->getLocation(), diag::note_within_field_of_type)
  6849. << PD->getDeclName();
  6850. // We have an error, now let's go back up through history and show where
  6851. // the offending field came from
  6852. for (ArrayRef<const FieldDecl *>::const_iterator
  6853. I = HistoryStack.begin() + 1,
  6854. E = HistoryStack.end();
  6855. I != E; ++I) {
  6856. const FieldDecl *OuterField = *I;
  6857. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  6858. << OuterField->getType();
  6859. }
  6860. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  6861. << QT->isPointerType()
  6862. << QT;
  6863. D.setInvalidType();
  6864. return;
  6865. }
  6866. } while (!VisitStack.empty());
  6867. }
  6868. NamedDecl*
  6869. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  6870. TypeSourceInfo *TInfo, LookupResult &Previous,
  6871. MultiTemplateParamsArg TemplateParamLists,
  6872. bool &AddToScope) {
  6873. QualType R = TInfo->getType();
  6874. assert(R.getTypePtr()->isFunctionType());
  6875. // TODO: consider using NameInfo for diagnostic.
  6876. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  6877. DeclarationName Name = NameInfo.getName();
  6878. StorageClass SC = getFunctionStorageClass(*this, D);
  6879. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  6880. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6881. diag::err_invalid_thread)
  6882. << DeclSpec::getSpecifierName(TSCS);
  6883. if (D.isFirstDeclarationOfMember())
  6884. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  6885. D.getIdentifierLoc());
  6886. bool isFriend = false;
  6887. FunctionTemplateDecl *FunctionTemplate = nullptr;
  6888. bool isExplicitSpecialization = false;
  6889. bool isFunctionTemplateSpecialization = false;
  6890. bool isDependentClassScopeExplicitSpecialization = false;
  6891. bool HasExplicitTemplateArgs = false;
  6892. TemplateArgumentListInfo TemplateArgs;
  6893. bool isVirtualOkay = false;
  6894. DeclContext *OriginalDC = DC;
  6895. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  6896. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  6897. isVirtualOkay);
  6898. if (!NewFD) return nullptr;
  6899. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  6900. NewFD->setTopLevelDeclInObjCContainer();
  6901. // Set the lexical context. If this is a function-scope declaration, or has a
  6902. // C++ scope specifier, or is the object of a friend declaration, the lexical
  6903. // context will be different from the semantic context.
  6904. NewFD->setLexicalDeclContext(CurContext);
  6905. if (IsLocalExternDecl)
  6906. NewFD->setLocalExternDecl();
  6907. if (getLangOpts().CPlusPlus) {
  6908. bool isInline = D.getDeclSpec().isInlineSpecified();
  6909. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  6910. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  6911. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  6912. bool isConcept = D.getDeclSpec().isConceptSpecified();
  6913. isFriend = D.getDeclSpec().isFriendSpecified();
  6914. if (isFriend && !isInline && D.isFunctionDefinition()) {
  6915. // C++ [class.friend]p5
  6916. // A function can be defined in a friend declaration of a
  6917. // class . . . . Such a function is implicitly inline.
  6918. NewFD->setImplicitlyInline();
  6919. }
  6920. // If this is a method defined in an __interface, and is not a constructor
  6921. // or an overloaded operator, then set the pure flag (isVirtual will already
  6922. // return true).
  6923. if (const CXXRecordDecl *Parent =
  6924. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  6925. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  6926. NewFD->setPure(true);
  6927. // C++ [class.union]p2
  6928. // A union can have member functions, but not virtual functions.
  6929. if (isVirtual && Parent->isUnion())
  6930. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  6931. }
  6932. SetNestedNameSpecifier(NewFD, D);
  6933. isExplicitSpecialization = false;
  6934. isFunctionTemplateSpecialization = false;
  6935. if (D.isInvalidType())
  6936. NewFD->setInvalidDecl();
  6937. // Match up the template parameter lists with the scope specifier, then
  6938. // determine whether we have a template or a template specialization.
  6939. bool Invalid = false;
  6940. if (TemplateParameterList *TemplateParams =
  6941. MatchTemplateParametersToScopeSpecifier(
  6942. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  6943. D.getCXXScopeSpec(),
  6944. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  6945. ? D.getName().TemplateId
  6946. : nullptr,
  6947. TemplateParamLists, isFriend, isExplicitSpecialization,
  6948. Invalid)) {
  6949. if (TemplateParams->size() > 0) {
  6950. // This is a function template
  6951. // Check that we can declare a template here.
  6952. if (CheckTemplateDeclScope(S, TemplateParams))
  6953. NewFD->setInvalidDecl();
  6954. // A destructor cannot be a template.
  6955. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6956. Diag(NewFD->getLocation(), diag::err_destructor_template);
  6957. NewFD->setInvalidDecl();
  6958. }
  6959. // If we're adding a template to a dependent context, we may need to
  6960. // rebuilding some of the types used within the template parameter list,
  6961. // now that we know what the current instantiation is.
  6962. if (DC->isDependentContext()) {
  6963. ContextRAII SavedContext(*this, DC);
  6964. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  6965. Invalid = true;
  6966. }
  6967. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  6968. NewFD->getLocation(),
  6969. Name, TemplateParams,
  6970. NewFD);
  6971. FunctionTemplate->setLexicalDeclContext(CurContext);
  6972. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  6973. // For source fidelity, store the other template param lists.
  6974. if (TemplateParamLists.size() > 1) {
  6975. NewFD->setTemplateParameterListsInfo(Context,
  6976. TemplateParamLists.drop_back(1));
  6977. }
  6978. } else {
  6979. // This is a function template specialization.
  6980. isFunctionTemplateSpecialization = true;
  6981. // For source fidelity, store all the template param lists.
  6982. if (TemplateParamLists.size() > 0)
  6983. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  6984. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  6985. if (isFriend) {
  6986. // We want to remove the "template<>", found here.
  6987. SourceRange RemoveRange = TemplateParams->getSourceRange();
  6988. // If we remove the template<> and the name is not a
  6989. // template-id, we're actually silently creating a problem:
  6990. // the friend declaration will refer to an untemplated decl,
  6991. // and clearly the user wants a template specialization. So
  6992. // we need to insert '<>' after the name.
  6993. SourceLocation InsertLoc;
  6994. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  6995. InsertLoc = D.getName().getSourceRange().getEnd();
  6996. InsertLoc = getLocForEndOfToken(InsertLoc);
  6997. }
  6998. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  6999. << Name << RemoveRange
  7000. << FixItHint::CreateRemoval(RemoveRange)
  7001. << FixItHint::CreateInsertion(InsertLoc, "<>");
  7002. }
  7003. }
  7004. }
  7005. else {
  7006. // All template param lists were matched against the scope specifier:
  7007. // this is NOT (an explicit specialization of) a template.
  7008. if (TemplateParamLists.size() > 0)
  7009. // For source fidelity, store all the template param lists.
  7010. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7011. }
  7012. if (Invalid) {
  7013. NewFD->setInvalidDecl();
  7014. if (FunctionTemplate)
  7015. FunctionTemplate->setInvalidDecl();
  7016. }
  7017. // C++ [dcl.fct.spec]p5:
  7018. // The virtual specifier shall only be used in declarations of
  7019. // nonstatic class member functions that appear within a
  7020. // member-specification of a class declaration; see 10.3.
  7021. //
  7022. if (isVirtual && !NewFD->isInvalidDecl()) {
  7023. if (!isVirtualOkay) {
  7024. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7025. diag::err_virtual_non_function);
  7026. } else if (!CurContext->isRecord()) {
  7027. // 'virtual' was specified outside of the class.
  7028. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7029. diag::err_virtual_out_of_class)
  7030. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7031. } else if (NewFD->getDescribedFunctionTemplate()) {
  7032. // C++ [temp.mem]p3:
  7033. // A member function template shall not be virtual.
  7034. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7035. diag::err_virtual_member_function_template)
  7036. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7037. } else {
  7038. // Okay: Add virtual to the method.
  7039. NewFD->setVirtualAsWritten(true);
  7040. }
  7041. if (getLangOpts().CPlusPlus14 &&
  7042. NewFD->getReturnType()->isUndeducedType())
  7043. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  7044. }
  7045. if (getLangOpts().CPlusPlus14 &&
  7046. (NewFD->isDependentContext() ||
  7047. (isFriend && CurContext->isDependentContext())) &&
  7048. NewFD->getReturnType()->isUndeducedType()) {
  7049. // If the function template is referenced directly (for instance, as a
  7050. // member of the current instantiation), pretend it has a dependent type.
  7051. // This is not really justified by the standard, but is the only sane
  7052. // thing to do.
  7053. // FIXME: For a friend function, we have not marked the function as being
  7054. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  7055. const FunctionProtoType *FPT =
  7056. NewFD->getType()->castAs<FunctionProtoType>();
  7057. QualType Result =
  7058. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  7059. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  7060. FPT->getExtProtoInfo()));
  7061. }
  7062. // C++ [dcl.fct.spec]p3:
  7063. // The inline specifier shall not appear on a block scope function
  7064. // declaration.
  7065. if (isInline && !NewFD->isInvalidDecl()) {
  7066. if (CurContext->isFunctionOrMethod()) {
  7067. // 'inline' is not allowed on block scope function declaration.
  7068. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7069. diag::err_inline_declaration_block_scope) << Name
  7070. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7071. }
  7072. }
  7073. // C++ [dcl.fct.spec]p6:
  7074. // The explicit specifier shall be used only in the declaration of a
  7075. // constructor or conversion function within its class definition;
  7076. // see 12.3.1 and 12.3.2.
  7077. if (isExplicit && !NewFD->isInvalidDecl()) {
  7078. if (!CurContext->isRecord()) {
  7079. // 'explicit' was specified outside of the class.
  7080. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7081. diag::err_explicit_out_of_class)
  7082. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  7083. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  7084. !isa<CXXConversionDecl>(NewFD)) {
  7085. // 'explicit' was specified on a function that wasn't a constructor
  7086. // or conversion function.
  7087. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7088. diag::err_explicit_non_ctor_or_conv_function)
  7089. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  7090. }
  7091. }
  7092. if (isConstexpr) {
  7093. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  7094. // are implicitly inline.
  7095. NewFD->setImplicitlyInline();
  7096. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  7097. // be either constructors or to return a literal type. Therefore,
  7098. // destructors cannot be declared constexpr.
  7099. if (isa<CXXDestructorDecl>(NewFD))
  7100. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  7101. }
  7102. if (isConcept) {
  7103. // This is a function concept.
  7104. if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
  7105. FTD->setConcept();
  7106. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  7107. // applied only to the definition of a function template [...]
  7108. if (!D.isFunctionDefinition()) {
  7109. Diag(D.getDeclSpec().getConceptSpecLoc(),
  7110. diag::err_function_concept_not_defined);
  7111. NewFD->setInvalidDecl();
  7112. }
  7113. // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
  7114. // have no exception-specification and is treated as if it were specified
  7115. // with noexcept(true) (15.4). [...]
  7116. if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
  7117. if (FPT->hasExceptionSpec()) {
  7118. SourceRange Range;
  7119. if (D.isFunctionDeclarator())
  7120. Range = D.getFunctionTypeInfo().getExceptionSpecRange();
  7121. Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
  7122. << FixItHint::CreateRemoval(Range);
  7123. NewFD->setInvalidDecl();
  7124. } else {
  7125. Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
  7126. }
  7127. // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
  7128. // following restrictions:
  7129. // - The declared return type shall have the type bool.
  7130. if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
  7131. Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
  7132. NewFD->setInvalidDecl();
  7133. }
  7134. // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
  7135. // following restrictions:
  7136. // - The declaration's parameter list shall be equivalent to an empty
  7137. // parameter list.
  7138. if (FPT->getNumParams() > 0 || FPT->isVariadic())
  7139. Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
  7140. }
  7141. // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
  7142. // implicity defined to be a constexpr declaration (implicitly inline)
  7143. NewFD->setImplicitlyInline();
  7144. // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
  7145. // be declared with the thread_local, inline, friend, or constexpr
  7146. // specifiers, [...]
  7147. if (isInline) {
  7148. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7149. diag::err_concept_decl_invalid_specifiers)
  7150. << 1 << 1;
  7151. NewFD->setInvalidDecl(true);
  7152. }
  7153. if (isFriend) {
  7154. Diag(D.getDeclSpec().getFriendSpecLoc(),
  7155. diag::err_concept_decl_invalid_specifiers)
  7156. << 1 << 2;
  7157. NewFD->setInvalidDecl(true);
  7158. }
  7159. if (isConstexpr) {
  7160. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  7161. diag::err_concept_decl_invalid_specifiers)
  7162. << 1 << 3;
  7163. NewFD->setInvalidDecl(true);
  7164. }
  7165. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  7166. // applied only to the definition of a function template or variable
  7167. // template, declared in namespace scope.
  7168. if (isFunctionTemplateSpecialization) {
  7169. Diag(D.getDeclSpec().getConceptSpecLoc(),
  7170. diag::err_concept_specified_specialization) << 1;
  7171. NewFD->setInvalidDecl(true);
  7172. return NewFD;
  7173. }
  7174. }
  7175. // If __module_private__ was specified, mark the function accordingly.
  7176. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7177. if (isFunctionTemplateSpecialization) {
  7178. SourceLocation ModulePrivateLoc
  7179. = D.getDeclSpec().getModulePrivateSpecLoc();
  7180. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  7181. << 0
  7182. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7183. } else {
  7184. NewFD->setModulePrivate();
  7185. if (FunctionTemplate)
  7186. FunctionTemplate->setModulePrivate();
  7187. }
  7188. }
  7189. if (isFriend) {
  7190. if (FunctionTemplate) {
  7191. FunctionTemplate->setObjectOfFriendDecl();
  7192. FunctionTemplate->setAccess(AS_public);
  7193. }
  7194. NewFD->setObjectOfFriendDecl();
  7195. NewFD->setAccess(AS_public);
  7196. }
  7197. // If a function is defined as defaulted or deleted, mark it as such now.
  7198. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  7199. // definition kind to FDK_Definition.
  7200. switch (D.getFunctionDefinitionKind()) {
  7201. case FDK_Declaration:
  7202. case FDK_Definition:
  7203. break;
  7204. case FDK_Defaulted:
  7205. NewFD->setDefaulted();
  7206. break;
  7207. case FDK_Deleted:
  7208. NewFD->setDeletedAsWritten();
  7209. break;
  7210. }
  7211. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  7212. D.isFunctionDefinition()) {
  7213. // C++ [class.mfct]p2:
  7214. // A member function may be defined (8.4) in its class definition, in
  7215. // which case it is an inline member function (7.1.2)
  7216. NewFD->setImplicitlyInline();
  7217. }
  7218. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  7219. !CurContext->isRecord()) {
  7220. // C++ [class.static]p1:
  7221. // A data or function member of a class may be declared static
  7222. // in a class definition, in which case it is a static member of
  7223. // the class.
  7224. // Complain about the 'static' specifier if it's on an out-of-line
  7225. // member function definition.
  7226. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7227. diag::err_static_out_of_line)
  7228. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7229. }
  7230. // C++11 [except.spec]p15:
  7231. // A deallocation function with no exception-specification is treated
  7232. // as if it were specified with noexcept(true).
  7233. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  7234. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  7235. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  7236. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  7237. NewFD->setType(Context.getFunctionType(
  7238. FPT->getReturnType(), FPT->getParamTypes(),
  7239. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  7240. }
  7241. // Filter out previous declarations that don't match the scope.
  7242. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  7243. D.getCXXScopeSpec().isNotEmpty() ||
  7244. isExplicitSpecialization ||
  7245. isFunctionTemplateSpecialization);
  7246. // Handle GNU asm-label extension (encoded as an attribute).
  7247. if (Expr *E = (Expr*) D.getAsmLabel()) {
  7248. // The parser guarantees this is a string.
  7249. StringLiteral *SE = cast<StringLiteral>(E);
  7250. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  7251. SE->getString(), 0));
  7252. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7253. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7254. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  7255. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7256. if (isDeclExternC(NewFD)) {
  7257. NewFD->addAttr(I->second);
  7258. ExtnameUndeclaredIdentifiers.erase(I);
  7259. } else
  7260. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  7261. << /*Variable*/0 << NewFD;
  7262. }
  7263. }
  7264. // Copy the parameter declarations from the declarator D to the function
  7265. // declaration NewFD, if they are available. First scavenge them into Params.
  7266. SmallVector<ParmVarDecl*, 16> Params;
  7267. if (D.isFunctionDeclarator()) {
  7268. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7269. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  7270. // function that takes no arguments, not a function that takes a
  7271. // single void argument.
  7272. // We let through "const void" here because Sema::GetTypeForDeclarator
  7273. // already checks for that case.
  7274. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  7275. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  7276. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  7277. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  7278. Param->setDeclContext(NewFD);
  7279. Params.push_back(Param);
  7280. if (Param->isInvalidDecl())
  7281. NewFD->setInvalidDecl();
  7282. }
  7283. }
  7284. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  7285. // When we're declaring a function with a typedef, typeof, etc as in the
  7286. // following example, we'll need to synthesize (unnamed)
  7287. // parameters for use in the declaration.
  7288. //
  7289. // @code
  7290. // typedef void fn(int);
  7291. // fn f;
  7292. // @endcode
  7293. // Synthesize a parameter for each argument type.
  7294. for (const auto &AI : FT->param_types()) {
  7295. ParmVarDecl *Param =
  7296. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  7297. Param->setScopeInfo(0, Params.size());
  7298. Params.push_back(Param);
  7299. }
  7300. } else {
  7301. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  7302. "Should not need args for typedef of non-prototype fn");
  7303. }
  7304. // Finally, we know we have the right number of parameters, install them.
  7305. NewFD->setParams(Params);
  7306. // Find all anonymous symbols defined during the declaration of this function
  7307. // and add to NewFD. This lets us track decls such 'enum Y' in:
  7308. //
  7309. // void f(enum Y {AA} x) {}
  7310. //
  7311. // which would otherwise incorrectly end up in the translation unit scope.
  7312. NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
  7313. DeclsInPrototypeScope.clear();
  7314. if (D.getDeclSpec().isNoreturnSpecified())
  7315. NewFD->addAttr(
  7316. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  7317. Context, 0));
  7318. // Functions returning a variably modified type violate C99 6.7.5.2p2
  7319. // because all functions have linkage.
  7320. if (!NewFD->isInvalidDecl() &&
  7321. NewFD->getReturnType()->isVariablyModifiedType()) {
  7322. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  7323. NewFD->setInvalidDecl();
  7324. }
  7325. // Apply an implicit SectionAttr if #pragma code_seg is active.
  7326. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  7327. !NewFD->hasAttr<SectionAttr>()) {
  7328. NewFD->addAttr(
  7329. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  7330. CodeSegStack.CurrentValue->getString(),
  7331. CodeSegStack.CurrentPragmaLocation));
  7332. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  7333. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  7334. ASTContext::PSF_Read,
  7335. NewFD))
  7336. NewFD->dropAttr<SectionAttr>();
  7337. }
  7338. // Handle attributes.
  7339. ProcessDeclAttributes(S, NewFD, D);
  7340. if (getLangOpts().CUDA)
  7341. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  7342. if (getLangOpts().OpenCL) {
  7343. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  7344. // type declaration will generate a compilation error.
  7345. unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
  7346. if (AddressSpace == LangAS::opencl_local ||
  7347. AddressSpace == LangAS::opencl_global ||
  7348. AddressSpace == LangAS::opencl_constant) {
  7349. Diag(NewFD->getLocation(),
  7350. diag::err_opencl_return_value_with_address_space);
  7351. NewFD->setInvalidDecl();
  7352. }
  7353. }
  7354. if (!getLangOpts().CPlusPlus) {
  7355. // Perform semantic checking on the function declaration.
  7356. bool isExplicitSpecialization=false;
  7357. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7358. CheckMain(NewFD, D.getDeclSpec());
  7359. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7360. CheckMSVCRTEntryPoint(NewFD);
  7361. if (!NewFD->isInvalidDecl())
  7362. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7363. isExplicitSpecialization));
  7364. else if (!Previous.empty())
  7365. // Recover gracefully from an invalid redeclaration.
  7366. D.setRedeclaration(true);
  7367. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7368. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7369. "previous declaration set still overloaded");
  7370. // Diagnose no-prototype function declarations with calling conventions that
  7371. // don't support variadic calls. Only do this in C and do it after merging
  7372. // possibly prototyped redeclarations.
  7373. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  7374. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  7375. CallingConv CC = FT->getExtInfo().getCC();
  7376. if (!supportsVariadicCall(CC)) {
  7377. // Windows system headers sometimes accidentally use stdcall without
  7378. // (void) parameters, so we relax this to a warning.
  7379. int DiagID =
  7380. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  7381. Diag(NewFD->getLocation(), DiagID)
  7382. << FunctionType::getNameForCallConv(CC);
  7383. }
  7384. }
  7385. } else {
  7386. // C++11 [replacement.functions]p3:
  7387. // The program's definitions shall not be specified as inline.
  7388. //
  7389. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  7390. //
  7391. // Suppress the diagnostic if the function is __attribute__((used)), since
  7392. // that forces an external definition to be emitted.
  7393. if (D.getDeclSpec().isInlineSpecified() &&
  7394. NewFD->isReplaceableGlobalAllocationFunction() &&
  7395. !NewFD->hasAttr<UsedAttr>())
  7396. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7397. diag::ext_operator_new_delete_declared_inline)
  7398. << NewFD->getDeclName();
  7399. // If the declarator is a template-id, translate the parser's template
  7400. // argument list into our AST format.
  7401. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  7402. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  7403. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  7404. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  7405. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  7406. TemplateId->NumArgs);
  7407. translateTemplateArguments(TemplateArgsPtr,
  7408. TemplateArgs);
  7409. HasExplicitTemplateArgs = true;
  7410. if (NewFD->isInvalidDecl()) {
  7411. HasExplicitTemplateArgs = false;
  7412. } else if (FunctionTemplate) {
  7413. // Function template with explicit template arguments.
  7414. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  7415. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  7416. HasExplicitTemplateArgs = false;
  7417. } else {
  7418. assert((isFunctionTemplateSpecialization ||
  7419. D.getDeclSpec().isFriendSpecified()) &&
  7420. "should have a 'template<>' for this decl");
  7421. // "friend void foo<>(int);" is an implicit specialization decl.
  7422. isFunctionTemplateSpecialization = true;
  7423. }
  7424. } else if (isFriend && isFunctionTemplateSpecialization) {
  7425. // This combination is only possible in a recovery case; the user
  7426. // wrote something like:
  7427. // template <> friend void foo(int);
  7428. // which we're recovering from as if the user had written:
  7429. // friend void foo<>(int);
  7430. // Go ahead and fake up a template id.
  7431. HasExplicitTemplateArgs = true;
  7432. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  7433. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  7434. }
  7435. // If it's a friend (and only if it's a friend), it's possible
  7436. // that either the specialized function type or the specialized
  7437. // template is dependent, and therefore matching will fail. In
  7438. // this case, don't check the specialization yet.
  7439. bool InstantiationDependent = false;
  7440. if (isFunctionTemplateSpecialization && isFriend &&
  7441. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  7442. TemplateSpecializationType::anyDependentTemplateArguments(
  7443. TemplateArgs,
  7444. InstantiationDependent))) {
  7445. assert(HasExplicitTemplateArgs &&
  7446. "friend function specialization without template args");
  7447. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  7448. Previous))
  7449. NewFD->setInvalidDecl();
  7450. } else if (isFunctionTemplateSpecialization) {
  7451. if (CurContext->isDependentContext() && CurContext->isRecord()
  7452. && !isFriend) {
  7453. isDependentClassScopeExplicitSpecialization = true;
  7454. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  7455. diag::ext_function_specialization_in_class :
  7456. diag::err_function_specialization_in_class)
  7457. << NewFD->getDeclName();
  7458. } else if (CheckFunctionTemplateSpecialization(NewFD,
  7459. (HasExplicitTemplateArgs ? &TemplateArgs
  7460. : nullptr),
  7461. Previous))
  7462. NewFD->setInvalidDecl();
  7463. // C++ [dcl.stc]p1:
  7464. // A storage-class-specifier shall not be specified in an explicit
  7465. // specialization (14.7.3)
  7466. FunctionTemplateSpecializationInfo *Info =
  7467. NewFD->getTemplateSpecializationInfo();
  7468. if (Info && SC != SC_None) {
  7469. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  7470. Diag(NewFD->getLocation(),
  7471. diag::err_explicit_specialization_inconsistent_storage_class)
  7472. << SC
  7473. << FixItHint::CreateRemoval(
  7474. D.getDeclSpec().getStorageClassSpecLoc());
  7475. else
  7476. Diag(NewFD->getLocation(),
  7477. diag::ext_explicit_specialization_storage_class)
  7478. << FixItHint::CreateRemoval(
  7479. D.getDeclSpec().getStorageClassSpecLoc());
  7480. }
  7481. } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
  7482. if (CheckMemberSpecialization(NewFD, Previous))
  7483. NewFD->setInvalidDecl();
  7484. }
  7485. // Perform semantic checking on the function declaration.
  7486. if (!isDependentClassScopeExplicitSpecialization) {
  7487. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7488. CheckMain(NewFD, D.getDeclSpec());
  7489. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7490. CheckMSVCRTEntryPoint(NewFD);
  7491. if (!NewFD->isInvalidDecl())
  7492. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7493. isExplicitSpecialization));
  7494. else if (!Previous.empty())
  7495. // Recover gracefully from an invalid redeclaration.
  7496. D.setRedeclaration(true);
  7497. }
  7498. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7499. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7500. "previous declaration set still overloaded");
  7501. NamedDecl *PrincipalDecl = (FunctionTemplate
  7502. ? cast<NamedDecl>(FunctionTemplate)
  7503. : NewFD);
  7504. if (isFriend && NewFD->getPreviousDecl()) {
  7505. AccessSpecifier Access = AS_public;
  7506. if (!NewFD->isInvalidDecl())
  7507. Access = NewFD->getPreviousDecl()->getAccess();
  7508. NewFD->setAccess(Access);
  7509. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  7510. }
  7511. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  7512. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  7513. PrincipalDecl->setNonMemberOperator();
  7514. // If we have a function template, check the template parameter
  7515. // list. This will check and merge default template arguments.
  7516. if (FunctionTemplate) {
  7517. FunctionTemplateDecl *PrevTemplate =
  7518. FunctionTemplate->getPreviousDecl();
  7519. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  7520. PrevTemplate ? PrevTemplate->getTemplateParameters()
  7521. : nullptr,
  7522. D.getDeclSpec().isFriendSpecified()
  7523. ? (D.isFunctionDefinition()
  7524. ? TPC_FriendFunctionTemplateDefinition
  7525. : TPC_FriendFunctionTemplate)
  7526. : (D.getCXXScopeSpec().isSet() &&
  7527. DC && DC->isRecord() &&
  7528. DC->isDependentContext())
  7529. ? TPC_ClassTemplateMember
  7530. : TPC_FunctionTemplate);
  7531. }
  7532. if (NewFD->isInvalidDecl()) {
  7533. // Ignore all the rest of this.
  7534. } else if (!D.isRedeclaration()) {
  7535. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  7536. AddToScope };
  7537. // Fake up an access specifier if it's supposed to be a class member.
  7538. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  7539. NewFD->setAccess(AS_public);
  7540. // Qualified decls generally require a previous declaration.
  7541. if (D.getCXXScopeSpec().isSet()) {
  7542. // ...with the major exception of templated-scope or
  7543. // dependent-scope friend declarations.
  7544. // TODO: we currently also suppress this check in dependent
  7545. // contexts because (1) the parameter depth will be off when
  7546. // matching friend templates and (2) we might actually be
  7547. // selecting a friend based on a dependent factor. But there
  7548. // are situations where these conditions don't apply and we
  7549. // can actually do this check immediately.
  7550. if (isFriend &&
  7551. (TemplateParamLists.size() ||
  7552. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  7553. CurContext->isDependentContext())) {
  7554. // ignore these
  7555. } else {
  7556. // The user tried to provide an out-of-line definition for a
  7557. // function that is a member of a class or namespace, but there
  7558. // was no such member function declared (C++ [class.mfct]p2,
  7559. // C++ [namespace.memdef]p2). For example:
  7560. //
  7561. // class X {
  7562. // void f() const;
  7563. // };
  7564. //
  7565. // void X::f() { } // ill-formed
  7566. //
  7567. // Complain about this problem, and attempt to suggest close
  7568. // matches (e.g., those that differ only in cv-qualifiers and
  7569. // whether the parameter types are references).
  7570. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7571. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  7572. AddToScope = ExtraArgs.AddToScope;
  7573. return Result;
  7574. }
  7575. }
  7576. // Unqualified local friend declarations are required to resolve
  7577. // to something.
  7578. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  7579. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7580. *this, Previous, NewFD, ExtraArgs, true, S)) {
  7581. AddToScope = ExtraArgs.AddToScope;
  7582. return Result;
  7583. }
  7584. }
  7585. } else if (!D.isFunctionDefinition() &&
  7586. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  7587. !isFriend && !isFunctionTemplateSpecialization &&
  7588. !isExplicitSpecialization) {
  7589. // An out-of-line member function declaration must also be a
  7590. // definition (C++ [class.mfct]p2).
  7591. // Note that this is not the case for explicit specializations of
  7592. // function templates or member functions of class templates, per
  7593. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  7594. // extension for compatibility with old SWIG code which likes to
  7595. // generate them.
  7596. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  7597. << D.getCXXScopeSpec().getRange();
  7598. }
  7599. }
  7600. ProcessPragmaWeak(S, NewFD);
  7601. checkAttributesAfterMerging(*this, *NewFD);
  7602. AddKnownFunctionAttributes(NewFD);
  7603. if (NewFD->hasAttr<OverloadableAttr>() &&
  7604. !NewFD->getType()->getAs<FunctionProtoType>()) {
  7605. Diag(NewFD->getLocation(),
  7606. diag::err_attribute_overloadable_no_prototype)
  7607. << NewFD;
  7608. // Turn this into a variadic function with no parameters.
  7609. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  7610. FunctionProtoType::ExtProtoInfo EPI(
  7611. Context.getDefaultCallingConvention(true, false));
  7612. EPI.Variadic = true;
  7613. EPI.ExtInfo = FT->getExtInfo();
  7614. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  7615. NewFD->setType(R);
  7616. }
  7617. // If there's a #pragma GCC visibility in scope, and this isn't a class
  7618. // member, set the visibility of this function.
  7619. if (!DC->isRecord() && NewFD->isExternallyVisible())
  7620. AddPushedVisibilityAttribute(NewFD);
  7621. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  7622. // marking the function.
  7623. AddCFAuditedAttribute(NewFD);
  7624. // If this is a function definition, check if we have to apply optnone due to
  7625. // a pragma.
  7626. if(D.isFunctionDefinition())
  7627. AddRangeBasedOptnone(NewFD);
  7628. // If this is the first declaration of an extern C variable, update
  7629. // the map of such variables.
  7630. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  7631. isIncompleteDeclExternC(*this, NewFD))
  7632. RegisterLocallyScopedExternCDecl(NewFD, S);
  7633. // Set this FunctionDecl's range up to the right paren.
  7634. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  7635. if (D.isRedeclaration() && !Previous.empty()) {
  7636. checkDLLAttributeRedeclaration(
  7637. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
  7638. isExplicitSpecialization || isFunctionTemplateSpecialization,
  7639. D.isFunctionDefinition());
  7640. }
  7641. if (getLangOpts().CUDA) {
  7642. IdentifierInfo *II = NewFD->getIdentifier();
  7643. if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
  7644. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  7645. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  7646. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  7647. Context.setcudaConfigureCallDecl(NewFD);
  7648. }
  7649. // Variadic functions, other than a *declaration* of printf, are not allowed
  7650. // in device-side CUDA code, unless someone passed
  7651. // -fcuda-allow-variadic-functions.
  7652. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  7653. (NewFD->hasAttr<CUDADeviceAttr>() ||
  7654. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  7655. !(II && II->isStr("printf") && NewFD->isExternC() &&
  7656. !D.isFunctionDefinition())) {
  7657. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  7658. }
  7659. }
  7660. if (getLangOpts().CPlusPlus) {
  7661. if (FunctionTemplate) {
  7662. if (NewFD->isInvalidDecl())
  7663. FunctionTemplate->setInvalidDecl();
  7664. return FunctionTemplate;
  7665. }
  7666. }
  7667. if (NewFD->hasAttr<OpenCLKernelAttr>()) {
  7668. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  7669. if ((getLangOpts().OpenCLVersion >= 120)
  7670. && (SC == SC_Static)) {
  7671. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  7672. D.setInvalidType();
  7673. }
  7674. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  7675. if (!NewFD->getReturnType()->isVoidType()) {
  7676. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  7677. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  7678. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  7679. : FixItHint());
  7680. D.setInvalidType();
  7681. }
  7682. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  7683. for (auto Param : NewFD->parameters())
  7684. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  7685. }
  7686. for (const ParmVarDecl *Param : NewFD->parameters()) {
  7687. QualType PT = Param->getType();
  7688. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  7689. // types.
  7690. if (getLangOpts().OpenCLVersion >= 200) {
  7691. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  7692. QualType ElemTy = PipeTy->getElementType();
  7693. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  7694. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  7695. D.setInvalidType();
  7696. }
  7697. }
  7698. }
  7699. }
  7700. MarkUnusedFileScopedDecl(NewFD);
  7701. // Here we have an function template explicit specialization at class scope.
  7702. // The actually specialization will be postponed to template instatiation
  7703. // time via the ClassScopeFunctionSpecializationDecl node.
  7704. if (isDependentClassScopeExplicitSpecialization) {
  7705. ClassScopeFunctionSpecializationDecl *NewSpec =
  7706. ClassScopeFunctionSpecializationDecl::Create(
  7707. Context, CurContext, SourceLocation(),
  7708. cast<CXXMethodDecl>(NewFD),
  7709. HasExplicitTemplateArgs, TemplateArgs);
  7710. CurContext->addDecl(NewSpec);
  7711. AddToScope = false;
  7712. }
  7713. return NewFD;
  7714. }
  7715. /// \brief Checks if the new declaration declared in dependent context must be
  7716. /// put in the same redeclaration chain as the specified declaration.
  7717. ///
  7718. /// \param D Declaration that is checked.
  7719. /// \param PrevDecl Previous declaration found with proper lookup method for the
  7720. /// same declaration name.
  7721. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  7722. /// belongs to.
  7723. ///
  7724. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  7725. // Any declarations should be put into redeclaration chains except for
  7726. // friend declaration in a dependent context that names a function in
  7727. // namespace scope.
  7728. //
  7729. // This allows to compile code like:
  7730. //
  7731. // void func();
  7732. // template<typename T> class C1 { friend void func() { } };
  7733. // template<typename T> class C2 { friend void func() { } };
  7734. //
  7735. // This code snippet is a valid code unless both templates are instantiated.
  7736. return !(D->getLexicalDeclContext()->isDependentContext() &&
  7737. D->getDeclContext()->isFileContext() &&
  7738. D->getFriendObjectKind() != Decl::FOK_None);
  7739. }
  7740. /// \brief Perform semantic checking of a new function declaration.
  7741. ///
  7742. /// Performs semantic analysis of the new function declaration
  7743. /// NewFD. This routine performs all semantic checking that does not
  7744. /// require the actual declarator involved in the declaration, and is
  7745. /// used both for the declaration of functions as they are parsed
  7746. /// (called via ActOnDeclarator) and for the declaration of functions
  7747. /// that have been instantiated via C++ template instantiation (called
  7748. /// via InstantiateDecl).
  7749. ///
  7750. /// \param IsExplicitSpecialization whether this new function declaration is
  7751. /// an explicit specialization of the previous declaration.
  7752. ///
  7753. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  7754. ///
  7755. /// \returns true if the function declaration is a redeclaration.
  7756. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  7757. LookupResult &Previous,
  7758. bool IsExplicitSpecialization) {
  7759. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  7760. "Variably modified return types are not handled here");
  7761. // Determine whether the type of this function should be merged with
  7762. // a previous visible declaration. This never happens for functions in C++,
  7763. // and always happens in C if the previous declaration was visible.
  7764. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  7765. !Previous.isShadowed();
  7766. bool Redeclaration = false;
  7767. NamedDecl *OldDecl = nullptr;
  7768. // Merge or overload the declaration with an existing declaration of
  7769. // the same name, if appropriate.
  7770. if (!Previous.empty()) {
  7771. // Determine whether NewFD is an overload of PrevDecl or
  7772. // a declaration that requires merging. If it's an overload,
  7773. // there's no more work to do here; we'll just add the new
  7774. // function to the scope.
  7775. if (!AllowOverloadingOfFunction(Previous, Context)) {
  7776. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  7777. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  7778. Redeclaration = true;
  7779. OldDecl = Candidate;
  7780. }
  7781. } else {
  7782. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  7783. /*NewIsUsingDecl*/ false)) {
  7784. case Ovl_Match:
  7785. Redeclaration = true;
  7786. break;
  7787. case Ovl_NonFunction:
  7788. Redeclaration = true;
  7789. break;
  7790. case Ovl_Overload:
  7791. Redeclaration = false;
  7792. break;
  7793. }
  7794. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  7795. // If a function name is overloadable in C, then every function
  7796. // with that name must be marked "overloadable".
  7797. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  7798. << Redeclaration << NewFD;
  7799. NamedDecl *OverloadedDecl = nullptr;
  7800. if (Redeclaration)
  7801. OverloadedDecl = OldDecl;
  7802. else if (!Previous.empty())
  7803. OverloadedDecl = Previous.getRepresentativeDecl();
  7804. if (OverloadedDecl)
  7805. Diag(OverloadedDecl->getLocation(),
  7806. diag::note_attribute_overloadable_prev_overload);
  7807. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  7808. }
  7809. }
  7810. }
  7811. // Check for a previous extern "C" declaration with this name.
  7812. if (!Redeclaration &&
  7813. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  7814. if (!Previous.empty()) {
  7815. // This is an extern "C" declaration with the same name as a previous
  7816. // declaration, and thus redeclares that entity...
  7817. Redeclaration = true;
  7818. OldDecl = Previous.getFoundDecl();
  7819. MergeTypeWithPrevious = false;
  7820. // ... except in the presence of __attribute__((overloadable)).
  7821. if (OldDecl->hasAttr<OverloadableAttr>()) {
  7822. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  7823. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  7824. << Redeclaration << NewFD;
  7825. Diag(Previous.getFoundDecl()->getLocation(),
  7826. diag::note_attribute_overloadable_prev_overload);
  7827. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  7828. }
  7829. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  7830. Redeclaration = false;
  7831. OldDecl = nullptr;
  7832. }
  7833. }
  7834. }
  7835. }
  7836. // C++11 [dcl.constexpr]p8:
  7837. // A constexpr specifier for a non-static member function that is not
  7838. // a constructor declares that member function to be const.
  7839. //
  7840. // This needs to be delayed until we know whether this is an out-of-line
  7841. // definition of a static member function.
  7842. //
  7843. // This rule is not present in C++1y, so we produce a backwards
  7844. // compatibility warning whenever it happens in C++11.
  7845. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  7846. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  7847. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  7848. (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
  7849. CXXMethodDecl *OldMD = nullptr;
  7850. if (OldDecl)
  7851. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  7852. if (!OldMD || !OldMD->isStatic()) {
  7853. const FunctionProtoType *FPT =
  7854. MD->getType()->castAs<FunctionProtoType>();
  7855. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  7856. EPI.TypeQuals |= Qualifiers::Const;
  7857. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  7858. FPT->getParamTypes(), EPI));
  7859. // Warn that we did this, if we're not performing template instantiation.
  7860. // In that case, we'll have warned already when the template was defined.
  7861. if (ActiveTemplateInstantiations.empty()) {
  7862. SourceLocation AddConstLoc;
  7863. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  7864. .IgnoreParens().getAs<FunctionTypeLoc>())
  7865. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  7866. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  7867. << FixItHint::CreateInsertion(AddConstLoc, " const");
  7868. }
  7869. }
  7870. }
  7871. if (Redeclaration) {
  7872. // NewFD and OldDecl represent declarations that need to be
  7873. // merged.
  7874. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  7875. NewFD->setInvalidDecl();
  7876. return Redeclaration;
  7877. }
  7878. Previous.clear();
  7879. Previous.addDecl(OldDecl);
  7880. if (FunctionTemplateDecl *OldTemplateDecl
  7881. = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  7882. NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
  7883. FunctionTemplateDecl *NewTemplateDecl
  7884. = NewFD->getDescribedFunctionTemplate();
  7885. assert(NewTemplateDecl && "Template/non-template mismatch");
  7886. if (CXXMethodDecl *Method
  7887. = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
  7888. Method->setAccess(OldTemplateDecl->getAccess());
  7889. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  7890. }
  7891. // If this is an explicit specialization of a member that is a function
  7892. // template, mark it as a member specialization.
  7893. if (IsExplicitSpecialization &&
  7894. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  7895. NewTemplateDecl->setMemberSpecialization();
  7896. assert(OldTemplateDecl->isMemberSpecialization());
  7897. // Explicit specializations of a member template do not inherit deleted
  7898. // status from the parent member template that they are specializing.
  7899. if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
  7900. FunctionDecl *const OldTemplatedDecl =
  7901. OldTemplateDecl->getTemplatedDecl();
  7902. assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
  7903. OldTemplatedDecl->setDeletedAsWritten(false);
  7904. }
  7905. }
  7906. } else {
  7907. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  7908. // This needs to happen first so that 'inline' propagates.
  7909. NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
  7910. if (isa<CXXMethodDecl>(NewFD))
  7911. NewFD->setAccess(OldDecl->getAccess());
  7912. }
  7913. }
  7914. }
  7915. // Semantic checking for this function declaration (in isolation).
  7916. if (getLangOpts().CPlusPlus) {
  7917. // C++-specific checks.
  7918. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  7919. CheckConstructor(Constructor);
  7920. } else if (CXXDestructorDecl *Destructor =
  7921. dyn_cast<CXXDestructorDecl>(NewFD)) {
  7922. CXXRecordDecl *Record = Destructor->getParent();
  7923. QualType ClassType = Context.getTypeDeclType(Record);
  7924. // FIXME: Shouldn't we be able to perform this check even when the class
  7925. // type is dependent? Both gcc and edg can handle that.
  7926. if (!ClassType->isDependentType()) {
  7927. DeclarationName Name
  7928. = Context.DeclarationNames.getCXXDestructorName(
  7929. Context.getCanonicalType(ClassType));
  7930. if (NewFD->getDeclName() != Name) {
  7931. Diag(NewFD->getLocation(), diag::err_destructor_name);
  7932. NewFD->setInvalidDecl();
  7933. return Redeclaration;
  7934. }
  7935. }
  7936. } else if (CXXConversionDecl *Conversion
  7937. = dyn_cast<CXXConversionDecl>(NewFD)) {
  7938. ActOnConversionDeclarator(Conversion);
  7939. }
  7940. // Find any virtual functions that this function overrides.
  7941. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  7942. if (!Method->isFunctionTemplateSpecialization() &&
  7943. !Method->getDescribedFunctionTemplate() &&
  7944. Method->isCanonicalDecl()) {
  7945. if (AddOverriddenMethods(Method->getParent(), Method)) {
  7946. // If the function was marked as "static", we have a problem.
  7947. if (NewFD->getStorageClass() == SC_Static) {
  7948. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  7949. }
  7950. }
  7951. }
  7952. if (Method->isStatic())
  7953. checkThisInStaticMemberFunctionType(Method);
  7954. }
  7955. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  7956. if (NewFD->isOverloadedOperator() &&
  7957. CheckOverloadedOperatorDeclaration(NewFD)) {
  7958. NewFD->setInvalidDecl();
  7959. return Redeclaration;
  7960. }
  7961. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  7962. if (NewFD->getLiteralIdentifier() &&
  7963. CheckLiteralOperatorDeclaration(NewFD)) {
  7964. NewFD->setInvalidDecl();
  7965. return Redeclaration;
  7966. }
  7967. // In C++, check default arguments now that we have merged decls. Unless
  7968. // the lexical context is the class, because in this case this is done
  7969. // during delayed parsing anyway.
  7970. if (!CurContext->isRecord())
  7971. CheckCXXDefaultArguments(NewFD);
  7972. // If this function declares a builtin function, check the type of this
  7973. // declaration against the expected type for the builtin.
  7974. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  7975. ASTContext::GetBuiltinTypeError Error;
  7976. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  7977. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  7978. if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
  7979. auto WithoutExceptionSpec = [&](QualType T) -> QualType {
  7980. auto *Proto = T->getAs<FunctionProtoType>();
  7981. if (!Proto)
  7982. return T;
  7983. return Context.getFunctionType(
  7984. Proto->getReturnType(), Proto->getParamTypes(),
  7985. Proto->getExtProtoInfo().withExceptionSpec(EST_None));
  7986. };
  7987. // If the type of the builtin differs only in its exception
  7988. // specification, that's OK.
  7989. // FIXME: If the types do differ in this way, it would be better to
  7990. // retain the 'noexcept' form of the type.
  7991. if (!getLangOpts().CPlusPlus1z ||
  7992. !Context.hasSameType(WithoutExceptionSpec(T),
  7993. WithoutExceptionSpec(NewFD->getType())))
  7994. // The type of this function differs from the type of the builtin,
  7995. // so forget about the builtin entirely.
  7996. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  7997. }
  7998. }
  7999. // If this function is declared as being extern "C", then check to see if
  8000. // the function returns a UDT (class, struct, or union type) that is not C
  8001. // compatible, and if it does, warn the user.
  8002. // But, issue any diagnostic on the first declaration only.
  8003. if (Previous.empty() && NewFD->isExternC()) {
  8004. QualType R = NewFD->getReturnType();
  8005. if (R->isIncompleteType() && !R->isVoidType())
  8006. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  8007. << NewFD << R;
  8008. else if (!R.isPODType(Context) && !R->isVoidType() &&
  8009. !R->isObjCObjectPointerType())
  8010. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  8011. }
  8012. // C++1z [dcl.fct]p6:
  8013. // [...] whether the function has a non-throwing exception-specification
  8014. // [is] part of the function type
  8015. //
  8016. // This results in an ABI break between C++14 and C++17 for functions whose
  8017. // declared type includes an exception-specification in a parameter or
  8018. // return type. (Exception specifications on the function itself are OK in
  8019. // most cases, and exception specifications are not permitted in most other
  8020. // contexts where they could make it into a mangling.)
  8021. if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
  8022. auto HasNoexcept = [&](QualType T) -> bool {
  8023. // Strip off declarator chunks that could be between us and a function
  8024. // type. We don't need to look far, exception specifications are very
  8025. // restricted prior to C++17.
  8026. if (auto *RT = T->getAs<ReferenceType>())
  8027. T = RT->getPointeeType();
  8028. else if (T->isAnyPointerType())
  8029. T = T->getPointeeType();
  8030. else if (auto *MPT = T->getAs<MemberPointerType>())
  8031. T = MPT->getPointeeType();
  8032. if (auto *FPT = T->getAs<FunctionProtoType>())
  8033. if (FPT->isNothrow(Context))
  8034. return true;
  8035. return false;
  8036. };
  8037. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  8038. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  8039. for (QualType T : FPT->param_types())
  8040. AnyNoexcept |= HasNoexcept(T);
  8041. if (AnyNoexcept)
  8042. Diag(NewFD->getLocation(),
  8043. diag::warn_cxx1z_compat_exception_spec_in_signature)
  8044. << NewFD;
  8045. }
  8046. if (!Redeclaration && LangOpts.CUDA)
  8047. checkCUDATargetOverload(NewFD, Previous);
  8048. }
  8049. return Redeclaration;
  8050. }
  8051. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  8052. // C++11 [basic.start.main]p3:
  8053. // A program that [...] declares main to be inline, static or
  8054. // constexpr is ill-formed.
  8055. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  8056. // appear in a declaration of main.
  8057. // static main is not an error under C99, but we should warn about it.
  8058. // We accept _Noreturn main as an extension.
  8059. if (FD->getStorageClass() == SC_Static)
  8060. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  8061. ? diag::err_static_main : diag::warn_static_main)
  8062. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  8063. if (FD->isInlineSpecified())
  8064. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  8065. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  8066. if (DS.isNoreturnSpecified()) {
  8067. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  8068. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  8069. Diag(NoreturnLoc, diag::ext_noreturn_main);
  8070. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  8071. << FixItHint::CreateRemoval(NoreturnRange);
  8072. }
  8073. if (FD->isConstexpr()) {
  8074. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  8075. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  8076. FD->setConstexpr(false);
  8077. }
  8078. if (getLangOpts().OpenCL) {
  8079. Diag(FD->getLocation(), diag::err_opencl_no_main)
  8080. << FD->hasAttr<OpenCLKernelAttr>();
  8081. FD->setInvalidDecl();
  8082. return;
  8083. }
  8084. QualType T = FD->getType();
  8085. assert(T->isFunctionType() && "function decl is not of function type");
  8086. const FunctionType* FT = T->castAs<FunctionType>();
  8087. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  8088. // In C with GNU extensions we allow main() to have non-integer return
  8089. // type, but we should warn about the extension, and we disable the
  8090. // implicit-return-zero rule.
  8091. // GCC in C mode accepts qualified 'int'.
  8092. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  8093. FD->setHasImplicitReturnZero(true);
  8094. else {
  8095. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  8096. SourceRange RTRange = FD->getReturnTypeSourceRange();
  8097. if (RTRange.isValid())
  8098. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  8099. << FixItHint::CreateReplacement(RTRange, "int");
  8100. }
  8101. } else {
  8102. // In C and C++, main magically returns 0 if you fall off the end;
  8103. // set the flag which tells us that.
  8104. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  8105. // All the standards say that main() should return 'int'.
  8106. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  8107. FD->setHasImplicitReturnZero(true);
  8108. else {
  8109. // Otherwise, this is just a flat-out error.
  8110. SourceRange RTRange = FD->getReturnTypeSourceRange();
  8111. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  8112. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  8113. : FixItHint());
  8114. FD->setInvalidDecl(true);
  8115. }
  8116. }
  8117. // Treat protoless main() as nullary.
  8118. if (isa<FunctionNoProtoType>(FT)) return;
  8119. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  8120. unsigned nparams = FTP->getNumParams();
  8121. assert(FD->getNumParams() == nparams);
  8122. bool HasExtraParameters = (nparams > 3);
  8123. if (FTP->isVariadic()) {
  8124. Diag(FD->getLocation(), diag::ext_variadic_main);
  8125. // FIXME: if we had information about the location of the ellipsis, we
  8126. // could add a FixIt hint to remove it as a parameter.
  8127. }
  8128. // Darwin passes an undocumented fourth argument of type char**. If
  8129. // other platforms start sprouting these, the logic below will start
  8130. // getting shifty.
  8131. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  8132. HasExtraParameters = false;
  8133. if (HasExtraParameters) {
  8134. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  8135. FD->setInvalidDecl(true);
  8136. nparams = 3;
  8137. }
  8138. // FIXME: a lot of the following diagnostics would be improved
  8139. // if we had some location information about types.
  8140. QualType CharPP =
  8141. Context.getPointerType(Context.getPointerType(Context.CharTy));
  8142. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  8143. for (unsigned i = 0; i < nparams; ++i) {
  8144. QualType AT = FTP->getParamType(i);
  8145. bool mismatch = true;
  8146. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  8147. mismatch = false;
  8148. else if (Expected[i] == CharPP) {
  8149. // As an extension, the following forms are okay:
  8150. // char const **
  8151. // char const * const *
  8152. // char * const *
  8153. QualifierCollector qs;
  8154. const PointerType* PT;
  8155. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  8156. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  8157. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  8158. Context.CharTy)) {
  8159. qs.removeConst();
  8160. mismatch = !qs.empty();
  8161. }
  8162. }
  8163. if (mismatch) {
  8164. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  8165. // TODO: suggest replacing given type with expected type
  8166. FD->setInvalidDecl(true);
  8167. }
  8168. }
  8169. if (nparams == 1 && !FD->isInvalidDecl()) {
  8170. Diag(FD->getLocation(), diag::warn_main_one_arg);
  8171. }
  8172. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  8173. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  8174. FD->setInvalidDecl();
  8175. }
  8176. }
  8177. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  8178. QualType T = FD->getType();
  8179. assert(T->isFunctionType() && "function decl is not of function type");
  8180. const FunctionType *FT = T->castAs<FunctionType>();
  8181. // Set an implicit return of 'zero' if the function can return some integral,
  8182. // enumeration, pointer or nullptr type.
  8183. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  8184. FT->getReturnType()->isAnyPointerType() ||
  8185. FT->getReturnType()->isNullPtrType())
  8186. // DllMain is exempt because a return value of zero means it failed.
  8187. if (FD->getName() != "DllMain")
  8188. FD->setHasImplicitReturnZero(true);
  8189. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  8190. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  8191. FD->setInvalidDecl();
  8192. }
  8193. }
  8194. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  8195. // FIXME: Need strict checking. In C89, we need to check for
  8196. // any assignment, increment, decrement, function-calls, or
  8197. // commas outside of a sizeof. In C99, it's the same list,
  8198. // except that the aforementioned are allowed in unevaluated
  8199. // expressions. Everything else falls under the
  8200. // "may accept other forms of constant expressions" exception.
  8201. // (We never end up here for C++, so the constant expression
  8202. // rules there don't matter.)
  8203. const Expr *Culprit;
  8204. if (Init->isConstantInitializer(Context, false, &Culprit))
  8205. return false;
  8206. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  8207. << Culprit->getSourceRange();
  8208. return true;
  8209. }
  8210. namespace {
  8211. // Visits an initialization expression to see if OrigDecl is evaluated in
  8212. // its own initialization and throws a warning if it does.
  8213. class SelfReferenceChecker
  8214. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  8215. Sema &S;
  8216. Decl *OrigDecl;
  8217. bool isRecordType;
  8218. bool isPODType;
  8219. bool isReferenceType;
  8220. bool isInitList;
  8221. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  8222. public:
  8223. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  8224. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  8225. S(S), OrigDecl(OrigDecl) {
  8226. isPODType = false;
  8227. isRecordType = false;
  8228. isReferenceType = false;
  8229. isInitList = false;
  8230. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  8231. isPODType = VD->getType().isPODType(S.Context);
  8232. isRecordType = VD->getType()->isRecordType();
  8233. isReferenceType = VD->getType()->isReferenceType();
  8234. }
  8235. }
  8236. // For most expressions, just call the visitor. For initializer lists,
  8237. // track the index of the field being initialized since fields are
  8238. // initialized in order allowing use of previously initialized fields.
  8239. void CheckExpr(Expr *E) {
  8240. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  8241. if (!InitList) {
  8242. Visit(E);
  8243. return;
  8244. }
  8245. // Track and increment the index here.
  8246. isInitList = true;
  8247. InitFieldIndex.push_back(0);
  8248. for (auto Child : InitList->children()) {
  8249. CheckExpr(cast<Expr>(Child));
  8250. ++InitFieldIndex.back();
  8251. }
  8252. InitFieldIndex.pop_back();
  8253. }
  8254. // Returns true if MemberExpr is checked and no futher checking is needed.
  8255. // Returns false if additional checking is required.
  8256. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  8257. llvm::SmallVector<FieldDecl*, 4> Fields;
  8258. Expr *Base = E;
  8259. bool ReferenceField = false;
  8260. // Get the field memebers used.
  8261. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  8262. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  8263. if (!FD)
  8264. return false;
  8265. Fields.push_back(FD);
  8266. if (FD->getType()->isReferenceType())
  8267. ReferenceField = true;
  8268. Base = ME->getBase()->IgnoreParenImpCasts();
  8269. }
  8270. // Keep checking only if the base Decl is the same.
  8271. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  8272. if (!DRE || DRE->getDecl() != OrigDecl)
  8273. return false;
  8274. // A reference field can be bound to an unininitialized field.
  8275. if (CheckReference && !ReferenceField)
  8276. return true;
  8277. // Convert FieldDecls to their index number.
  8278. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  8279. for (const FieldDecl *I : llvm::reverse(Fields))
  8280. UsedFieldIndex.push_back(I->getFieldIndex());
  8281. // See if a warning is needed by checking the first difference in index
  8282. // numbers. If field being used has index less than the field being
  8283. // initialized, then the use is safe.
  8284. for (auto UsedIter = UsedFieldIndex.begin(),
  8285. UsedEnd = UsedFieldIndex.end(),
  8286. OrigIter = InitFieldIndex.begin(),
  8287. OrigEnd = InitFieldIndex.end();
  8288. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  8289. if (*UsedIter < *OrigIter)
  8290. return true;
  8291. if (*UsedIter > *OrigIter)
  8292. break;
  8293. }
  8294. // TODO: Add a different warning which will print the field names.
  8295. HandleDeclRefExpr(DRE);
  8296. return true;
  8297. }
  8298. // For most expressions, the cast is directly above the DeclRefExpr.
  8299. // For conditional operators, the cast can be outside the conditional
  8300. // operator if both expressions are DeclRefExpr's.
  8301. void HandleValue(Expr *E) {
  8302. E = E->IgnoreParens();
  8303. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  8304. HandleDeclRefExpr(DRE);
  8305. return;
  8306. }
  8307. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  8308. Visit(CO->getCond());
  8309. HandleValue(CO->getTrueExpr());
  8310. HandleValue(CO->getFalseExpr());
  8311. return;
  8312. }
  8313. if (BinaryConditionalOperator *BCO =
  8314. dyn_cast<BinaryConditionalOperator>(E)) {
  8315. Visit(BCO->getCond());
  8316. HandleValue(BCO->getFalseExpr());
  8317. return;
  8318. }
  8319. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  8320. HandleValue(OVE->getSourceExpr());
  8321. return;
  8322. }
  8323. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  8324. if (BO->getOpcode() == BO_Comma) {
  8325. Visit(BO->getLHS());
  8326. HandleValue(BO->getRHS());
  8327. return;
  8328. }
  8329. }
  8330. if (isa<MemberExpr>(E)) {
  8331. if (isInitList) {
  8332. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  8333. false /*CheckReference*/))
  8334. return;
  8335. }
  8336. Expr *Base = E->IgnoreParenImpCasts();
  8337. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  8338. // Check for static member variables and don't warn on them.
  8339. if (!isa<FieldDecl>(ME->getMemberDecl()))
  8340. return;
  8341. Base = ME->getBase()->IgnoreParenImpCasts();
  8342. }
  8343. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  8344. HandleDeclRefExpr(DRE);
  8345. return;
  8346. }
  8347. Visit(E);
  8348. }
  8349. // Reference types not handled in HandleValue are handled here since all
  8350. // uses of references are bad, not just r-value uses.
  8351. void VisitDeclRefExpr(DeclRefExpr *E) {
  8352. if (isReferenceType)
  8353. HandleDeclRefExpr(E);
  8354. }
  8355. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  8356. if (E->getCastKind() == CK_LValueToRValue) {
  8357. HandleValue(E->getSubExpr());
  8358. return;
  8359. }
  8360. Inherited::VisitImplicitCastExpr(E);
  8361. }
  8362. void VisitMemberExpr(MemberExpr *E) {
  8363. if (isInitList) {
  8364. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  8365. return;
  8366. }
  8367. // Don't warn on arrays since they can be treated as pointers.
  8368. if (E->getType()->canDecayToPointerType()) return;
  8369. // Warn when a non-static method call is followed by non-static member
  8370. // field accesses, which is followed by a DeclRefExpr.
  8371. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  8372. bool Warn = (MD && !MD->isStatic());
  8373. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  8374. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  8375. if (!isa<FieldDecl>(ME->getMemberDecl()))
  8376. Warn = false;
  8377. Base = ME->getBase()->IgnoreParenImpCasts();
  8378. }
  8379. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  8380. if (Warn)
  8381. HandleDeclRefExpr(DRE);
  8382. return;
  8383. }
  8384. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  8385. // Visit that expression.
  8386. Visit(Base);
  8387. }
  8388. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  8389. Expr *Callee = E->getCallee();
  8390. if (isa<UnresolvedLookupExpr>(Callee))
  8391. return Inherited::VisitCXXOperatorCallExpr(E);
  8392. Visit(Callee);
  8393. for (auto Arg: E->arguments())
  8394. HandleValue(Arg->IgnoreParenImpCasts());
  8395. }
  8396. void VisitUnaryOperator(UnaryOperator *E) {
  8397. // For POD record types, addresses of its own members are well-defined.
  8398. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  8399. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  8400. if (!isPODType)
  8401. HandleValue(E->getSubExpr());
  8402. return;
  8403. }
  8404. if (E->isIncrementDecrementOp()) {
  8405. HandleValue(E->getSubExpr());
  8406. return;
  8407. }
  8408. Inherited::VisitUnaryOperator(E);
  8409. }
  8410. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  8411. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  8412. if (E->getConstructor()->isCopyConstructor()) {
  8413. Expr *ArgExpr = E->getArg(0);
  8414. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  8415. if (ILE->getNumInits() == 1)
  8416. ArgExpr = ILE->getInit(0);
  8417. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  8418. if (ICE->getCastKind() == CK_NoOp)
  8419. ArgExpr = ICE->getSubExpr();
  8420. HandleValue(ArgExpr);
  8421. return;
  8422. }
  8423. Inherited::VisitCXXConstructExpr(E);
  8424. }
  8425. void VisitCallExpr(CallExpr *E) {
  8426. // Treat std::move as a use.
  8427. if (E->getNumArgs() == 1) {
  8428. if (FunctionDecl *FD = E->getDirectCallee()) {
  8429. if (FD->isInStdNamespace() && FD->getIdentifier() &&
  8430. FD->getIdentifier()->isStr("move")) {
  8431. HandleValue(E->getArg(0));
  8432. return;
  8433. }
  8434. }
  8435. }
  8436. Inherited::VisitCallExpr(E);
  8437. }
  8438. void VisitBinaryOperator(BinaryOperator *E) {
  8439. if (E->isCompoundAssignmentOp()) {
  8440. HandleValue(E->getLHS());
  8441. Visit(E->getRHS());
  8442. return;
  8443. }
  8444. Inherited::VisitBinaryOperator(E);
  8445. }
  8446. // A custom visitor for BinaryConditionalOperator is needed because the
  8447. // regular visitor would check the condition and true expression separately
  8448. // but both point to the same place giving duplicate diagnostics.
  8449. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  8450. Visit(E->getCond());
  8451. Visit(E->getFalseExpr());
  8452. }
  8453. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  8454. Decl* ReferenceDecl = DRE->getDecl();
  8455. if (OrigDecl != ReferenceDecl) return;
  8456. unsigned diag;
  8457. if (isReferenceType) {
  8458. diag = diag::warn_uninit_self_reference_in_reference_init;
  8459. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  8460. diag = diag::warn_static_self_reference_in_init;
  8461. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  8462. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  8463. DRE->getDecl()->getType()->isRecordType()) {
  8464. diag = diag::warn_uninit_self_reference_in_init;
  8465. } else {
  8466. // Local variables will be handled by the CFG analysis.
  8467. return;
  8468. }
  8469. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  8470. S.PDiag(diag)
  8471. << DRE->getNameInfo().getName()
  8472. << OrigDecl->getLocation()
  8473. << DRE->getSourceRange());
  8474. }
  8475. };
  8476. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  8477. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  8478. bool DirectInit) {
  8479. // Parameters arguments are occassionially constructed with itself,
  8480. // for instance, in recursive functions. Skip them.
  8481. if (isa<ParmVarDecl>(OrigDecl))
  8482. return;
  8483. E = E->IgnoreParens();
  8484. // Skip checking T a = a where T is not a record or reference type.
  8485. // Doing so is a way to silence uninitialized warnings.
  8486. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  8487. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  8488. if (ICE->getCastKind() == CK_LValueToRValue)
  8489. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  8490. if (DRE->getDecl() == OrigDecl)
  8491. return;
  8492. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  8493. }
  8494. } // end anonymous namespace
  8495. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  8496. DeclarationName Name, QualType Type,
  8497. TypeSourceInfo *TSI,
  8498. SourceRange Range, bool DirectInit,
  8499. Expr *Init) {
  8500. bool IsInitCapture = !VDecl;
  8501. assert((!VDecl || !VDecl->isInitCapture()) &&
  8502. "init captures are expected to be deduced prior to initialization");
  8503. // FIXME: Deduction for a decomposition declaration does weird things if the
  8504. // initializer is an array.
  8505. ArrayRef<Expr *> DeduceInits = Init;
  8506. if (DirectInit) {
  8507. if (auto *PL = dyn_cast<ParenListExpr>(Init))
  8508. DeduceInits = PL->exprs();
  8509. else if (auto *IL = dyn_cast<InitListExpr>(Init))
  8510. DeduceInits = IL->inits();
  8511. }
  8512. // Deduction only works if we have exactly one source expression.
  8513. if (DeduceInits.empty()) {
  8514. // It isn't possible to write this directly, but it is possible to
  8515. // end up in this situation with "auto x(some_pack...);"
  8516. Diag(Init->getLocStart(), IsInitCapture
  8517. ? diag::err_init_capture_no_expression
  8518. : diag::err_auto_var_init_no_expression)
  8519. << Name << Type << Range;
  8520. return QualType();
  8521. }
  8522. if (DeduceInits.size() > 1) {
  8523. Diag(DeduceInits[1]->getLocStart(),
  8524. IsInitCapture ? diag::err_init_capture_multiple_expressions
  8525. : diag::err_auto_var_init_multiple_expressions)
  8526. << Name << Type << Range;
  8527. return QualType();
  8528. }
  8529. Expr *DeduceInit = DeduceInits[0];
  8530. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  8531. Diag(Init->getLocStart(), IsInitCapture
  8532. ? diag::err_init_capture_paren_braces
  8533. : diag::err_auto_var_init_paren_braces)
  8534. << isa<InitListExpr>(Init) << Name << Type << Range;
  8535. return QualType();
  8536. }
  8537. // Expressions default to 'id' when we're in a debugger.
  8538. bool DefaultedAnyToId = false;
  8539. if (getLangOpts().DebuggerCastResultToId &&
  8540. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  8541. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  8542. if (Result.isInvalid()) {
  8543. return QualType();
  8544. }
  8545. Init = Result.get();
  8546. DefaultedAnyToId = true;
  8547. }
  8548. QualType DeducedType;
  8549. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  8550. if (!IsInitCapture)
  8551. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  8552. else if (isa<InitListExpr>(Init))
  8553. Diag(Range.getBegin(),
  8554. diag::err_init_capture_deduction_failure_from_init_list)
  8555. << Name
  8556. << (DeduceInit->getType().isNull() ? TSI->getType()
  8557. : DeduceInit->getType())
  8558. << DeduceInit->getSourceRange();
  8559. else
  8560. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  8561. << Name << TSI->getType()
  8562. << (DeduceInit->getType().isNull() ? TSI->getType()
  8563. : DeduceInit->getType())
  8564. << DeduceInit->getSourceRange();
  8565. }
  8566. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  8567. // 'id' instead of a specific object type prevents most of our usual
  8568. // checks.
  8569. // We only want to warn outside of template instantiations, though:
  8570. // inside a template, the 'id' could have come from a parameter.
  8571. if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
  8572. !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  8573. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  8574. Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
  8575. }
  8576. return DeducedType;
  8577. }
  8578. /// AddInitializerToDecl - Adds the initializer Init to the
  8579. /// declaration dcl. If DirectInit is true, this is C++ direct
  8580. /// initialization rather than copy initialization.
  8581. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
  8582. bool DirectInit, bool TypeMayContainAuto) {
  8583. // If there is no declaration, there was an error parsing it. Just ignore
  8584. // the initializer.
  8585. if (!RealDecl || RealDecl->isInvalidDecl()) {
  8586. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  8587. return;
  8588. }
  8589. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  8590. // Pure-specifiers are handled in ActOnPureSpecifier.
  8591. Diag(Method->getLocation(), diag::err_member_function_initialization)
  8592. << Method->getDeclName() << Init->getSourceRange();
  8593. Method->setInvalidDecl();
  8594. return;
  8595. }
  8596. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  8597. if (!VDecl) {
  8598. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  8599. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  8600. RealDecl->setInvalidDecl();
  8601. return;
  8602. }
  8603. // C++1z [dcl.dcl]p1 grammar implies that a parenthesized initializer is not
  8604. // permitted.
  8605. if (isa<DecompositionDecl>(VDecl) && DirectInit && isa<ParenListExpr>(Init))
  8606. Diag(VDecl->getLocation(), diag::err_decomp_decl_paren_init) << VDecl;
  8607. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  8608. if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
  8609. // Attempt typo correction early so that the type of the init expression can
  8610. // be deduced based on the chosen correction if the original init contains a
  8611. // TypoExpr.
  8612. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  8613. if (!Res.isUsable()) {
  8614. RealDecl->setInvalidDecl();
  8615. return;
  8616. }
  8617. Init = Res.get();
  8618. QualType DeducedType = deduceVarTypeFromInitializer(
  8619. VDecl, VDecl->getDeclName(), VDecl->getType(),
  8620. VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
  8621. if (DeducedType.isNull()) {
  8622. RealDecl->setInvalidDecl();
  8623. return;
  8624. }
  8625. VDecl->setType(DeducedType);
  8626. assert(VDecl->isLinkageValid());
  8627. // In ARC, infer lifetime.
  8628. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  8629. VDecl->setInvalidDecl();
  8630. // If this is a redeclaration, check that the type we just deduced matches
  8631. // the previously declared type.
  8632. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  8633. // We never need to merge the type, because we cannot form an incomplete
  8634. // array of auto, nor deduce such a type.
  8635. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  8636. }
  8637. // Check the deduced type is valid for a variable declaration.
  8638. CheckVariableDeclarationType(VDecl);
  8639. if (VDecl->isInvalidDecl())
  8640. return;
  8641. }
  8642. // dllimport cannot be used on variable definitions.
  8643. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  8644. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  8645. VDecl->setInvalidDecl();
  8646. return;
  8647. }
  8648. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  8649. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  8650. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  8651. VDecl->setInvalidDecl();
  8652. return;
  8653. }
  8654. if (!VDecl->getType()->isDependentType()) {
  8655. // A definition must end up with a complete type, which means it must be
  8656. // complete with the restriction that an array type might be completed by
  8657. // the initializer; note that later code assumes this restriction.
  8658. QualType BaseDeclType = VDecl->getType();
  8659. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  8660. BaseDeclType = Array->getElementType();
  8661. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  8662. diag::err_typecheck_decl_incomplete_type)) {
  8663. RealDecl->setInvalidDecl();
  8664. return;
  8665. }
  8666. // The variable can not have an abstract class type.
  8667. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  8668. diag::err_abstract_type_in_decl,
  8669. AbstractVariableType))
  8670. VDecl->setInvalidDecl();
  8671. }
  8672. // If adding the initializer will turn this declaration into a definition,
  8673. // and we already have a definition for this variable, diagnose or otherwise
  8674. // handle the situation.
  8675. VarDecl *Def;
  8676. if ((Def = VDecl->getDefinition()) && Def != VDecl &&
  8677. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  8678. !VDecl->isThisDeclarationADemotedDefinition() &&
  8679. checkVarDeclRedefinition(Def, VDecl))
  8680. return;
  8681. if (getLangOpts().CPlusPlus) {
  8682. // C++ [class.static.data]p4
  8683. // If a static data member is of const integral or const
  8684. // enumeration type, its declaration in the class definition can
  8685. // specify a constant-initializer which shall be an integral
  8686. // constant expression (5.19). In that case, the member can appear
  8687. // in integral constant expressions. The member shall still be
  8688. // defined in a namespace scope if it is used in the program and the
  8689. // namespace scope definition shall not contain an initializer.
  8690. //
  8691. // We already performed a redefinition check above, but for static
  8692. // data members we also need to check whether there was an in-class
  8693. // declaration with an initializer.
  8694. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  8695. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  8696. << VDecl->getDeclName();
  8697. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  8698. diag::note_previous_initializer)
  8699. << 0;
  8700. return;
  8701. }
  8702. if (VDecl->hasLocalStorage())
  8703. getCurFunction()->setHasBranchProtectedScope();
  8704. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  8705. VDecl->setInvalidDecl();
  8706. return;
  8707. }
  8708. }
  8709. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  8710. // a kernel function cannot be initialized."
  8711. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  8712. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  8713. VDecl->setInvalidDecl();
  8714. return;
  8715. }
  8716. // Get the decls type and save a reference for later, since
  8717. // CheckInitializerTypes may change it.
  8718. QualType DclT = VDecl->getType(), SavT = DclT;
  8719. // Expressions default to 'id' when we're in a debugger
  8720. // and we are assigning it to a variable of Objective-C pointer type.
  8721. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  8722. Init->getType() == Context.UnknownAnyTy) {
  8723. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  8724. if (Result.isInvalid()) {
  8725. VDecl->setInvalidDecl();
  8726. return;
  8727. }
  8728. Init = Result.get();
  8729. }
  8730. // Perform the initialization.
  8731. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  8732. if (!VDecl->isInvalidDecl()) {
  8733. // Handle errors like: int a({0})
  8734. if (CXXDirectInit && CXXDirectInit->getNumExprs() == 1 &&
  8735. !canInitializeWithParenthesizedList(VDecl->getType()))
  8736. if (auto IList = dyn_cast<InitListExpr>(CXXDirectInit->getExpr(0))) {
  8737. Diag(VDecl->getLocation(), diag::err_list_init_in_parens)
  8738. << VDecl->getType() << CXXDirectInit->getSourceRange()
  8739. << FixItHint::CreateRemoval(CXXDirectInit->getLocStart())
  8740. << FixItHint::CreateRemoval(CXXDirectInit->getLocEnd());
  8741. Init = IList;
  8742. CXXDirectInit = nullptr;
  8743. }
  8744. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  8745. InitializationKind Kind =
  8746. DirectInit
  8747. ? CXXDirectInit
  8748. ? InitializationKind::CreateDirect(VDecl->getLocation(),
  8749. Init->getLocStart(),
  8750. Init->getLocEnd())
  8751. : InitializationKind::CreateDirectList(VDecl->getLocation())
  8752. : InitializationKind::CreateCopy(VDecl->getLocation(),
  8753. Init->getLocStart());
  8754. MultiExprArg Args = Init;
  8755. if (CXXDirectInit)
  8756. Args = MultiExprArg(CXXDirectInit->getExprs(),
  8757. CXXDirectInit->getNumExprs());
  8758. // Try to correct any TypoExprs in the initialization arguments.
  8759. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  8760. ExprResult Res = CorrectDelayedTyposInExpr(
  8761. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  8762. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  8763. return Init.Failed() ? ExprError() : E;
  8764. });
  8765. if (Res.isInvalid()) {
  8766. VDecl->setInvalidDecl();
  8767. } else if (Res.get() != Args[Idx]) {
  8768. Args[Idx] = Res.get();
  8769. }
  8770. }
  8771. if (VDecl->isInvalidDecl())
  8772. return;
  8773. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  8774. /*TopLevelOfInitList=*/false,
  8775. /*TreatUnavailableAsInvalid=*/false);
  8776. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  8777. if (Result.isInvalid()) {
  8778. VDecl->setInvalidDecl();
  8779. return;
  8780. }
  8781. Init = Result.getAs<Expr>();
  8782. }
  8783. // Check for self-references within variable initializers.
  8784. // Variables declared within a function/method body (except for references)
  8785. // are handled by a dataflow analysis.
  8786. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  8787. VDecl->getType()->isReferenceType()) {
  8788. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  8789. }
  8790. // If the type changed, it means we had an incomplete type that was
  8791. // completed by the initializer. For example:
  8792. // int ary[] = { 1, 3, 5 };
  8793. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  8794. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  8795. VDecl->setType(DclT);
  8796. if (!VDecl->isInvalidDecl()) {
  8797. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  8798. if (VDecl->hasAttr<BlocksAttr>())
  8799. checkRetainCycles(VDecl, Init);
  8800. // It is safe to assign a weak reference into a strong variable.
  8801. // Although this code can still have problems:
  8802. // id x = self.weakProp;
  8803. // id y = self.weakProp;
  8804. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  8805. // paths through the function. This should be revisited if
  8806. // -Wrepeated-use-of-weak is made flow-sensitive.
  8807. if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
  8808. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  8809. Init->getLocStart()))
  8810. getCurFunction()->markSafeWeakUse(Init);
  8811. }
  8812. // The initialization is usually a full-expression.
  8813. //
  8814. // FIXME: If this is a braced initialization of an aggregate, it is not
  8815. // an expression, and each individual field initializer is a separate
  8816. // full-expression. For instance, in:
  8817. //
  8818. // struct Temp { ~Temp(); };
  8819. // struct S { S(Temp); };
  8820. // struct T { S a, b; } t = { Temp(), Temp() }
  8821. //
  8822. // we should destroy the first Temp before constructing the second.
  8823. ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
  8824. false,
  8825. VDecl->isConstexpr());
  8826. if (Result.isInvalid()) {
  8827. VDecl->setInvalidDecl();
  8828. return;
  8829. }
  8830. Init = Result.get();
  8831. // Attach the initializer to the decl.
  8832. VDecl->setInit(Init);
  8833. if (VDecl->isLocalVarDecl()) {
  8834. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  8835. // static storage duration shall be constant expressions or string literals.
  8836. // C++ does not have this restriction.
  8837. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
  8838. const Expr *Culprit;
  8839. if (VDecl->getStorageClass() == SC_Static)
  8840. CheckForConstantInitializer(Init, DclT);
  8841. // C89 is stricter than C99 for non-static aggregate types.
  8842. // C89 6.5.7p3: All the expressions [...] in an initializer list
  8843. // for an object that has aggregate or union type shall be
  8844. // constant expressions.
  8845. else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  8846. isa<InitListExpr>(Init) &&
  8847. !Init->isConstantInitializer(Context, false, &Culprit))
  8848. Diag(Culprit->getExprLoc(),
  8849. diag::ext_aggregate_init_not_constant)
  8850. << Culprit->getSourceRange();
  8851. }
  8852. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  8853. VDecl->getLexicalDeclContext()->isRecord()) {
  8854. // This is an in-class initialization for a static data member, e.g.,
  8855. //
  8856. // struct S {
  8857. // static const int value = 17;
  8858. // };
  8859. // C++ [class.mem]p4:
  8860. // A member-declarator can contain a constant-initializer only
  8861. // if it declares a static member (9.4) of const integral or
  8862. // const enumeration type, see 9.4.2.
  8863. //
  8864. // C++11 [class.static.data]p3:
  8865. // If a non-volatile non-inline const static data member is of integral
  8866. // or enumeration type, its declaration in the class definition can
  8867. // specify a brace-or-equal-initializer in which every initalizer-clause
  8868. // that is an assignment-expression is a constant expression. A static
  8869. // data member of literal type can be declared in the class definition
  8870. // with the constexpr specifier; if so, its declaration shall specify a
  8871. // brace-or-equal-initializer in which every initializer-clause that is
  8872. // an assignment-expression is a constant expression.
  8873. // Do nothing on dependent types.
  8874. if (DclT->isDependentType()) {
  8875. // Allow any 'static constexpr' members, whether or not they are of literal
  8876. // type. We separately check that every constexpr variable is of literal
  8877. // type.
  8878. } else if (VDecl->isConstexpr()) {
  8879. // Require constness.
  8880. } else if (!DclT.isConstQualified()) {
  8881. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  8882. << Init->getSourceRange();
  8883. VDecl->setInvalidDecl();
  8884. // We allow integer constant expressions in all cases.
  8885. } else if (DclT->isIntegralOrEnumerationType()) {
  8886. // Check whether the expression is a constant expression.
  8887. SourceLocation Loc;
  8888. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  8889. // In C++11, a non-constexpr const static data member with an
  8890. // in-class initializer cannot be volatile.
  8891. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  8892. else if (Init->isValueDependent())
  8893. ; // Nothing to check.
  8894. else if (Init->isIntegerConstantExpr(Context, &Loc))
  8895. ; // Ok, it's an ICE!
  8896. else if (Init->isEvaluatable(Context)) {
  8897. // If we can constant fold the initializer through heroics, accept it,
  8898. // but report this as a use of an extension for -pedantic.
  8899. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  8900. << Init->getSourceRange();
  8901. } else {
  8902. // Otherwise, this is some crazy unknown case. Report the issue at the
  8903. // location provided by the isIntegerConstantExpr failed check.
  8904. Diag(Loc, diag::err_in_class_initializer_non_constant)
  8905. << Init->getSourceRange();
  8906. VDecl->setInvalidDecl();
  8907. }
  8908. // We allow foldable floating-point constants as an extension.
  8909. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  8910. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  8911. // it anyway and provide a fixit to add the 'constexpr'.
  8912. if (getLangOpts().CPlusPlus11) {
  8913. Diag(VDecl->getLocation(),
  8914. diag::ext_in_class_initializer_float_type_cxx11)
  8915. << DclT << Init->getSourceRange();
  8916. Diag(VDecl->getLocStart(),
  8917. diag::note_in_class_initializer_float_type_cxx11)
  8918. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  8919. } else {
  8920. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  8921. << DclT << Init->getSourceRange();
  8922. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  8923. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  8924. << Init->getSourceRange();
  8925. VDecl->setInvalidDecl();
  8926. }
  8927. }
  8928. // Suggest adding 'constexpr' in C++11 for literal types.
  8929. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  8930. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  8931. << DclT << Init->getSourceRange()
  8932. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  8933. VDecl->setConstexpr(true);
  8934. } else {
  8935. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  8936. << DclT << Init->getSourceRange();
  8937. VDecl->setInvalidDecl();
  8938. }
  8939. } else if (VDecl->isFileVarDecl()) {
  8940. // In C, extern is typically used to avoid tentative definitions when
  8941. // declaring variables in headers, but adding an intializer makes it a
  8942. // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
  8943. // In C++, extern is often used to give implictly static const variables
  8944. // external linkage, so don't warn in that case. If selectany is present,
  8945. // this might be header code intended for C and C++ inclusion, so apply the
  8946. // C++ rules.
  8947. if (VDecl->getStorageClass() == SC_Extern &&
  8948. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  8949. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  8950. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  8951. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  8952. Diag(VDecl->getLocation(), diag::warn_extern_init);
  8953. // C99 6.7.8p4. All file scoped initializers need to be constant.
  8954. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  8955. CheckForConstantInitializer(Init, DclT);
  8956. }
  8957. // We will represent direct-initialization similarly to copy-initialization:
  8958. // int x(1); -as-> int x = 1;
  8959. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  8960. //
  8961. // Clients that want to distinguish between the two forms, can check for
  8962. // direct initializer using VarDecl::getInitStyle().
  8963. // A major benefit is that clients that don't particularly care about which
  8964. // exactly form was it (like the CodeGen) can handle both cases without
  8965. // special case code.
  8966. // C++ 8.5p11:
  8967. // The form of initialization (using parentheses or '=') is generally
  8968. // insignificant, but does matter when the entity being initialized has a
  8969. // class type.
  8970. if (CXXDirectInit) {
  8971. assert(DirectInit && "Call-style initializer must be direct init.");
  8972. VDecl->setInitStyle(VarDecl::CallInit);
  8973. } else if (DirectInit) {
  8974. // This must be list-initialization. No other way is direct-initialization.
  8975. VDecl->setInitStyle(VarDecl::ListInit);
  8976. }
  8977. CheckCompleteVariableDeclaration(VDecl);
  8978. }
  8979. /// ActOnInitializerError - Given that there was an error parsing an
  8980. /// initializer for the given declaration, try to return to some form
  8981. /// of sanity.
  8982. void Sema::ActOnInitializerError(Decl *D) {
  8983. // Our main concern here is re-establishing invariants like "a
  8984. // variable's type is either dependent or complete".
  8985. if (!D || D->isInvalidDecl()) return;
  8986. VarDecl *VD = dyn_cast<VarDecl>(D);
  8987. if (!VD) return;
  8988. // Bindings are not usable if we can't make sense of the initializer.
  8989. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  8990. for (auto *BD : DD->bindings())
  8991. BD->setInvalidDecl();
  8992. // Auto types are meaningless if we can't make sense of the initializer.
  8993. if (ParsingInitForAutoVars.count(D)) {
  8994. D->setInvalidDecl();
  8995. return;
  8996. }
  8997. QualType Ty = VD->getType();
  8998. if (Ty->isDependentType()) return;
  8999. // Require a complete type.
  9000. if (RequireCompleteType(VD->getLocation(),
  9001. Context.getBaseElementType(Ty),
  9002. diag::err_typecheck_decl_incomplete_type)) {
  9003. VD->setInvalidDecl();
  9004. return;
  9005. }
  9006. // Require a non-abstract type.
  9007. if (RequireNonAbstractType(VD->getLocation(), Ty,
  9008. diag::err_abstract_type_in_decl,
  9009. AbstractVariableType)) {
  9010. VD->setInvalidDecl();
  9011. return;
  9012. }
  9013. // Don't bother complaining about constructors or destructors,
  9014. // though.
  9015. }
  9016. /// Checks if an object of the given type can be initialized with parenthesized
  9017. /// init-list.
  9018. ///
  9019. /// \param TargetType Type of object being initialized.
  9020. ///
  9021. /// The function is used to detect wrong initializations, such as 'int({0})'.
  9022. ///
  9023. bool Sema::canInitializeWithParenthesizedList(QualType TargetType) {
  9024. return TargetType->isDependentType() || TargetType->isRecordType() ||
  9025. TargetType->getContainedAutoType();
  9026. }
  9027. void Sema::ActOnUninitializedDecl(Decl *RealDecl,
  9028. bool TypeMayContainAuto) {
  9029. // If there is no declaration, there was an error parsing it. Just ignore it.
  9030. if (!RealDecl)
  9031. return;
  9032. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  9033. QualType Type = Var->getType();
  9034. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  9035. if (isa<DecompositionDecl>(RealDecl)) {
  9036. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  9037. Var->setInvalidDecl();
  9038. return;
  9039. }
  9040. // C++11 [dcl.spec.auto]p3
  9041. if (TypeMayContainAuto && Type->getContainedAutoType()) {
  9042. Diag(Var->getLocation(), diag::err_auto_var_requires_init)
  9043. << Var->getDeclName() << Type;
  9044. Var->setInvalidDecl();
  9045. return;
  9046. }
  9047. // C++11 [class.static.data]p3: A static data member can be declared with
  9048. // the constexpr specifier; if so, its declaration shall specify
  9049. // a brace-or-equal-initializer.
  9050. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  9051. // the definition of a variable [...] or the declaration of a static data
  9052. // member.
  9053. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  9054. !Var->isThisDeclarationADemotedDefinition()) {
  9055. if (Var->isStaticDataMember()) {
  9056. // C++1z removes the relevant rule; the in-class declaration is always
  9057. // a definition there.
  9058. if (!getLangOpts().CPlusPlus1z) {
  9059. Diag(Var->getLocation(),
  9060. diag::err_constexpr_static_mem_var_requires_init)
  9061. << Var->getDeclName();
  9062. Var->setInvalidDecl();
  9063. return;
  9064. }
  9065. } else {
  9066. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  9067. Var->setInvalidDecl();
  9068. return;
  9069. }
  9070. }
  9071. // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
  9072. // definition having the concept specifier is called a variable concept. A
  9073. // concept definition refers to [...] a variable concept and its initializer.
  9074. if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
  9075. if (VTD->isConcept()) {
  9076. Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
  9077. Var->setInvalidDecl();
  9078. return;
  9079. }
  9080. }
  9081. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  9082. // be initialized.
  9083. if (!Var->isInvalidDecl() &&
  9084. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  9085. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  9086. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  9087. Var->setInvalidDecl();
  9088. return;
  9089. }
  9090. switch (Var->isThisDeclarationADefinition()) {
  9091. case VarDecl::Definition:
  9092. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  9093. break;
  9094. // We have an out-of-line definition of a static data member
  9095. // that has an in-class initializer, so we type-check this like
  9096. // a declaration.
  9097. //
  9098. // Fall through
  9099. case VarDecl::DeclarationOnly:
  9100. // It's only a declaration.
  9101. // Block scope. C99 6.7p7: If an identifier for an object is
  9102. // declared with no linkage (C99 6.2.2p6), the type for the
  9103. // object shall be complete.
  9104. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  9105. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  9106. RequireCompleteType(Var->getLocation(), Type,
  9107. diag::err_typecheck_decl_incomplete_type))
  9108. Var->setInvalidDecl();
  9109. // Make sure that the type is not abstract.
  9110. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  9111. RequireNonAbstractType(Var->getLocation(), Type,
  9112. diag::err_abstract_type_in_decl,
  9113. AbstractVariableType))
  9114. Var->setInvalidDecl();
  9115. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  9116. Var->getStorageClass() == SC_PrivateExtern) {
  9117. Diag(Var->getLocation(), diag::warn_private_extern);
  9118. Diag(Var->getLocation(), diag::note_private_extern);
  9119. }
  9120. return;
  9121. case VarDecl::TentativeDefinition:
  9122. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  9123. // object that has file scope without an initializer, and without a
  9124. // storage-class specifier or with the storage-class specifier "static",
  9125. // constitutes a tentative definition. Note: A tentative definition with
  9126. // external linkage is valid (C99 6.2.2p5).
  9127. if (!Var->isInvalidDecl()) {
  9128. if (const IncompleteArrayType *ArrayT
  9129. = Context.getAsIncompleteArrayType(Type)) {
  9130. if (RequireCompleteType(Var->getLocation(),
  9131. ArrayT->getElementType(),
  9132. diag::err_illegal_decl_array_incomplete_type))
  9133. Var->setInvalidDecl();
  9134. } else if (Var->getStorageClass() == SC_Static) {
  9135. // C99 6.9.2p3: If the declaration of an identifier for an object is
  9136. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  9137. // declared type shall not be an incomplete type.
  9138. // NOTE: code such as the following
  9139. // static struct s;
  9140. // struct s { int a; };
  9141. // is accepted by gcc. Hence here we issue a warning instead of
  9142. // an error and we do not invalidate the static declaration.
  9143. // NOTE: to avoid multiple warnings, only check the first declaration.
  9144. if (Var->isFirstDecl())
  9145. RequireCompleteType(Var->getLocation(), Type,
  9146. diag::ext_typecheck_decl_incomplete_type);
  9147. }
  9148. }
  9149. // Record the tentative definition; we're done.
  9150. if (!Var->isInvalidDecl())
  9151. TentativeDefinitions.push_back(Var);
  9152. return;
  9153. }
  9154. // Provide a specific diagnostic for uninitialized variable
  9155. // definitions with incomplete array type.
  9156. if (Type->isIncompleteArrayType()) {
  9157. Diag(Var->getLocation(),
  9158. diag::err_typecheck_incomplete_array_needs_initializer);
  9159. Var->setInvalidDecl();
  9160. return;
  9161. }
  9162. // Provide a specific diagnostic for uninitialized variable
  9163. // definitions with reference type.
  9164. if (Type->isReferenceType()) {
  9165. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  9166. << Var->getDeclName()
  9167. << SourceRange(Var->getLocation(), Var->getLocation());
  9168. Var->setInvalidDecl();
  9169. return;
  9170. }
  9171. // Do not attempt to type-check the default initializer for a
  9172. // variable with dependent type.
  9173. if (Type->isDependentType())
  9174. return;
  9175. if (Var->isInvalidDecl())
  9176. return;
  9177. if (!Var->hasAttr<AliasAttr>()) {
  9178. if (RequireCompleteType(Var->getLocation(),
  9179. Context.getBaseElementType(Type),
  9180. diag::err_typecheck_decl_incomplete_type)) {
  9181. Var->setInvalidDecl();
  9182. return;
  9183. }
  9184. } else {
  9185. return;
  9186. }
  9187. // The variable can not have an abstract class type.
  9188. if (RequireNonAbstractType(Var->getLocation(), Type,
  9189. diag::err_abstract_type_in_decl,
  9190. AbstractVariableType)) {
  9191. Var->setInvalidDecl();
  9192. return;
  9193. }
  9194. // Check for jumps past the implicit initializer. C++0x
  9195. // clarifies that this applies to a "variable with automatic
  9196. // storage duration", not a "local variable".
  9197. // C++11 [stmt.dcl]p3
  9198. // A program that jumps from a point where a variable with automatic
  9199. // storage duration is not in scope to a point where it is in scope is
  9200. // ill-formed unless the variable has scalar type, class type with a
  9201. // trivial default constructor and a trivial destructor, a cv-qualified
  9202. // version of one of these types, or an array of one of the preceding
  9203. // types and is declared without an initializer.
  9204. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  9205. if (const RecordType *Record
  9206. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  9207. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  9208. // Mark the function for further checking even if the looser rules of
  9209. // C++11 do not require such checks, so that we can diagnose
  9210. // incompatibilities with C++98.
  9211. if (!CXXRecord->isPOD())
  9212. getCurFunction()->setHasBranchProtectedScope();
  9213. }
  9214. }
  9215. // C++03 [dcl.init]p9:
  9216. // If no initializer is specified for an object, and the
  9217. // object is of (possibly cv-qualified) non-POD class type (or
  9218. // array thereof), the object shall be default-initialized; if
  9219. // the object is of const-qualified type, the underlying class
  9220. // type shall have a user-declared default
  9221. // constructor. Otherwise, if no initializer is specified for
  9222. // a non- static object, the object and its subobjects, if
  9223. // any, have an indeterminate initial value); if the object
  9224. // or any of its subobjects are of const-qualified type, the
  9225. // program is ill-formed.
  9226. // C++0x [dcl.init]p11:
  9227. // If no initializer is specified for an object, the object is
  9228. // default-initialized; [...].
  9229. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  9230. InitializationKind Kind
  9231. = InitializationKind::CreateDefault(Var->getLocation());
  9232. InitializationSequence InitSeq(*this, Entity, Kind, None);
  9233. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  9234. if (Init.isInvalid())
  9235. Var->setInvalidDecl();
  9236. else if (Init.get()) {
  9237. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  9238. // This is important for template substitution.
  9239. Var->setInitStyle(VarDecl::CallInit);
  9240. }
  9241. CheckCompleteVariableDeclaration(Var);
  9242. }
  9243. }
  9244. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  9245. // If there is no declaration, there was an error parsing it. Ignore it.
  9246. if (!D)
  9247. return;
  9248. VarDecl *VD = dyn_cast<VarDecl>(D);
  9249. if (!VD) {
  9250. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  9251. D->setInvalidDecl();
  9252. return;
  9253. }
  9254. VD->setCXXForRangeDecl(true);
  9255. // for-range-declaration cannot be given a storage class specifier.
  9256. int Error = -1;
  9257. switch (VD->getStorageClass()) {
  9258. case SC_None:
  9259. break;
  9260. case SC_Extern:
  9261. Error = 0;
  9262. break;
  9263. case SC_Static:
  9264. Error = 1;
  9265. break;
  9266. case SC_PrivateExtern:
  9267. Error = 2;
  9268. break;
  9269. case SC_Auto:
  9270. Error = 3;
  9271. break;
  9272. case SC_Register:
  9273. Error = 4;
  9274. break;
  9275. }
  9276. if (Error != -1) {
  9277. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  9278. << VD->getDeclName() << Error;
  9279. D->setInvalidDecl();
  9280. }
  9281. }
  9282. StmtResult
  9283. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  9284. IdentifierInfo *Ident,
  9285. ParsedAttributes &Attrs,
  9286. SourceLocation AttrEnd) {
  9287. // C++1y [stmt.iter]p1:
  9288. // A range-based for statement of the form
  9289. // for ( for-range-identifier : for-range-initializer ) statement
  9290. // is equivalent to
  9291. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  9292. DeclSpec DS(Attrs.getPool().getFactory());
  9293. const char *PrevSpec;
  9294. unsigned DiagID;
  9295. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  9296. getPrintingPolicy());
  9297. Declarator D(DS, Declarator::ForContext);
  9298. D.SetIdentifier(Ident, IdentLoc);
  9299. D.takeAttributes(Attrs, AttrEnd);
  9300. ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
  9301. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
  9302. EmptyAttrs, IdentLoc);
  9303. Decl *Var = ActOnDeclarator(S, D);
  9304. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  9305. FinalizeDeclaration(Var);
  9306. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  9307. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  9308. }
  9309. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  9310. if (var->isInvalidDecl()) return;
  9311. if (getLangOpts().OpenCL) {
  9312. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  9313. // initialiser
  9314. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  9315. !var->hasInit()) {
  9316. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  9317. << 1 /*Init*/;
  9318. var->setInvalidDecl();
  9319. return;
  9320. }
  9321. }
  9322. // In Objective-C, don't allow jumps past the implicit initialization of a
  9323. // local retaining variable.
  9324. if (getLangOpts().ObjC1 &&
  9325. var->hasLocalStorage()) {
  9326. switch (var->getType().getObjCLifetime()) {
  9327. case Qualifiers::OCL_None:
  9328. case Qualifiers::OCL_ExplicitNone:
  9329. case Qualifiers::OCL_Autoreleasing:
  9330. break;
  9331. case Qualifiers::OCL_Weak:
  9332. case Qualifiers::OCL_Strong:
  9333. getCurFunction()->setHasBranchProtectedScope();
  9334. break;
  9335. }
  9336. }
  9337. // Warn about externally-visible variables being defined without a
  9338. // prior declaration. We only want to do this for global
  9339. // declarations, but we also specifically need to avoid doing it for
  9340. // class members because the linkage of an anonymous class can
  9341. // change if it's later given a typedef name.
  9342. if (var->isThisDeclarationADefinition() &&
  9343. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  9344. var->isExternallyVisible() && var->hasLinkage() &&
  9345. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  9346. var->getLocation())) {
  9347. // Find a previous declaration that's not a definition.
  9348. VarDecl *prev = var->getPreviousDecl();
  9349. while (prev && prev->isThisDeclarationADefinition())
  9350. prev = prev->getPreviousDecl();
  9351. if (!prev)
  9352. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  9353. }
  9354. // Cache the result of checking for constant initialization.
  9355. Optional<bool> CacheHasConstInit;
  9356. const Expr *CacheCulprit;
  9357. auto checkConstInit = [&]() mutable {
  9358. if (!CacheHasConstInit)
  9359. CacheHasConstInit = var->getInit()->isConstantInitializer(
  9360. Context, var->getType()->isReferenceType(), &CacheCulprit);
  9361. return *CacheHasConstInit;
  9362. };
  9363. if (var->getTLSKind() == VarDecl::TLS_Static) {
  9364. if (var->getType().isDestructedType()) {
  9365. // GNU C++98 edits for __thread, [basic.start.term]p3:
  9366. // The type of an object with thread storage duration shall not
  9367. // have a non-trivial destructor.
  9368. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  9369. if (getLangOpts().CPlusPlus11)
  9370. Diag(var->getLocation(), diag::note_use_thread_local);
  9371. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  9372. if (!checkConstInit()) {
  9373. // GNU C++98 edits for __thread, [basic.start.init]p4:
  9374. // An object of thread storage duration shall not require dynamic
  9375. // initialization.
  9376. // FIXME: Need strict checking here.
  9377. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  9378. << CacheCulprit->getSourceRange();
  9379. if (getLangOpts().CPlusPlus11)
  9380. Diag(var->getLocation(), diag::note_use_thread_local);
  9381. }
  9382. }
  9383. }
  9384. // Apply section attributes and pragmas to global variables.
  9385. bool GlobalStorage = var->hasGlobalStorage();
  9386. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  9387. ActiveTemplateInstantiations.empty()) {
  9388. PragmaStack<StringLiteral *> *Stack = nullptr;
  9389. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  9390. if (var->getType().isConstQualified())
  9391. Stack = &ConstSegStack;
  9392. else if (!var->getInit()) {
  9393. Stack = &BSSSegStack;
  9394. SectionFlags |= ASTContext::PSF_Write;
  9395. } else {
  9396. Stack = &DataSegStack;
  9397. SectionFlags |= ASTContext::PSF_Write;
  9398. }
  9399. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  9400. var->addAttr(SectionAttr::CreateImplicit(
  9401. Context, SectionAttr::Declspec_allocate,
  9402. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  9403. }
  9404. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  9405. if (UnifySection(SA->getName(), SectionFlags, var))
  9406. var->dropAttr<SectionAttr>();
  9407. // Apply the init_seg attribute if this has an initializer. If the
  9408. // initializer turns out to not be dynamic, we'll end up ignoring this
  9409. // attribute.
  9410. if (CurInitSeg && var->getInit())
  9411. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  9412. CurInitSegLoc));
  9413. }
  9414. // All the following checks are C++ only.
  9415. if (!getLangOpts().CPlusPlus) {
  9416. // If this variable must be emitted, add it as an initializer for the
  9417. // current module.
  9418. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  9419. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  9420. return;
  9421. }
  9422. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  9423. CheckCompleteDecompositionDeclaration(DD);
  9424. QualType type = var->getType();
  9425. if (type->isDependentType()) return;
  9426. // __block variables might require us to capture a copy-initializer.
  9427. if (var->hasAttr<BlocksAttr>()) {
  9428. // It's currently invalid to ever have a __block variable with an
  9429. // array type; should we diagnose that here?
  9430. // Regardless, we don't want to ignore array nesting when
  9431. // constructing this copy.
  9432. if (type->isStructureOrClassType()) {
  9433. EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
  9434. SourceLocation poi = var->getLocation();
  9435. Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
  9436. ExprResult result
  9437. = PerformMoveOrCopyInitialization(
  9438. InitializedEntity::InitializeBlock(poi, type, false),
  9439. var, var->getType(), varRef, /*AllowNRVO=*/true);
  9440. if (!result.isInvalid()) {
  9441. result = MaybeCreateExprWithCleanups(result);
  9442. Expr *init = result.getAs<Expr>();
  9443. Context.setBlockVarCopyInits(var, init);
  9444. }
  9445. }
  9446. }
  9447. Expr *Init = var->getInit();
  9448. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  9449. QualType baseType = Context.getBaseElementType(type);
  9450. if (!var->getDeclContext()->isDependentContext() &&
  9451. Init && !Init->isValueDependent()) {
  9452. if (var->isConstexpr()) {
  9453. SmallVector<PartialDiagnosticAt, 8> Notes;
  9454. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  9455. SourceLocation DiagLoc = var->getLocation();
  9456. // If the note doesn't add any useful information other than a source
  9457. // location, fold it into the primary diagnostic.
  9458. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  9459. diag::note_invalid_subexpr_in_const_expr) {
  9460. DiagLoc = Notes[0].first;
  9461. Notes.clear();
  9462. }
  9463. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  9464. << var << Init->getSourceRange();
  9465. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  9466. Diag(Notes[I].first, Notes[I].second);
  9467. }
  9468. } else if (var->isUsableInConstantExpressions(Context)) {
  9469. // Check whether the initializer of a const variable of integral or
  9470. // enumeration type is an ICE now, since we can't tell whether it was
  9471. // initialized by a constant expression if we check later.
  9472. var->checkInitIsICE();
  9473. }
  9474. // Don't emit further diagnostics about constexpr globals since they
  9475. // were just diagnosed.
  9476. if (!var->isConstexpr() && GlobalStorage &&
  9477. var->hasAttr<RequireConstantInitAttr>()) {
  9478. // FIXME: Need strict checking in C++03 here.
  9479. bool DiagErr = getLangOpts().CPlusPlus11
  9480. ? !var->checkInitIsICE() : !checkConstInit();
  9481. if (DiagErr) {
  9482. auto attr = var->getAttr<RequireConstantInitAttr>();
  9483. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  9484. << Init->getSourceRange();
  9485. Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
  9486. << attr->getRange();
  9487. }
  9488. }
  9489. else if (!var->isConstexpr() && IsGlobal &&
  9490. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  9491. var->getLocation())) {
  9492. // Warn about globals which don't have a constant initializer. Don't
  9493. // warn about globals with a non-trivial destructor because we already
  9494. // warned about them.
  9495. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  9496. if (!(RD && !RD->hasTrivialDestructor())) {
  9497. if (!checkConstInit())
  9498. Diag(var->getLocation(), diag::warn_global_constructor)
  9499. << Init->getSourceRange();
  9500. }
  9501. }
  9502. }
  9503. // Require the destructor.
  9504. if (const RecordType *recordType = baseType->getAs<RecordType>())
  9505. FinalizeVarWithDestructor(var, recordType);
  9506. // If this variable must be emitted, add it as an initializer for the current
  9507. // module.
  9508. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  9509. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  9510. }
  9511. /// \brief Determines if a variable's alignment is dependent.
  9512. static bool hasDependentAlignment(VarDecl *VD) {
  9513. if (VD->getType()->isDependentType())
  9514. return true;
  9515. for (auto *I : VD->specific_attrs<AlignedAttr>())
  9516. if (I->isAlignmentDependent())
  9517. return true;
  9518. return false;
  9519. }
  9520. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  9521. /// any semantic actions necessary after any initializer has been attached.
  9522. void
  9523. Sema::FinalizeDeclaration(Decl *ThisDecl) {
  9524. // Note that we are no longer parsing the initializer for this declaration.
  9525. ParsingInitForAutoVars.erase(ThisDecl);
  9526. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  9527. if (!VD)
  9528. return;
  9529. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  9530. for (auto *BD : DD->bindings()) {
  9531. FinalizeDeclaration(BD);
  9532. }
  9533. }
  9534. checkAttributesAfterMerging(*this, *VD);
  9535. // Perform TLS alignment check here after attributes attached to the variable
  9536. // which may affect the alignment have been processed. Only perform the check
  9537. // if the target has a maximum TLS alignment (zero means no constraints).
  9538. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  9539. // Protect the check so that it's not performed on dependent types and
  9540. // dependent alignments (we can't determine the alignment in that case).
  9541. if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
  9542. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  9543. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  9544. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  9545. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  9546. << (unsigned)MaxAlignChars.getQuantity();
  9547. }
  9548. }
  9549. }
  9550. if (VD->isStaticLocal()) {
  9551. if (FunctionDecl *FD =
  9552. dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  9553. // Static locals inherit dll attributes from their function.
  9554. if (Attr *A = getDLLAttr(FD)) {
  9555. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  9556. NewAttr->setInherited(true);
  9557. VD->addAttr(NewAttr);
  9558. }
  9559. // CUDA E.2.9.4: Within the body of a __device__ or __global__
  9560. // function, only __shared__ variables may be declared with
  9561. // static storage class.
  9562. if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
  9563. CUDADiagIfDeviceCode(VD->getLocation(),
  9564. diag::err_device_static_local_var)
  9565. << CurrentCUDATarget())
  9566. VD->setInvalidDecl();
  9567. }
  9568. }
  9569. // Perform check for initializers of device-side global variables.
  9570. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  9571. // 7.5). We must also apply the same checks to all __shared__
  9572. // variables whether they are local or not. CUDA also allows
  9573. // constant initializers for __constant__ and __device__ variables.
  9574. if (getLangOpts().CUDA) {
  9575. const Expr *Init = VD->getInit();
  9576. if (Init && VD->hasGlobalStorage()) {
  9577. if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
  9578. VD->hasAttr<CUDASharedAttr>()) {
  9579. assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
  9580. bool AllowedInit = false;
  9581. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
  9582. AllowedInit =
  9583. isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
  9584. // We'll allow constant initializers even if it's a non-empty
  9585. // constructor according to CUDA rules. This deviates from NVCC,
  9586. // but allows us to handle things like constexpr constructors.
  9587. if (!AllowedInit &&
  9588. (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  9589. AllowedInit = VD->getInit()->isConstantInitializer(
  9590. Context, VD->getType()->isReferenceType());
  9591. // Also make sure that destructor, if there is one, is empty.
  9592. if (AllowedInit)
  9593. if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
  9594. AllowedInit =
  9595. isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
  9596. if (!AllowedInit) {
  9597. Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
  9598. ? diag::err_shared_var_init
  9599. : diag::err_dynamic_var_init)
  9600. << Init->getSourceRange();
  9601. VD->setInvalidDecl();
  9602. }
  9603. } else {
  9604. // This is a host-side global variable. Check that the initializer is
  9605. // callable from the host side.
  9606. const FunctionDecl *InitFn = nullptr;
  9607. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
  9608. InitFn = CE->getConstructor();
  9609. } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
  9610. InitFn = CE->getDirectCallee();
  9611. }
  9612. if (InitFn) {
  9613. CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
  9614. if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
  9615. Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
  9616. << InitFnTarget << InitFn;
  9617. Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
  9618. VD->setInvalidDecl();
  9619. }
  9620. }
  9621. }
  9622. }
  9623. }
  9624. // Grab the dllimport or dllexport attribute off of the VarDecl.
  9625. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  9626. // Imported static data members cannot be defined out-of-line.
  9627. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  9628. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  9629. VD->isThisDeclarationADefinition()) {
  9630. // We allow definitions of dllimport class template static data members
  9631. // with a warning.
  9632. CXXRecordDecl *Context =
  9633. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  9634. bool IsClassTemplateMember =
  9635. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  9636. Context->getDescribedClassTemplate();
  9637. Diag(VD->getLocation(),
  9638. IsClassTemplateMember
  9639. ? diag::warn_attribute_dllimport_static_field_definition
  9640. : diag::err_attribute_dllimport_static_field_definition);
  9641. Diag(IA->getLocation(), diag::note_attribute);
  9642. if (!IsClassTemplateMember)
  9643. VD->setInvalidDecl();
  9644. }
  9645. }
  9646. // dllimport/dllexport variables cannot be thread local, their TLS index
  9647. // isn't exported with the variable.
  9648. if (DLLAttr && VD->getTLSKind()) {
  9649. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  9650. if (F && getDLLAttr(F)) {
  9651. assert(VD->isStaticLocal());
  9652. // But if this is a static local in a dlimport/dllexport function, the
  9653. // function will never be inlined, which means the var would never be
  9654. // imported, so having it marked import/export is safe.
  9655. } else {
  9656. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  9657. << DLLAttr;
  9658. VD->setInvalidDecl();
  9659. }
  9660. }
  9661. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  9662. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  9663. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  9664. VD->dropAttr<UsedAttr>();
  9665. }
  9666. }
  9667. const DeclContext *DC = VD->getDeclContext();
  9668. // If there's a #pragma GCC visibility in scope, and this isn't a class
  9669. // member, set the visibility of this variable.
  9670. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  9671. AddPushedVisibilityAttribute(VD);
  9672. // FIXME: Warn on unused templates.
  9673. if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
  9674. !isa<VarTemplatePartialSpecializationDecl>(VD))
  9675. MarkUnusedFileScopedDecl(VD);
  9676. // Now we have parsed the initializer and can update the table of magic
  9677. // tag values.
  9678. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  9679. !VD->getType()->isIntegralOrEnumerationType())
  9680. return;
  9681. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  9682. const Expr *MagicValueExpr = VD->getInit();
  9683. if (!MagicValueExpr) {
  9684. continue;
  9685. }
  9686. llvm::APSInt MagicValueInt;
  9687. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  9688. Diag(I->getRange().getBegin(),
  9689. diag::err_type_tag_for_datatype_not_ice)
  9690. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  9691. continue;
  9692. }
  9693. if (MagicValueInt.getActiveBits() > 64) {
  9694. Diag(I->getRange().getBegin(),
  9695. diag::err_type_tag_for_datatype_too_large)
  9696. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  9697. continue;
  9698. }
  9699. uint64_t MagicValue = MagicValueInt.getZExtValue();
  9700. RegisterTypeTagForDatatype(I->getArgumentKind(),
  9701. MagicValue,
  9702. I->getMatchingCType(),
  9703. I->getLayoutCompatible(),
  9704. I->getMustBeNull());
  9705. }
  9706. }
  9707. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  9708. ArrayRef<Decl *> Group) {
  9709. SmallVector<Decl*, 8> Decls;
  9710. if (DS.isTypeSpecOwned())
  9711. Decls.push_back(DS.getRepAsDecl());
  9712. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  9713. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  9714. bool DiagnosedMultipleDecomps = false;
  9715. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  9716. if (Decl *D = Group[i]) {
  9717. auto *DD = dyn_cast<DeclaratorDecl>(D);
  9718. if (DD && !FirstDeclaratorInGroup)
  9719. FirstDeclaratorInGroup = DD;
  9720. auto *Decomp = dyn_cast<DecompositionDecl>(D);
  9721. if (Decomp && !FirstDecompDeclaratorInGroup)
  9722. FirstDecompDeclaratorInGroup = Decomp;
  9723. // A decomposition declaration cannot be combined with any other
  9724. // declaration in the same group.
  9725. auto *OtherDD = FirstDeclaratorInGroup;
  9726. if (OtherDD == FirstDecompDeclaratorInGroup)
  9727. OtherDD = DD;
  9728. if (OtherDD && FirstDecompDeclaratorInGroup &&
  9729. OtherDD != FirstDecompDeclaratorInGroup &&
  9730. !DiagnosedMultipleDecomps) {
  9731. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  9732. diag::err_decomp_decl_not_alone)
  9733. << OtherDD->getSourceRange();
  9734. DiagnosedMultipleDecomps = true;
  9735. }
  9736. Decls.push_back(D);
  9737. }
  9738. }
  9739. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  9740. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  9741. handleTagNumbering(Tag, S);
  9742. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  9743. getLangOpts().CPlusPlus)
  9744. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  9745. }
  9746. }
  9747. return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
  9748. }
  9749. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  9750. /// group, performing any necessary semantic checking.
  9751. Sema::DeclGroupPtrTy
  9752. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
  9753. bool TypeMayContainAuto) {
  9754. // C++0x [dcl.spec.auto]p7:
  9755. // If the type deduced for the template parameter U is not the same in each
  9756. // deduction, the program is ill-formed.
  9757. // FIXME: When initializer-list support is added, a distinction is needed
  9758. // between the deduced type U and the deduced type which 'auto' stands for.
  9759. // auto a = 0, b = { 1, 2, 3 };
  9760. // is legal because the deduced type U is 'int' in both cases.
  9761. if (TypeMayContainAuto && Group.size() > 1) {
  9762. QualType Deduced;
  9763. CanQualType DeducedCanon;
  9764. VarDecl *DeducedDecl = nullptr;
  9765. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  9766. if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
  9767. AutoType *AT = D->getType()->getContainedAutoType();
  9768. // Don't reissue diagnostics when instantiating a template.
  9769. if (AT && D->isInvalidDecl())
  9770. break;
  9771. QualType U = AT ? AT->getDeducedType() : QualType();
  9772. if (!U.isNull()) {
  9773. CanQualType UCanon = Context.getCanonicalType(U);
  9774. if (Deduced.isNull()) {
  9775. Deduced = U;
  9776. DeducedCanon = UCanon;
  9777. DeducedDecl = D;
  9778. } else if (DeducedCanon != UCanon) {
  9779. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  9780. diag::err_auto_different_deductions)
  9781. << (unsigned)AT->getKeyword()
  9782. << Deduced << DeducedDecl->getDeclName()
  9783. << U << D->getDeclName()
  9784. << DeducedDecl->getInit()->getSourceRange()
  9785. << D->getInit()->getSourceRange();
  9786. D->setInvalidDecl();
  9787. break;
  9788. }
  9789. }
  9790. }
  9791. }
  9792. }
  9793. ActOnDocumentableDecls(Group);
  9794. return DeclGroupPtrTy::make(
  9795. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  9796. }
  9797. void Sema::ActOnDocumentableDecl(Decl *D) {
  9798. ActOnDocumentableDecls(D);
  9799. }
  9800. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  9801. // Don't parse the comment if Doxygen diagnostics are ignored.
  9802. if (Group.empty() || !Group[0])
  9803. return;
  9804. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  9805. Group[0]->getLocation()) &&
  9806. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  9807. Group[0]->getLocation()))
  9808. return;
  9809. if (Group.size() >= 2) {
  9810. // This is a decl group. Normally it will contain only declarations
  9811. // produced from declarator list. But in case we have any definitions or
  9812. // additional declaration references:
  9813. // 'typedef struct S {} S;'
  9814. // 'typedef struct S *S;'
  9815. // 'struct S *pS;'
  9816. // FinalizeDeclaratorGroup adds these as separate declarations.
  9817. Decl *MaybeTagDecl = Group[0];
  9818. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  9819. Group = Group.slice(1);
  9820. }
  9821. }
  9822. // See if there are any new comments that are not attached to a decl.
  9823. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  9824. if (!Comments.empty() &&
  9825. !Comments.back()->isAttached()) {
  9826. // There is at least one comment that not attached to a decl.
  9827. // Maybe it should be attached to one of these decls?
  9828. //
  9829. // Note that this way we pick up not only comments that precede the
  9830. // declaration, but also comments that *follow* the declaration -- thanks to
  9831. // the lookahead in the lexer: we've consumed the semicolon and looked
  9832. // ahead through comments.
  9833. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  9834. Context.getCommentForDecl(Group[i], &PP);
  9835. }
  9836. }
  9837. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  9838. /// to introduce parameters into function prototype scope.
  9839. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  9840. const DeclSpec &DS = D.getDeclSpec();
  9841. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  9842. // C++03 [dcl.stc]p2 also permits 'auto'.
  9843. StorageClass SC = SC_None;
  9844. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  9845. SC = SC_Register;
  9846. } else if (getLangOpts().CPlusPlus &&
  9847. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  9848. SC = SC_Auto;
  9849. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  9850. Diag(DS.getStorageClassSpecLoc(),
  9851. diag::err_invalid_storage_class_in_func_decl);
  9852. D.getMutableDeclSpec().ClearStorageClassSpecs();
  9853. }
  9854. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  9855. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  9856. << DeclSpec::getSpecifierName(TSCS);
  9857. if (DS.isInlineSpecified())
  9858. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  9859. << getLangOpts().CPlusPlus1z;
  9860. if (DS.isConstexprSpecified())
  9861. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  9862. << 0;
  9863. if (DS.isConceptSpecified())
  9864. Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
  9865. DiagnoseFunctionSpecifiers(DS);
  9866. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  9867. QualType parmDeclType = TInfo->getType();
  9868. if (getLangOpts().CPlusPlus) {
  9869. // Check that there are no default arguments inside the type of this
  9870. // parameter.
  9871. CheckExtraCXXDefaultArguments(D);
  9872. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  9873. if (D.getCXXScopeSpec().isSet()) {
  9874. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  9875. << D.getCXXScopeSpec().getRange();
  9876. D.getCXXScopeSpec().clear();
  9877. }
  9878. }
  9879. // Ensure we have a valid name
  9880. IdentifierInfo *II = nullptr;
  9881. if (D.hasName()) {
  9882. II = D.getIdentifier();
  9883. if (!II) {
  9884. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  9885. << GetNameForDeclarator(D).getName();
  9886. D.setInvalidType(true);
  9887. }
  9888. }
  9889. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  9890. if (II) {
  9891. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  9892. ForRedeclaration);
  9893. LookupName(R, S);
  9894. if (R.isSingleResult()) {
  9895. NamedDecl *PrevDecl = R.getFoundDecl();
  9896. if (PrevDecl->isTemplateParameter()) {
  9897. // Maybe we will complain about the shadowed template parameter.
  9898. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  9899. // Just pretend that we didn't see the previous declaration.
  9900. PrevDecl = nullptr;
  9901. } else if (S->isDeclScope(PrevDecl)) {
  9902. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  9903. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  9904. // Recover by removing the name
  9905. II = nullptr;
  9906. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  9907. D.setInvalidType(true);
  9908. }
  9909. }
  9910. }
  9911. // Temporarily put parameter variables in the translation unit, not
  9912. // the enclosing context. This prevents them from accidentally
  9913. // looking like class members in C++.
  9914. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  9915. D.getLocStart(),
  9916. D.getIdentifierLoc(), II,
  9917. parmDeclType, TInfo,
  9918. SC);
  9919. if (D.isInvalidType())
  9920. New->setInvalidDecl();
  9921. assert(S->isFunctionPrototypeScope());
  9922. assert(S->getFunctionPrototypeDepth() >= 1);
  9923. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  9924. S->getNextFunctionPrototypeIndex());
  9925. // Add the parameter declaration into this scope.
  9926. S->AddDecl(New);
  9927. if (II)
  9928. IdResolver.AddDecl(New);
  9929. ProcessDeclAttributes(S, New, D);
  9930. if (D.getDeclSpec().isModulePrivateSpecified())
  9931. Diag(New->getLocation(), diag::err_module_private_local)
  9932. << 1 << New->getDeclName()
  9933. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  9934. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  9935. if (New->hasAttr<BlocksAttr>()) {
  9936. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  9937. }
  9938. return New;
  9939. }
  9940. /// \brief Synthesizes a variable for a parameter arising from a
  9941. /// typedef.
  9942. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  9943. SourceLocation Loc,
  9944. QualType T) {
  9945. /* FIXME: setting StartLoc == Loc.
  9946. Would it be worth to modify callers so as to provide proper source
  9947. location for the unnamed parameters, embedding the parameter's type? */
  9948. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  9949. T, Context.getTrivialTypeSourceInfo(T, Loc),
  9950. SC_None, nullptr);
  9951. Param->setImplicit();
  9952. return Param;
  9953. }
  9954. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  9955. // Don't diagnose unused-parameter errors in template instantiations; we
  9956. // will already have done so in the template itself.
  9957. if (!ActiveTemplateInstantiations.empty())
  9958. return;
  9959. for (const ParmVarDecl *Parameter : Parameters) {
  9960. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  9961. !Parameter->hasAttr<UnusedAttr>()) {
  9962. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  9963. << Parameter->getDeclName();
  9964. }
  9965. }
  9966. }
  9967. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  9968. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  9969. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  9970. return;
  9971. // Warn if the return value is pass-by-value and larger than the specified
  9972. // threshold.
  9973. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  9974. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  9975. if (Size > LangOpts.NumLargeByValueCopy)
  9976. Diag(D->getLocation(), diag::warn_return_value_size)
  9977. << D->getDeclName() << Size;
  9978. }
  9979. // Warn if any parameter is pass-by-value and larger than the specified
  9980. // threshold.
  9981. for (const ParmVarDecl *Parameter : Parameters) {
  9982. QualType T = Parameter->getType();
  9983. if (T->isDependentType() || !T.isPODType(Context))
  9984. continue;
  9985. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  9986. if (Size > LangOpts.NumLargeByValueCopy)
  9987. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  9988. << Parameter->getDeclName() << Size;
  9989. }
  9990. }
  9991. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  9992. SourceLocation NameLoc, IdentifierInfo *Name,
  9993. QualType T, TypeSourceInfo *TSInfo,
  9994. StorageClass SC) {
  9995. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  9996. if (getLangOpts().ObjCAutoRefCount &&
  9997. T.getObjCLifetime() == Qualifiers::OCL_None &&
  9998. T->isObjCLifetimeType()) {
  9999. Qualifiers::ObjCLifetime lifetime;
  10000. // Special cases for arrays:
  10001. // - if it's const, use __unsafe_unretained
  10002. // - otherwise, it's an error
  10003. if (T->isArrayType()) {
  10004. if (!T.isConstQualified()) {
  10005. DelayedDiagnostics.add(
  10006. sema::DelayedDiagnostic::makeForbiddenType(
  10007. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  10008. }
  10009. lifetime = Qualifiers::OCL_ExplicitNone;
  10010. } else {
  10011. lifetime = T->getObjCARCImplicitLifetime();
  10012. }
  10013. T = Context.getLifetimeQualifiedType(T, lifetime);
  10014. }
  10015. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  10016. Context.getAdjustedParameterType(T),
  10017. TSInfo, SC, nullptr);
  10018. // Parameters can not be abstract class types.
  10019. // For record types, this is done by the AbstractClassUsageDiagnoser once
  10020. // the class has been completely parsed.
  10021. if (!CurContext->isRecord() &&
  10022. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  10023. AbstractParamType))
  10024. New->setInvalidDecl();
  10025. // Parameter declarators cannot be interface types. All ObjC objects are
  10026. // passed by reference.
  10027. if (T->isObjCObjectType()) {
  10028. SourceLocation TypeEndLoc =
  10029. getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
  10030. Diag(NameLoc,
  10031. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  10032. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  10033. T = Context.getObjCObjectPointerType(T);
  10034. New->setType(T);
  10035. }
  10036. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  10037. // duration shall not be qualified by an address-space qualifier."
  10038. // Since all parameters have automatic store duration, they can not have
  10039. // an address space.
  10040. if (T.getAddressSpace() != 0) {
  10041. // OpenCL allows function arguments declared to be an array of a type
  10042. // to be qualified with an address space.
  10043. if (!(getLangOpts().OpenCL && T->isArrayType())) {
  10044. Diag(NameLoc, diag::err_arg_with_address_space);
  10045. New->setInvalidDecl();
  10046. }
  10047. }
  10048. return New;
  10049. }
  10050. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  10051. SourceLocation LocAfterDecls) {
  10052. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  10053. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  10054. // for a K&R function.
  10055. if (!FTI.hasPrototype) {
  10056. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  10057. --i;
  10058. if (FTI.Params[i].Param == nullptr) {
  10059. SmallString<256> Code;
  10060. llvm::raw_svector_ostream(Code)
  10061. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  10062. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  10063. << FTI.Params[i].Ident
  10064. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  10065. // Implicitly declare the argument as type 'int' for lack of a better
  10066. // type.
  10067. AttributeFactory attrs;
  10068. DeclSpec DS(attrs);
  10069. const char* PrevSpec; // unused
  10070. unsigned DiagID; // unused
  10071. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  10072. DiagID, Context.getPrintingPolicy());
  10073. // Use the identifier location for the type source range.
  10074. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  10075. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  10076. Declarator ParamD(DS, Declarator::KNRTypeListContext);
  10077. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  10078. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  10079. }
  10080. }
  10081. }
  10082. }
  10083. Decl *
  10084. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  10085. MultiTemplateParamsArg TemplateParameterLists,
  10086. SkipBodyInfo *SkipBody) {
  10087. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  10088. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  10089. Scope *ParentScope = FnBodyScope->getParent();
  10090. D.setFunctionDefinitionKind(FDK_Definition);
  10091. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  10092. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  10093. }
  10094. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  10095. Consumer.HandleInlineFunctionDefinition(D);
  10096. }
  10097. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  10098. const FunctionDecl*& PossibleZeroParamPrototype) {
  10099. // Don't warn about invalid declarations.
  10100. if (FD->isInvalidDecl())
  10101. return false;
  10102. // Or declarations that aren't global.
  10103. if (!FD->isGlobal())
  10104. return false;
  10105. // Don't warn about C++ member functions.
  10106. if (isa<CXXMethodDecl>(FD))
  10107. return false;
  10108. // Don't warn about 'main'.
  10109. if (FD->isMain())
  10110. return false;
  10111. // Don't warn about inline functions.
  10112. if (FD->isInlined())
  10113. return false;
  10114. // Don't warn about function templates.
  10115. if (FD->getDescribedFunctionTemplate())
  10116. return false;
  10117. // Don't warn about function template specializations.
  10118. if (FD->isFunctionTemplateSpecialization())
  10119. return false;
  10120. // Don't warn for OpenCL kernels.
  10121. if (FD->hasAttr<OpenCLKernelAttr>())
  10122. return false;
  10123. // Don't warn on explicitly deleted functions.
  10124. if (FD->isDeleted())
  10125. return false;
  10126. bool MissingPrototype = true;
  10127. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  10128. Prev; Prev = Prev->getPreviousDecl()) {
  10129. // Ignore any declarations that occur in function or method
  10130. // scope, because they aren't visible from the header.
  10131. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  10132. continue;
  10133. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  10134. if (FD->getNumParams() == 0)
  10135. PossibleZeroParamPrototype = Prev;
  10136. break;
  10137. }
  10138. return MissingPrototype;
  10139. }
  10140. void
  10141. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  10142. const FunctionDecl *EffectiveDefinition,
  10143. SkipBodyInfo *SkipBody) {
  10144. // Don't complain if we're in GNU89 mode and the previous definition
  10145. // was an extern inline function.
  10146. const FunctionDecl *Definition = EffectiveDefinition;
  10147. if (!Definition)
  10148. if (!FD->isDefined(Definition))
  10149. return;
  10150. if (canRedefineFunction(Definition, getLangOpts()))
  10151. return;
  10152. // If we don't have a visible definition of the function, and it's inline or
  10153. // a template, skip the new definition.
  10154. if (SkipBody && !hasVisibleDefinition(Definition) &&
  10155. (Definition->getFormalLinkage() == InternalLinkage ||
  10156. Definition->isInlined() ||
  10157. Definition->getDescribedFunctionTemplate() ||
  10158. Definition->getNumTemplateParameterLists())) {
  10159. SkipBody->ShouldSkip = true;
  10160. if (auto *TD = Definition->getDescribedFunctionTemplate())
  10161. makeMergedDefinitionVisible(TD, FD->getLocation());
  10162. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
  10163. FD->getLocation());
  10164. return;
  10165. }
  10166. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  10167. Definition->getStorageClass() == SC_Extern)
  10168. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  10169. << FD->getDeclName() << getLangOpts().CPlusPlus;
  10170. else
  10171. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  10172. Diag(Definition->getLocation(), diag::note_previous_definition);
  10173. FD->setInvalidDecl();
  10174. }
  10175. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  10176. Sema &S) {
  10177. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  10178. LambdaScopeInfo *LSI = S.PushLambdaScope();
  10179. LSI->CallOperator = CallOperator;
  10180. LSI->Lambda = LambdaClass;
  10181. LSI->ReturnType = CallOperator->getReturnType();
  10182. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  10183. if (LCD == LCD_None)
  10184. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  10185. else if (LCD == LCD_ByCopy)
  10186. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  10187. else if (LCD == LCD_ByRef)
  10188. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  10189. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  10190. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  10191. LSI->Mutable = !CallOperator->isConst();
  10192. // Add the captures to the LSI so they can be noted as already
  10193. // captured within tryCaptureVar.
  10194. auto I = LambdaClass->field_begin();
  10195. for (const auto &C : LambdaClass->captures()) {
  10196. if (C.capturesVariable()) {
  10197. VarDecl *VD = C.getCapturedVar();
  10198. if (VD->isInitCapture())
  10199. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  10200. QualType CaptureType = VD->getType();
  10201. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  10202. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  10203. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  10204. /*EllipsisLoc*/C.isPackExpansion()
  10205. ? C.getEllipsisLoc() : SourceLocation(),
  10206. CaptureType, /*Expr*/ nullptr);
  10207. } else if (C.capturesThis()) {
  10208. LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
  10209. /*Expr*/ nullptr,
  10210. C.getCaptureKind() == LCK_StarThis);
  10211. } else {
  10212. LSI->addVLATypeCapture(C.getLocation(), I->getType());
  10213. }
  10214. ++I;
  10215. }
  10216. }
  10217. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  10218. SkipBodyInfo *SkipBody) {
  10219. // Clear the last template instantiation error context.
  10220. LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
  10221. if (!D)
  10222. return D;
  10223. FunctionDecl *FD = nullptr;
  10224. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  10225. FD = FunTmpl->getTemplatedDecl();
  10226. else
  10227. FD = cast<FunctionDecl>(D);
  10228. // See if this is a redefinition.
  10229. if (!FD->isLateTemplateParsed()) {
  10230. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  10231. // If we're skipping the body, we're done. Don't enter the scope.
  10232. if (SkipBody && SkipBody->ShouldSkip)
  10233. return D;
  10234. }
  10235. // Mark this function as "will have a body eventually". This lets users to
  10236. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  10237. // this function.
  10238. FD->setWillHaveBody();
  10239. // If we are instantiating a generic lambda call operator, push
  10240. // a LambdaScopeInfo onto the function stack. But use the information
  10241. // that's already been calculated (ActOnLambdaExpr) to prime the current
  10242. // LambdaScopeInfo.
  10243. // When the template operator is being specialized, the LambdaScopeInfo,
  10244. // has to be properly restored so that tryCaptureVariable doesn't try
  10245. // and capture any new variables. In addition when calculating potential
  10246. // captures during transformation of nested lambdas, it is necessary to
  10247. // have the LSI properly restored.
  10248. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  10249. assert(ActiveTemplateInstantiations.size() &&
  10250. "There should be an active template instantiation on the stack "
  10251. "when instantiating a generic lambda!");
  10252. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  10253. }
  10254. else
  10255. // Enter a new function scope
  10256. PushFunctionScope();
  10257. // Builtin functions cannot be defined.
  10258. if (unsigned BuiltinID = FD->getBuiltinID()) {
  10259. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  10260. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  10261. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  10262. FD->setInvalidDecl();
  10263. }
  10264. }
  10265. // The return type of a function definition must be complete
  10266. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  10267. QualType ResultType = FD->getReturnType();
  10268. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  10269. !FD->isInvalidDecl() &&
  10270. RequireCompleteType(FD->getLocation(), ResultType,
  10271. diag::err_func_def_incomplete_result))
  10272. FD->setInvalidDecl();
  10273. if (FnBodyScope)
  10274. PushDeclContext(FnBodyScope, FD);
  10275. // Check the validity of our function parameters
  10276. CheckParmsForFunctionDef(FD->parameters(),
  10277. /*CheckParameterNames=*/true);
  10278. // Introduce our parameters into the function scope
  10279. for (auto Param : FD->parameters()) {
  10280. Param->setOwningFunction(FD);
  10281. // If this has an identifier, add it to the scope stack.
  10282. if (Param->getIdentifier() && FnBodyScope) {
  10283. CheckShadow(FnBodyScope, Param);
  10284. PushOnScopeChains(Param, FnBodyScope);
  10285. }
  10286. }
  10287. // If we had any tags defined in the function prototype,
  10288. // introduce them into the function scope.
  10289. if (FnBodyScope) {
  10290. for (ArrayRef<NamedDecl *>::iterator
  10291. I = FD->getDeclsInPrototypeScope().begin(),
  10292. E = FD->getDeclsInPrototypeScope().end();
  10293. I != E; ++I) {
  10294. NamedDecl *D = *I;
  10295. // Some of these decls (like enums) may have been pinned to the
  10296. // translation unit for lack of a real context earlier. If so, remove
  10297. // from the translation unit and reattach to the current context.
  10298. if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
  10299. // Is the decl actually in the context?
  10300. if (Context.getTranslationUnitDecl()->containsDecl(D))
  10301. Context.getTranslationUnitDecl()->removeDecl(D);
  10302. // Either way, reassign the lexical decl context to our FunctionDecl.
  10303. D->setLexicalDeclContext(CurContext);
  10304. }
  10305. // If the decl has a non-null name, make accessible in the current scope.
  10306. if (!D->getName().empty())
  10307. PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
  10308. // Similarly, dive into enums and fish their constants out, making them
  10309. // accessible in this scope.
  10310. if (auto *ED = dyn_cast<EnumDecl>(D)) {
  10311. for (auto *EI : ED->enumerators())
  10312. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  10313. }
  10314. }
  10315. }
  10316. // Ensure that the function's exception specification is instantiated.
  10317. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  10318. ResolveExceptionSpec(D->getLocation(), FPT);
  10319. // dllimport cannot be applied to non-inline function definitions.
  10320. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  10321. !FD->isTemplateInstantiation()) {
  10322. assert(!FD->hasAttr<DLLExportAttr>());
  10323. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  10324. FD->setInvalidDecl();
  10325. return D;
  10326. }
  10327. // We want to attach documentation to original Decl (which might be
  10328. // a function template).
  10329. ActOnDocumentableDecl(D);
  10330. if (getCurLexicalContext()->isObjCContainer() &&
  10331. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  10332. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  10333. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  10334. return D;
  10335. }
  10336. /// \brief Given the set of return statements within a function body,
  10337. /// compute the variables that are subject to the named return value
  10338. /// optimization.
  10339. ///
  10340. /// Each of the variables that is subject to the named return value
  10341. /// optimization will be marked as NRVO variables in the AST, and any
  10342. /// return statement that has a marked NRVO variable as its NRVO candidate can
  10343. /// use the named return value optimization.
  10344. ///
  10345. /// This function applies a very simplistic algorithm for NRVO: if every return
  10346. /// statement in the scope of a variable has the same NRVO candidate, that
  10347. /// candidate is an NRVO variable.
  10348. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  10349. ReturnStmt **Returns = Scope->Returns.data();
  10350. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  10351. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  10352. if (!NRVOCandidate->isNRVOVariable())
  10353. Returns[I]->setNRVOCandidate(nullptr);
  10354. }
  10355. }
  10356. }
  10357. bool Sema::canDelayFunctionBody(const Declarator &D) {
  10358. // We can't delay parsing the body of a constexpr function template (yet).
  10359. if (D.getDeclSpec().isConstexprSpecified())
  10360. return false;
  10361. // We can't delay parsing the body of a function template with a deduced
  10362. // return type (yet).
  10363. if (D.getDeclSpec().containsPlaceholderType()) {
  10364. // If the placeholder introduces a non-deduced trailing return type,
  10365. // we can still delay parsing it.
  10366. if (D.getNumTypeObjects()) {
  10367. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  10368. if (Outer.Kind == DeclaratorChunk::Function &&
  10369. Outer.Fun.hasTrailingReturnType()) {
  10370. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  10371. return Ty.isNull() || !Ty->isUndeducedType();
  10372. }
  10373. }
  10374. return false;
  10375. }
  10376. return true;
  10377. }
  10378. bool Sema::canSkipFunctionBody(Decl *D) {
  10379. // We cannot skip the body of a function (or function template) which is
  10380. // constexpr, since we may need to evaluate its body in order to parse the
  10381. // rest of the file.
  10382. // We cannot skip the body of a function with an undeduced return type,
  10383. // because any callers of that function need to know the type.
  10384. if (const FunctionDecl *FD = D->getAsFunction())
  10385. if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
  10386. return false;
  10387. return Consumer.shouldSkipFunctionBody(D);
  10388. }
  10389. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  10390. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
  10391. FD->setHasSkippedBody();
  10392. else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
  10393. MD->setHasSkippedBody();
  10394. return Decl;
  10395. }
  10396. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  10397. return ActOnFinishFunctionBody(D, BodyArg, false);
  10398. }
  10399. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  10400. bool IsInstantiation) {
  10401. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  10402. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  10403. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  10404. if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty())
  10405. CheckCompletedCoroutineBody(FD, Body);
  10406. if (FD) {
  10407. FD->setBody(Body);
  10408. if (getLangOpts().CPlusPlus14) {
  10409. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  10410. FD->getReturnType()->isUndeducedType()) {
  10411. // If the function has a deduced result type but contains no 'return'
  10412. // statements, the result type as written must be exactly 'auto', and
  10413. // the deduced result type is 'void'.
  10414. if (!FD->getReturnType()->getAs<AutoType>()) {
  10415. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  10416. << FD->getReturnType();
  10417. FD->setInvalidDecl();
  10418. } else {
  10419. // Substitute 'void' for the 'auto' in the type.
  10420. TypeLoc ResultType = getReturnTypeLoc(FD);
  10421. Context.adjustDeducedFunctionResultType(
  10422. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  10423. }
  10424. }
  10425. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  10426. // In C++11, we don't use 'auto' deduction rules for lambda call
  10427. // operators because we don't support return type deduction.
  10428. auto *LSI = getCurLambda();
  10429. if (LSI->HasImplicitReturnType) {
  10430. deduceClosureReturnType(*LSI);
  10431. // C++11 [expr.prim.lambda]p4:
  10432. // [...] if there are no return statements in the compound-statement
  10433. // [the deduced type is] the type void
  10434. QualType RetType =
  10435. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  10436. // Update the return type to the deduced type.
  10437. const FunctionProtoType *Proto =
  10438. FD->getType()->getAs<FunctionProtoType>();
  10439. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  10440. Proto->getExtProtoInfo()));
  10441. }
  10442. }
  10443. // The only way to be included in UndefinedButUsed is if there is an
  10444. // ODR use before the definition. Avoid the expensive map lookup if this
  10445. // is the first declaration.
  10446. if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
  10447. if (!FD->isExternallyVisible())
  10448. UndefinedButUsed.erase(FD);
  10449. else if (FD->isInlined() &&
  10450. !LangOpts.GNUInline &&
  10451. (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
  10452. UndefinedButUsed.erase(FD);
  10453. }
  10454. // If the function implicitly returns zero (like 'main') or is naked,
  10455. // don't complain about missing return statements.
  10456. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  10457. WP.disableCheckFallThrough();
  10458. // MSVC permits the use of pure specifier (=0) on function definition,
  10459. // defined at class scope, warn about this non-standard construct.
  10460. if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
  10461. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  10462. if (!FD->isInvalidDecl()) {
  10463. // Don't diagnose unused parameters of defaulted or deleted functions.
  10464. if (!FD->isDeleted() && !FD->isDefaulted())
  10465. DiagnoseUnusedParameters(FD->parameters());
  10466. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  10467. FD->getReturnType(), FD);
  10468. // If this is a structor, we need a vtable.
  10469. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  10470. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  10471. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  10472. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  10473. // Try to apply the named return value optimization. We have to check
  10474. // if we can do this here because lambdas keep return statements around
  10475. // to deduce an implicit return type.
  10476. if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
  10477. !FD->isDependentContext())
  10478. computeNRVO(Body, getCurFunction());
  10479. }
  10480. // GNU warning -Wmissing-prototypes:
  10481. // Warn if a global function is defined without a previous
  10482. // prototype declaration. This warning is issued even if the
  10483. // definition itself provides a prototype. The aim is to detect
  10484. // global functions that fail to be declared in header files.
  10485. const FunctionDecl *PossibleZeroParamPrototype = nullptr;
  10486. if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
  10487. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  10488. if (PossibleZeroParamPrototype) {
  10489. // We found a declaration that is not a prototype,
  10490. // but that could be a zero-parameter prototype
  10491. if (TypeSourceInfo *TI =
  10492. PossibleZeroParamPrototype->getTypeSourceInfo()) {
  10493. TypeLoc TL = TI->getTypeLoc();
  10494. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  10495. Diag(PossibleZeroParamPrototype->getLocation(),
  10496. diag::note_declaration_not_a_prototype)
  10497. << PossibleZeroParamPrototype
  10498. << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
  10499. }
  10500. }
  10501. // GNU warning -Wstrict-prototypes
  10502. // Warn if K&R function is defined without a previous declaration.
  10503. // This warning is issued only if the definition itself does not provide
  10504. // a prototype. Only K&R definitions do not provide a prototype.
  10505. // An empty list in a function declarator that is part of a definition
  10506. // of that function specifies that the function has no parameters
  10507. // (C99 6.7.5.3p14)
  10508. if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
  10509. !LangOpts.CPlusPlus) {
  10510. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  10511. TypeLoc TL = TI->getTypeLoc();
  10512. FunctionTypeLoc FTL = TL.castAs<FunctionTypeLoc>();
  10513. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
  10514. }
  10515. }
  10516. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  10517. const CXXMethodDecl *KeyFunction;
  10518. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  10519. MD->isVirtual() &&
  10520. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  10521. MD == KeyFunction->getCanonicalDecl()) {
  10522. // Update the key-function state if necessary for this ABI.
  10523. if (FD->isInlined() &&
  10524. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  10525. Context.setNonKeyFunction(MD);
  10526. // If the newly-chosen key function is already defined, then we
  10527. // need to mark the vtable as used retroactively.
  10528. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  10529. const FunctionDecl *Definition;
  10530. if (KeyFunction && KeyFunction->isDefined(Definition))
  10531. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  10532. } else {
  10533. // We just defined they key function; mark the vtable as used.
  10534. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  10535. }
  10536. }
  10537. }
  10538. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  10539. "Function parsing confused");
  10540. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  10541. assert(MD == getCurMethodDecl() && "Method parsing confused");
  10542. MD->setBody(Body);
  10543. if (!MD->isInvalidDecl()) {
  10544. DiagnoseUnusedParameters(MD->parameters());
  10545. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  10546. MD->getReturnType(), MD);
  10547. if (Body)
  10548. computeNRVO(Body, getCurFunction());
  10549. }
  10550. if (getCurFunction()->ObjCShouldCallSuper) {
  10551. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
  10552. << MD->getSelector().getAsString();
  10553. getCurFunction()->ObjCShouldCallSuper = false;
  10554. }
  10555. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  10556. const ObjCMethodDecl *InitMethod = nullptr;
  10557. bool isDesignated =
  10558. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  10559. assert(isDesignated && InitMethod);
  10560. (void)isDesignated;
  10561. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  10562. auto IFace = MD->getClassInterface();
  10563. if (!IFace)
  10564. return false;
  10565. auto SuperD = IFace->getSuperClass();
  10566. if (!SuperD)
  10567. return false;
  10568. return SuperD->getIdentifier() ==
  10569. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  10570. };
  10571. // Don't issue this warning for unavailable inits or direct subclasses
  10572. // of NSObject.
  10573. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  10574. Diag(MD->getLocation(),
  10575. diag::warn_objc_designated_init_missing_super_call);
  10576. Diag(InitMethod->getLocation(),
  10577. diag::note_objc_designated_init_marked_here);
  10578. }
  10579. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  10580. }
  10581. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  10582. // Don't issue this warning for unavaialable inits.
  10583. if (!MD->isUnavailable())
  10584. Diag(MD->getLocation(),
  10585. diag::warn_objc_secondary_init_missing_init_call);
  10586. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  10587. }
  10588. } else {
  10589. return nullptr;
  10590. }
  10591. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  10592. DiagnoseUnguardedAvailabilityViolations(dcl);
  10593. assert(!getCurFunction()->ObjCShouldCallSuper &&
  10594. "This should only be set for ObjC methods, which should have been "
  10595. "handled in the block above.");
  10596. // Verify and clean out per-function state.
  10597. if (Body && (!FD || !FD->isDefaulted())) {
  10598. // C++ constructors that have function-try-blocks can't have return
  10599. // statements in the handlers of that block. (C++ [except.handle]p14)
  10600. // Verify this.
  10601. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  10602. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  10603. // Verify that gotos and switch cases don't jump into scopes illegally.
  10604. if (getCurFunction()->NeedsScopeChecking() &&
  10605. !PP.isCodeCompletionEnabled())
  10606. DiagnoseInvalidJumps(Body);
  10607. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  10608. if (!Destructor->getParent()->isDependentType())
  10609. CheckDestructor(Destructor);
  10610. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  10611. Destructor->getParent());
  10612. }
  10613. // If any errors have occurred, clear out any temporaries that may have
  10614. // been leftover. This ensures that these temporaries won't be picked up for
  10615. // deletion in some later function.
  10616. if (getDiagnostics().hasErrorOccurred() ||
  10617. getDiagnostics().getSuppressAllDiagnostics()) {
  10618. DiscardCleanupsInEvaluationContext();
  10619. }
  10620. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  10621. !isa<FunctionTemplateDecl>(dcl)) {
  10622. // Since the body is valid, issue any analysis-based warnings that are
  10623. // enabled.
  10624. ActivePolicy = &WP;
  10625. }
  10626. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  10627. (!CheckConstexprFunctionDecl(FD) ||
  10628. !CheckConstexprFunctionBody(FD, Body)))
  10629. FD->setInvalidDecl();
  10630. if (FD && FD->hasAttr<NakedAttr>()) {
  10631. for (const Stmt *S : Body->children()) {
  10632. // Allow local register variables without initializer as they don't
  10633. // require prologue.
  10634. bool RegisterVariables = false;
  10635. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  10636. for (const auto *Decl : DS->decls()) {
  10637. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  10638. RegisterVariables =
  10639. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  10640. if (!RegisterVariables)
  10641. break;
  10642. }
  10643. }
  10644. }
  10645. if (RegisterVariables)
  10646. continue;
  10647. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  10648. Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
  10649. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  10650. FD->setInvalidDecl();
  10651. break;
  10652. }
  10653. }
  10654. }
  10655. assert(ExprCleanupObjects.size() ==
  10656. ExprEvalContexts.back().NumCleanupObjects &&
  10657. "Leftover temporaries in function");
  10658. assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
  10659. assert(MaybeODRUseExprs.empty() &&
  10660. "Leftover expressions for odr-use checking");
  10661. }
  10662. if (!IsInstantiation)
  10663. PopDeclContext();
  10664. PopFunctionScopeInfo(ActivePolicy, dcl);
  10665. // If any errors have occurred, clear out any temporaries that may have
  10666. // been leftover. This ensures that these temporaries won't be picked up for
  10667. // deletion in some later function.
  10668. if (getDiagnostics().hasErrorOccurred()) {
  10669. DiscardCleanupsInEvaluationContext();
  10670. }
  10671. return dcl;
  10672. }
  10673. /// When we finish delayed parsing of an attribute, we must attach it to the
  10674. /// relevant Decl.
  10675. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  10676. ParsedAttributes &Attrs) {
  10677. // Always attach attributes to the underlying decl.
  10678. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  10679. D = TD->getTemplatedDecl();
  10680. ProcessDeclAttributeList(S, D, Attrs.getList());
  10681. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  10682. if (Method->isStatic())
  10683. checkThisInStaticMemberFunctionAttributes(Method);
  10684. }
  10685. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  10686. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  10687. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  10688. IdentifierInfo &II, Scope *S) {
  10689. // Before we produce a declaration for an implicitly defined
  10690. // function, see whether there was a locally-scoped declaration of
  10691. // this name as a function or variable. If so, use that
  10692. // (non-visible) declaration, and complain about it.
  10693. if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
  10694. Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
  10695. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  10696. return ExternCPrev;
  10697. }
  10698. // Extension in C99. Legal in C90, but warn about it.
  10699. unsigned diag_id;
  10700. if (II.getName().startswith("__builtin_"))
  10701. diag_id = diag::warn_builtin_unknown;
  10702. else if (getLangOpts().C99)
  10703. diag_id = diag::ext_implicit_function_decl;
  10704. else
  10705. diag_id = diag::warn_implicit_function_decl;
  10706. Diag(Loc, diag_id) << &II;
  10707. // Because typo correction is expensive, only do it if the implicit
  10708. // function declaration is going to be treated as an error.
  10709. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  10710. TypoCorrection Corrected;
  10711. if (S &&
  10712. (Corrected = CorrectTypo(
  10713. DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
  10714. llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
  10715. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  10716. /*ErrorRecovery*/false);
  10717. }
  10718. // Set a Declarator for the implicit definition: int foo();
  10719. const char *Dummy;
  10720. AttributeFactory attrFactory;
  10721. DeclSpec DS(attrFactory);
  10722. unsigned DiagID;
  10723. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  10724. Context.getPrintingPolicy());
  10725. (void)Error; // Silence warning.
  10726. assert(!Error && "Error setting up implicit decl!");
  10727. SourceLocation NoLoc;
  10728. Declarator D(DS, Declarator::BlockContext);
  10729. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  10730. /*IsAmbiguous=*/false,
  10731. /*LParenLoc=*/NoLoc,
  10732. /*Params=*/nullptr,
  10733. /*NumParams=*/0,
  10734. /*EllipsisLoc=*/NoLoc,
  10735. /*RParenLoc=*/NoLoc,
  10736. /*TypeQuals=*/0,
  10737. /*RefQualifierIsLvalueRef=*/true,
  10738. /*RefQualifierLoc=*/NoLoc,
  10739. /*ConstQualifierLoc=*/NoLoc,
  10740. /*VolatileQualifierLoc=*/NoLoc,
  10741. /*RestrictQualifierLoc=*/NoLoc,
  10742. /*MutableLoc=*/NoLoc,
  10743. EST_None,
  10744. /*ESpecRange=*/SourceRange(),
  10745. /*Exceptions=*/nullptr,
  10746. /*ExceptionRanges=*/nullptr,
  10747. /*NumExceptions=*/0,
  10748. /*NoexceptExpr=*/nullptr,
  10749. /*ExceptionSpecTokens=*/nullptr,
  10750. Loc, Loc, D),
  10751. DS.getAttributes(),
  10752. SourceLocation());
  10753. D.SetIdentifier(&II, Loc);
  10754. // Insert this function into translation-unit scope.
  10755. DeclContext *PrevDC = CurContext;
  10756. CurContext = Context.getTranslationUnitDecl();
  10757. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
  10758. FD->setImplicit();
  10759. CurContext = PrevDC;
  10760. AddKnownFunctionAttributes(FD);
  10761. return FD;
  10762. }
  10763. /// \brief Adds any function attributes that we know a priori based on
  10764. /// the declaration of this function.
  10765. ///
  10766. /// These attributes can apply both to implicitly-declared builtins
  10767. /// (like __builtin___printf_chk) or to library-declared functions
  10768. /// like NSLog or printf.
  10769. ///
  10770. /// We need to check for duplicate attributes both here and where user-written
  10771. /// attributes are applied to declarations.
  10772. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  10773. if (FD->isInvalidDecl())
  10774. return;
  10775. // If this is a built-in function, map its builtin attributes to
  10776. // actual attributes.
  10777. if (unsigned BuiltinID = FD->getBuiltinID()) {
  10778. // Handle printf-formatting attributes.
  10779. unsigned FormatIdx;
  10780. bool HasVAListArg;
  10781. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  10782. if (!FD->hasAttr<FormatAttr>()) {
  10783. const char *fmt = "printf";
  10784. unsigned int NumParams = FD->getNumParams();
  10785. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  10786. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  10787. fmt = "NSString";
  10788. FD->addAttr(FormatAttr::CreateImplicit(Context,
  10789. &Context.Idents.get(fmt),
  10790. FormatIdx+1,
  10791. HasVAListArg ? 0 : FormatIdx+2,
  10792. FD->getLocation()));
  10793. }
  10794. }
  10795. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  10796. HasVAListArg)) {
  10797. if (!FD->hasAttr<FormatAttr>())
  10798. FD->addAttr(FormatAttr::CreateImplicit(Context,
  10799. &Context.Idents.get("scanf"),
  10800. FormatIdx+1,
  10801. HasVAListArg ? 0 : FormatIdx+2,
  10802. FD->getLocation()));
  10803. }
  10804. // Mark const if we don't care about errno and that is the only
  10805. // thing preventing the function from being const. This allows
  10806. // IRgen to use LLVM intrinsics for such functions.
  10807. if (!getLangOpts().MathErrno &&
  10808. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
  10809. if (!FD->hasAttr<ConstAttr>())
  10810. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  10811. }
  10812. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  10813. !FD->hasAttr<ReturnsTwiceAttr>())
  10814. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  10815. FD->getLocation()));
  10816. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  10817. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  10818. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  10819. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  10820. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  10821. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  10822. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  10823. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  10824. // Add the appropriate attribute, depending on the CUDA compilation mode
  10825. // and which target the builtin belongs to. For example, during host
  10826. // compilation, aux builtins are __device__, while the rest are __host__.
  10827. if (getLangOpts().CUDAIsDevice !=
  10828. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  10829. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  10830. else
  10831. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  10832. }
  10833. }
  10834. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  10835. // throw, add an implicit nothrow attribute to any extern "C" function we come
  10836. // across.
  10837. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  10838. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  10839. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  10840. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  10841. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  10842. }
  10843. IdentifierInfo *Name = FD->getIdentifier();
  10844. if (!Name)
  10845. return;
  10846. if ((!getLangOpts().CPlusPlus &&
  10847. FD->getDeclContext()->isTranslationUnit()) ||
  10848. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  10849. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  10850. LinkageSpecDecl::lang_c)) {
  10851. // Okay: this could be a libc/libm/Objective-C function we know
  10852. // about.
  10853. } else
  10854. return;
  10855. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  10856. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  10857. // target-specific builtins, perhaps?
  10858. if (!FD->hasAttr<FormatAttr>())
  10859. FD->addAttr(FormatAttr::CreateImplicit(Context,
  10860. &Context.Idents.get("printf"), 2,
  10861. Name->isStr("vasprintf") ? 0 : 3,
  10862. FD->getLocation()));
  10863. }
  10864. if (Name->isStr("__CFStringMakeConstantString")) {
  10865. // We already have a __builtin___CFStringMakeConstantString,
  10866. // but builds that use -fno-constant-cfstrings don't go through that.
  10867. if (!FD->hasAttr<FormatArgAttr>())
  10868. FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
  10869. FD->getLocation()));
  10870. }
  10871. }
  10872. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  10873. TypeSourceInfo *TInfo) {
  10874. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  10875. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  10876. if (!TInfo) {
  10877. assert(D.isInvalidType() && "no declarator info for valid type");
  10878. TInfo = Context.getTrivialTypeSourceInfo(T);
  10879. }
  10880. // Scope manipulation handled by caller.
  10881. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  10882. D.getLocStart(),
  10883. D.getIdentifierLoc(),
  10884. D.getIdentifier(),
  10885. TInfo);
  10886. // Bail out immediately if we have an invalid declaration.
  10887. if (D.isInvalidType()) {
  10888. NewTD->setInvalidDecl();
  10889. return NewTD;
  10890. }
  10891. if (D.getDeclSpec().isModulePrivateSpecified()) {
  10892. if (CurContext->isFunctionOrMethod())
  10893. Diag(NewTD->getLocation(), diag::err_module_private_local)
  10894. << 2 << NewTD->getDeclName()
  10895. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  10896. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  10897. else
  10898. NewTD->setModulePrivate();
  10899. }
  10900. // C++ [dcl.typedef]p8:
  10901. // If the typedef declaration defines an unnamed class (or
  10902. // enum), the first typedef-name declared by the declaration
  10903. // to be that class type (or enum type) is used to denote the
  10904. // class type (or enum type) for linkage purposes only.
  10905. // We need to check whether the type was declared in the declaration.
  10906. switch (D.getDeclSpec().getTypeSpecType()) {
  10907. case TST_enum:
  10908. case TST_struct:
  10909. case TST_interface:
  10910. case TST_union:
  10911. case TST_class: {
  10912. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  10913. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  10914. break;
  10915. }
  10916. default:
  10917. break;
  10918. }
  10919. return NewTD;
  10920. }
  10921. /// \brief Check that this is a valid underlying type for an enum declaration.
  10922. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  10923. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  10924. QualType T = TI->getType();
  10925. if (T->isDependentType())
  10926. return false;
  10927. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  10928. if (BT->isInteger())
  10929. return false;
  10930. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  10931. return true;
  10932. }
  10933. /// Check whether this is a valid redeclaration of a previous enumeration.
  10934. /// \return true if the redeclaration was invalid.
  10935. bool Sema::CheckEnumRedeclaration(
  10936. SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
  10937. bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
  10938. bool IsFixed = !EnumUnderlyingTy.isNull();
  10939. if (IsScoped != Prev->isScoped()) {
  10940. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  10941. << Prev->isScoped();
  10942. Diag(Prev->getLocation(), diag::note_previous_declaration);
  10943. return true;
  10944. }
  10945. if (IsFixed && Prev->isFixed()) {
  10946. if (!EnumUnderlyingTy->isDependentType() &&
  10947. !Prev->getIntegerType()->isDependentType() &&
  10948. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  10949. Prev->getIntegerType())) {
  10950. // TODO: Highlight the underlying type of the redeclaration.
  10951. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  10952. << EnumUnderlyingTy << Prev->getIntegerType();
  10953. Diag(Prev->getLocation(), diag::note_previous_declaration)
  10954. << Prev->getIntegerTypeRange();
  10955. return true;
  10956. }
  10957. } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
  10958. ;
  10959. } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
  10960. ;
  10961. } else if (IsFixed != Prev->isFixed()) {
  10962. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  10963. << Prev->isFixed();
  10964. Diag(Prev->getLocation(), diag::note_previous_declaration);
  10965. return true;
  10966. }
  10967. return false;
  10968. }
  10969. /// \brief Get diagnostic %select index for tag kind for
  10970. /// redeclaration diagnostic message.
  10971. /// WARNING: Indexes apply to particular diagnostics only!
  10972. ///
  10973. /// \returns diagnostic %select index.
  10974. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  10975. switch (Tag) {
  10976. case TTK_Struct: return 0;
  10977. case TTK_Interface: return 1;
  10978. case TTK_Class: return 2;
  10979. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  10980. }
  10981. }
  10982. /// \brief Determine if tag kind is a class-key compatible with
  10983. /// class for redeclaration (class, struct, or __interface).
  10984. ///
  10985. /// \returns true iff the tag kind is compatible.
  10986. static bool isClassCompatTagKind(TagTypeKind Tag)
  10987. {
  10988. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  10989. }
  10990. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl) {
  10991. if (isa<TypedefDecl>(PrevDecl))
  10992. return NTK_Typedef;
  10993. else if (isa<TypeAliasDecl>(PrevDecl))
  10994. return NTK_TypeAlias;
  10995. else if (isa<ClassTemplateDecl>(PrevDecl))
  10996. return NTK_Template;
  10997. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  10998. return NTK_TypeAliasTemplate;
  10999. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  11000. return NTK_TemplateTemplateArgument;
  11001. return NTK_Unknown;
  11002. }
  11003. /// \brief Determine whether a tag with a given kind is acceptable
  11004. /// as a redeclaration of the given tag declaration.
  11005. ///
  11006. /// \returns true if the new tag kind is acceptable, false otherwise.
  11007. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  11008. TagTypeKind NewTag, bool isDefinition,
  11009. SourceLocation NewTagLoc,
  11010. const IdentifierInfo *Name) {
  11011. // C++ [dcl.type.elab]p3:
  11012. // The class-key or enum keyword present in the
  11013. // elaborated-type-specifier shall agree in kind with the
  11014. // declaration to which the name in the elaborated-type-specifier
  11015. // refers. This rule also applies to the form of
  11016. // elaborated-type-specifier that declares a class-name or
  11017. // friend class since it can be construed as referring to the
  11018. // definition of the class. Thus, in any
  11019. // elaborated-type-specifier, the enum keyword shall be used to
  11020. // refer to an enumeration (7.2), the union class-key shall be
  11021. // used to refer to a union (clause 9), and either the class or
  11022. // struct class-key shall be used to refer to a class (clause 9)
  11023. // declared using the class or struct class-key.
  11024. TagTypeKind OldTag = Previous->getTagKind();
  11025. if (!isDefinition || !isClassCompatTagKind(NewTag))
  11026. if (OldTag == NewTag)
  11027. return true;
  11028. if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
  11029. // Warn about the struct/class tag mismatch.
  11030. bool isTemplate = false;
  11031. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  11032. isTemplate = Record->getDescribedClassTemplate();
  11033. if (!ActiveTemplateInstantiations.empty()) {
  11034. // In a template instantiation, do not offer fix-its for tag mismatches
  11035. // since they usually mess up the template instead of fixing the problem.
  11036. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  11037. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11038. << getRedeclDiagFromTagKind(OldTag);
  11039. return true;
  11040. }
  11041. if (isDefinition) {
  11042. // On definitions, check previous tags and issue a fix-it for each
  11043. // one that doesn't match the current tag.
  11044. if (Previous->getDefinition()) {
  11045. // Don't suggest fix-its for redefinitions.
  11046. return true;
  11047. }
  11048. bool previousMismatch = false;
  11049. for (auto I : Previous->redecls()) {
  11050. if (I->getTagKind() != NewTag) {
  11051. if (!previousMismatch) {
  11052. previousMismatch = true;
  11053. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  11054. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11055. << getRedeclDiagFromTagKind(I->getTagKind());
  11056. }
  11057. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  11058. << getRedeclDiagFromTagKind(NewTag)
  11059. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  11060. TypeWithKeyword::getTagTypeKindName(NewTag));
  11061. }
  11062. }
  11063. return true;
  11064. }
  11065. // Check for a previous definition. If current tag and definition
  11066. // are same type, do nothing. If no definition, but disagree with
  11067. // with previous tag type, give a warning, but no fix-it.
  11068. const TagDecl *Redecl = Previous->getDefinition() ?
  11069. Previous->getDefinition() : Previous;
  11070. if (Redecl->getTagKind() == NewTag) {
  11071. return true;
  11072. }
  11073. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  11074. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11075. << getRedeclDiagFromTagKind(OldTag);
  11076. Diag(Redecl->getLocation(), diag::note_previous_use);
  11077. // If there is a previous definition, suggest a fix-it.
  11078. if (Previous->getDefinition()) {
  11079. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  11080. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  11081. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  11082. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  11083. }
  11084. return true;
  11085. }
  11086. return false;
  11087. }
  11088. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  11089. /// from an outer enclosing namespace or file scope inside a friend declaration.
  11090. /// This should provide the commented out code in the following snippet:
  11091. /// namespace N {
  11092. /// struct X;
  11093. /// namespace M {
  11094. /// struct Y { friend struct /*N::*/ X; };
  11095. /// }
  11096. /// }
  11097. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  11098. SourceLocation NameLoc) {
  11099. // While the decl is in a namespace, do repeated lookup of that name and see
  11100. // if we get the same namespace back. If we do not, continue until
  11101. // translation unit scope, at which point we have a fully qualified NNS.
  11102. SmallVector<IdentifierInfo *, 4> Namespaces;
  11103. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  11104. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  11105. // This tag should be declared in a namespace, which can only be enclosed by
  11106. // other namespaces. Bail if there's an anonymous namespace in the chain.
  11107. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  11108. if (!Namespace || Namespace->isAnonymousNamespace())
  11109. return FixItHint();
  11110. IdentifierInfo *II = Namespace->getIdentifier();
  11111. Namespaces.push_back(II);
  11112. NamedDecl *Lookup = SemaRef.LookupSingleName(
  11113. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  11114. if (Lookup == Namespace)
  11115. break;
  11116. }
  11117. // Once we have all the namespaces, reverse them to go outermost first, and
  11118. // build an NNS.
  11119. SmallString<64> Insertion;
  11120. llvm::raw_svector_ostream OS(Insertion);
  11121. if (DC->isTranslationUnit())
  11122. OS << "::";
  11123. std::reverse(Namespaces.begin(), Namespaces.end());
  11124. for (auto *II : Namespaces)
  11125. OS << II->getName() << "::";
  11126. return FixItHint::CreateInsertion(NameLoc, Insertion);
  11127. }
  11128. /// \brief Determine whether a tag originally declared in context \p OldDC can
  11129. /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
  11130. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  11131. /// using-declaration).
  11132. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  11133. DeclContext *NewDC) {
  11134. OldDC = OldDC->getRedeclContext();
  11135. NewDC = NewDC->getRedeclContext();
  11136. if (OldDC->Equals(NewDC))
  11137. return true;
  11138. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  11139. // encloses the other).
  11140. if (S.getLangOpts().MSVCCompat &&
  11141. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  11142. return true;
  11143. return false;
  11144. }
  11145. /// Find the DeclContext in which a tag is implicitly declared if we see an
  11146. /// elaborated type specifier in the specified context, and lookup finds
  11147. /// nothing.
  11148. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  11149. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  11150. DC = DC->getParent();
  11151. return DC;
  11152. }
  11153. /// Find the Scope in which a tag is implicitly declared if we see an
  11154. /// elaborated type specifier in the specified context, and lookup finds
  11155. /// nothing.
  11156. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  11157. while (S->isClassScope() ||
  11158. (LangOpts.CPlusPlus &&
  11159. S->isFunctionPrototypeScope()) ||
  11160. ((S->getFlags() & Scope::DeclScope) == 0) ||
  11161. (S->getEntity() && S->getEntity()->isTransparentContext()))
  11162. S = S->getParent();
  11163. return S;
  11164. }
  11165. /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
  11166. /// former case, Name will be non-null. In the later case, Name will be null.
  11167. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  11168. /// reference/declaration/definition of a tag.
  11169. ///
  11170. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  11171. /// trailing-type-specifier) other than one in an alias-declaration.
  11172. ///
  11173. /// \param SkipBody If non-null, will be set to indicate if the caller should
  11174. /// skip the definition of this tag and treat it as if it were a declaration.
  11175. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  11176. SourceLocation KWLoc, CXXScopeSpec &SS,
  11177. IdentifierInfo *Name, SourceLocation NameLoc,
  11178. AttributeList *Attr, AccessSpecifier AS,
  11179. SourceLocation ModulePrivateLoc,
  11180. MultiTemplateParamsArg TemplateParameterLists,
  11181. bool &OwnedDecl, bool &IsDependent,
  11182. SourceLocation ScopedEnumKWLoc,
  11183. bool ScopedEnumUsesClassTag,
  11184. TypeResult UnderlyingType,
  11185. bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
  11186. // If this is not a definition, it must have a name.
  11187. IdentifierInfo *OrigName = Name;
  11188. assert((Name != nullptr || TUK == TUK_Definition) &&
  11189. "Nameless record must be a definition!");
  11190. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  11191. OwnedDecl = false;
  11192. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  11193. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  11194. // FIXME: Check explicit specializations more carefully.
  11195. bool isExplicitSpecialization = false;
  11196. bool Invalid = false;
  11197. // We only need to do this matching if we have template parameters
  11198. // or a scope specifier, which also conveniently avoids this work
  11199. // for non-C++ cases.
  11200. if (TemplateParameterLists.size() > 0 ||
  11201. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  11202. if (TemplateParameterList *TemplateParams =
  11203. MatchTemplateParametersToScopeSpecifier(
  11204. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  11205. TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
  11206. if (Kind == TTK_Enum) {
  11207. Diag(KWLoc, diag::err_enum_template);
  11208. return nullptr;
  11209. }
  11210. if (TemplateParams->size() > 0) {
  11211. // This is a declaration or definition of a class template (which may
  11212. // be a member of another template).
  11213. if (Invalid)
  11214. return nullptr;
  11215. OwnedDecl = false;
  11216. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  11217. SS, Name, NameLoc, Attr,
  11218. TemplateParams, AS,
  11219. ModulePrivateLoc,
  11220. /*FriendLoc*/SourceLocation(),
  11221. TemplateParameterLists.size()-1,
  11222. TemplateParameterLists.data(),
  11223. SkipBody);
  11224. return Result.get();
  11225. } else {
  11226. // The "template<>" header is extraneous.
  11227. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  11228. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  11229. isExplicitSpecialization = true;
  11230. }
  11231. }
  11232. }
  11233. // Figure out the underlying type if this a enum declaration. We need to do
  11234. // this early, because it's needed to detect if this is an incompatible
  11235. // redeclaration.
  11236. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  11237. bool EnumUnderlyingIsImplicit = false;
  11238. if (Kind == TTK_Enum) {
  11239. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
  11240. // No underlying type explicitly specified, or we failed to parse the
  11241. // type, default to int.
  11242. EnumUnderlying = Context.IntTy.getTypePtr();
  11243. else if (UnderlyingType.get()) {
  11244. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  11245. // integral type; any cv-qualification is ignored.
  11246. TypeSourceInfo *TI = nullptr;
  11247. GetTypeFromParser(UnderlyingType.get(), &TI);
  11248. EnumUnderlying = TI;
  11249. if (CheckEnumUnderlyingType(TI))
  11250. // Recover by falling back to int.
  11251. EnumUnderlying = Context.IntTy.getTypePtr();
  11252. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  11253. UPPC_FixedUnderlyingType))
  11254. EnumUnderlying = Context.IntTy.getTypePtr();
  11255. } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  11256. if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
  11257. // Microsoft enums are always of int type.
  11258. EnumUnderlying = Context.IntTy.getTypePtr();
  11259. EnumUnderlyingIsImplicit = true;
  11260. }
  11261. }
  11262. }
  11263. DeclContext *SearchDC = CurContext;
  11264. DeclContext *DC = CurContext;
  11265. bool isStdBadAlloc = false;
  11266. bool isStdAlignValT = false;
  11267. RedeclarationKind Redecl = ForRedeclaration;
  11268. if (TUK == TUK_Friend || TUK == TUK_Reference)
  11269. Redecl = NotForRedeclaration;
  11270. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  11271. if (Name && SS.isNotEmpty()) {
  11272. // We have a nested-name tag ('struct foo::bar').
  11273. // Check for invalid 'foo::'.
  11274. if (SS.isInvalid()) {
  11275. Name = nullptr;
  11276. goto CreateNewDecl;
  11277. }
  11278. // If this is a friend or a reference to a class in a dependent
  11279. // context, don't try to make a decl for it.
  11280. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  11281. DC = computeDeclContext(SS, false);
  11282. if (!DC) {
  11283. IsDependent = true;
  11284. return nullptr;
  11285. }
  11286. } else {
  11287. DC = computeDeclContext(SS, true);
  11288. if (!DC) {
  11289. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  11290. << SS.getRange();
  11291. return nullptr;
  11292. }
  11293. }
  11294. if (RequireCompleteDeclContext(SS, DC))
  11295. return nullptr;
  11296. SearchDC = DC;
  11297. // Look-up name inside 'foo::'.
  11298. LookupQualifiedName(Previous, DC);
  11299. if (Previous.isAmbiguous())
  11300. return nullptr;
  11301. if (Previous.empty()) {
  11302. // Name lookup did not find anything. However, if the
  11303. // nested-name-specifier refers to the current instantiation,
  11304. // and that current instantiation has any dependent base
  11305. // classes, we might find something at instantiation time: treat
  11306. // this as a dependent elaborated-type-specifier.
  11307. // But this only makes any sense for reference-like lookups.
  11308. if (Previous.wasNotFoundInCurrentInstantiation() &&
  11309. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  11310. IsDependent = true;
  11311. return nullptr;
  11312. }
  11313. // A tag 'foo::bar' must already exist.
  11314. Diag(NameLoc, diag::err_not_tag_in_scope)
  11315. << Kind << Name << DC << SS.getRange();
  11316. Name = nullptr;
  11317. Invalid = true;
  11318. goto CreateNewDecl;
  11319. }
  11320. } else if (Name) {
  11321. // C++14 [class.mem]p14:
  11322. // If T is the name of a class, then each of the following shall have a
  11323. // name different from T:
  11324. // -- every member of class T that is itself a type
  11325. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  11326. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  11327. return nullptr;
  11328. // If this is a named struct, check to see if there was a previous forward
  11329. // declaration or definition.
  11330. // FIXME: We're looking into outer scopes here, even when we
  11331. // shouldn't be. Doing so can result in ambiguities that we
  11332. // shouldn't be diagnosing.
  11333. LookupName(Previous, S);
  11334. // When declaring or defining a tag, ignore ambiguities introduced
  11335. // by types using'ed into this scope.
  11336. if (Previous.isAmbiguous() &&
  11337. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  11338. LookupResult::Filter F = Previous.makeFilter();
  11339. while (F.hasNext()) {
  11340. NamedDecl *ND = F.next();
  11341. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  11342. SearchDC->getRedeclContext()))
  11343. F.erase();
  11344. }
  11345. F.done();
  11346. }
  11347. // C++11 [namespace.memdef]p3:
  11348. // If the name in a friend declaration is neither qualified nor
  11349. // a template-id and the declaration is a function or an
  11350. // elaborated-type-specifier, the lookup to determine whether
  11351. // the entity has been previously declared shall not consider
  11352. // any scopes outside the innermost enclosing namespace.
  11353. //
  11354. // MSVC doesn't implement the above rule for types, so a friend tag
  11355. // declaration may be a redeclaration of a type declared in an enclosing
  11356. // scope. They do implement this rule for friend functions.
  11357. //
  11358. // Does it matter that this should be by scope instead of by
  11359. // semantic context?
  11360. if (!Previous.empty() && TUK == TUK_Friend) {
  11361. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  11362. LookupResult::Filter F = Previous.makeFilter();
  11363. bool FriendSawTagOutsideEnclosingNamespace = false;
  11364. while (F.hasNext()) {
  11365. NamedDecl *ND = F.next();
  11366. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  11367. if (DC->isFileContext() &&
  11368. !EnclosingNS->Encloses(ND->getDeclContext())) {
  11369. if (getLangOpts().MSVCCompat)
  11370. FriendSawTagOutsideEnclosingNamespace = true;
  11371. else
  11372. F.erase();
  11373. }
  11374. }
  11375. F.done();
  11376. // Diagnose this MSVC extension in the easy case where lookup would have
  11377. // unambiguously found something outside the enclosing namespace.
  11378. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  11379. NamedDecl *ND = Previous.getFoundDecl();
  11380. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  11381. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  11382. }
  11383. }
  11384. // Note: there used to be some attempt at recovery here.
  11385. if (Previous.isAmbiguous())
  11386. return nullptr;
  11387. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  11388. // FIXME: This makes sure that we ignore the contexts associated
  11389. // with C structs, unions, and enums when looking for a matching
  11390. // tag declaration or definition. See the similar lookup tweak
  11391. // in Sema::LookupName; is there a better way to deal with this?
  11392. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  11393. SearchDC = SearchDC->getParent();
  11394. }
  11395. }
  11396. if (Previous.isSingleResult() &&
  11397. Previous.getFoundDecl()->isTemplateParameter()) {
  11398. // Maybe we will complain about the shadowed template parameter.
  11399. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  11400. // Just pretend that we didn't see the previous declaration.
  11401. Previous.clear();
  11402. }
  11403. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  11404. DC->Equals(getStdNamespace())) {
  11405. if (Name->isStr("bad_alloc")) {
  11406. // This is a declaration of or a reference to "std::bad_alloc".
  11407. isStdBadAlloc = true;
  11408. // If std::bad_alloc has been implicitly declared (but made invisible to
  11409. // name lookup), fill in this implicit declaration as the previous
  11410. // declaration, so that the declarations get chained appropriately.
  11411. if (Previous.empty() && StdBadAlloc)
  11412. Previous.addDecl(getStdBadAlloc());
  11413. } else if (Name->isStr("align_val_t")) {
  11414. isStdAlignValT = true;
  11415. if (Previous.empty() && StdAlignValT)
  11416. Previous.addDecl(getStdAlignValT());
  11417. }
  11418. }
  11419. // If we didn't find a previous declaration, and this is a reference
  11420. // (or friend reference), move to the correct scope. In C++, we
  11421. // also need to do a redeclaration lookup there, just in case
  11422. // there's a shadow friend decl.
  11423. if (Name && Previous.empty() &&
  11424. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  11425. if (Invalid) goto CreateNewDecl;
  11426. assert(SS.isEmpty());
  11427. if (TUK == TUK_Reference) {
  11428. // C++ [basic.scope.pdecl]p5:
  11429. // -- for an elaborated-type-specifier of the form
  11430. //
  11431. // class-key identifier
  11432. //
  11433. // if the elaborated-type-specifier is used in the
  11434. // decl-specifier-seq or parameter-declaration-clause of a
  11435. // function defined in namespace scope, the identifier is
  11436. // declared as a class-name in the namespace that contains
  11437. // the declaration; otherwise, except as a friend
  11438. // declaration, the identifier is declared in the smallest
  11439. // non-class, non-function-prototype scope that contains the
  11440. // declaration.
  11441. //
  11442. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  11443. // C structs and unions.
  11444. //
  11445. // It is an error in C++ to declare (rather than define) an enum
  11446. // type, including via an elaborated type specifier. We'll
  11447. // diagnose that later; for now, declare the enum in the same
  11448. // scope as we would have picked for any other tag type.
  11449. //
  11450. // GNU C also supports this behavior as part of its incomplete
  11451. // enum types extension, while GNU C++ does not.
  11452. //
  11453. // Find the context where we'll be declaring the tag.
  11454. // FIXME: We would like to maintain the current DeclContext as the
  11455. // lexical context,
  11456. SearchDC = getTagInjectionContext(SearchDC);
  11457. // Find the scope where we'll be declaring the tag.
  11458. S = getTagInjectionScope(S, getLangOpts());
  11459. } else {
  11460. assert(TUK == TUK_Friend);
  11461. // C++ [namespace.memdef]p3:
  11462. // If a friend declaration in a non-local class first declares a
  11463. // class or function, the friend class or function is a member of
  11464. // the innermost enclosing namespace.
  11465. SearchDC = SearchDC->getEnclosingNamespaceContext();
  11466. }
  11467. // In C++, we need to do a redeclaration lookup to properly
  11468. // diagnose some problems.
  11469. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  11470. // hidden declaration so that we don't get ambiguity errors when using a
  11471. // type declared by an elaborated-type-specifier. In C that is not correct
  11472. // and we should instead merge compatible types found by lookup.
  11473. if (getLangOpts().CPlusPlus) {
  11474. Previous.setRedeclarationKind(ForRedeclaration);
  11475. LookupQualifiedName(Previous, SearchDC);
  11476. } else {
  11477. Previous.setRedeclarationKind(ForRedeclaration);
  11478. LookupName(Previous, S);
  11479. }
  11480. }
  11481. // If we have a known previous declaration to use, then use it.
  11482. if (Previous.empty() && SkipBody && SkipBody->Previous)
  11483. Previous.addDecl(SkipBody->Previous);
  11484. if (!Previous.empty()) {
  11485. NamedDecl *PrevDecl = Previous.getFoundDecl();
  11486. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  11487. // It's okay to have a tag decl in the same scope as a typedef
  11488. // which hides a tag decl in the same scope. Finding this
  11489. // insanity with a redeclaration lookup can only actually happen
  11490. // in C++.
  11491. //
  11492. // This is also okay for elaborated-type-specifiers, which is
  11493. // technically forbidden by the current standard but which is
  11494. // okay according to the likely resolution of an open issue;
  11495. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  11496. if (getLangOpts().CPlusPlus) {
  11497. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  11498. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  11499. TagDecl *Tag = TT->getDecl();
  11500. if (Tag->getDeclName() == Name &&
  11501. Tag->getDeclContext()->getRedeclContext()
  11502. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  11503. PrevDecl = Tag;
  11504. Previous.clear();
  11505. Previous.addDecl(Tag);
  11506. Previous.resolveKind();
  11507. }
  11508. }
  11509. }
  11510. }
  11511. // If this is a redeclaration of a using shadow declaration, it must
  11512. // declare a tag in the same context. In MSVC mode, we allow a
  11513. // redefinition if either context is within the other.
  11514. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  11515. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  11516. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  11517. isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
  11518. !(OldTag && isAcceptableTagRedeclContext(
  11519. *this, OldTag->getDeclContext(), SearchDC))) {
  11520. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  11521. Diag(Shadow->getTargetDecl()->getLocation(),
  11522. diag::note_using_decl_target);
  11523. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  11524. << 0;
  11525. // Recover by ignoring the old declaration.
  11526. Previous.clear();
  11527. goto CreateNewDecl;
  11528. }
  11529. }
  11530. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  11531. // If this is a use of a previous tag, or if the tag is already declared
  11532. // in the same scope (so that the definition/declaration completes or
  11533. // rementions the tag), reuse the decl.
  11534. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  11535. isDeclInScope(DirectPrevDecl, SearchDC, S,
  11536. SS.isNotEmpty() || isExplicitSpecialization)) {
  11537. // Make sure that this wasn't declared as an enum and now used as a
  11538. // struct or something similar.
  11539. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  11540. TUK == TUK_Definition, KWLoc,
  11541. Name)) {
  11542. bool SafeToContinue
  11543. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  11544. Kind != TTK_Enum);
  11545. if (SafeToContinue)
  11546. Diag(KWLoc, diag::err_use_with_wrong_tag)
  11547. << Name
  11548. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  11549. PrevTagDecl->getKindName());
  11550. else
  11551. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  11552. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  11553. if (SafeToContinue)
  11554. Kind = PrevTagDecl->getTagKind();
  11555. else {
  11556. // Recover by making this an anonymous redefinition.
  11557. Name = nullptr;
  11558. Previous.clear();
  11559. Invalid = true;
  11560. }
  11561. }
  11562. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  11563. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  11564. // If this is an elaborated-type-specifier for a scoped enumeration,
  11565. // the 'class' keyword is not necessary and not permitted.
  11566. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  11567. if (ScopedEnum)
  11568. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  11569. << PrevEnum->isScoped()
  11570. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  11571. return PrevTagDecl;
  11572. }
  11573. QualType EnumUnderlyingTy;
  11574. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  11575. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  11576. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  11577. EnumUnderlyingTy = QualType(T, 0);
  11578. // All conflicts with previous declarations are recovered by
  11579. // returning the previous declaration, unless this is a definition,
  11580. // in which case we want the caller to bail out.
  11581. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  11582. ScopedEnum, EnumUnderlyingTy,
  11583. EnumUnderlyingIsImplicit, PrevEnum))
  11584. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  11585. }
  11586. // C++11 [class.mem]p1:
  11587. // A member shall not be declared twice in the member-specification,
  11588. // except that a nested class or member class template can be declared
  11589. // and then later defined.
  11590. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  11591. S->isDeclScope(PrevDecl)) {
  11592. Diag(NameLoc, diag::ext_member_redeclared);
  11593. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  11594. }
  11595. if (!Invalid) {
  11596. // If this is a use, just return the declaration we found, unless
  11597. // we have attributes.
  11598. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  11599. if (Attr) {
  11600. // FIXME: Diagnose these attributes. For now, we create a new
  11601. // declaration to hold them.
  11602. } else if (TUK == TUK_Reference &&
  11603. (PrevTagDecl->getFriendObjectKind() ==
  11604. Decl::FOK_Undeclared ||
  11605. PP.getModuleContainingLocation(
  11606. PrevDecl->getLocation()) !=
  11607. PP.getModuleContainingLocation(KWLoc)) &&
  11608. SS.isEmpty()) {
  11609. // This declaration is a reference to an existing entity, but
  11610. // has different visibility from that entity: it either makes
  11611. // a friend visible or it makes a type visible in a new module.
  11612. // In either case, create a new declaration. We only do this if
  11613. // the declaration would have meant the same thing if no prior
  11614. // declaration were found, that is, if it was found in the same
  11615. // scope where we would have injected a declaration.
  11616. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  11617. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  11618. return PrevTagDecl;
  11619. // This is in the injected scope, create a new declaration in
  11620. // that scope.
  11621. S = getTagInjectionScope(S, getLangOpts());
  11622. } else {
  11623. return PrevTagDecl;
  11624. }
  11625. }
  11626. // Diagnose attempts to redefine a tag.
  11627. if (TUK == TUK_Definition) {
  11628. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  11629. // If we're defining a specialization and the previous definition
  11630. // is from an implicit instantiation, don't emit an error
  11631. // here; we'll catch this in the general case below.
  11632. bool IsExplicitSpecializationAfterInstantiation = false;
  11633. if (isExplicitSpecialization) {
  11634. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  11635. IsExplicitSpecializationAfterInstantiation =
  11636. RD->getTemplateSpecializationKind() !=
  11637. TSK_ExplicitSpecialization;
  11638. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  11639. IsExplicitSpecializationAfterInstantiation =
  11640. ED->getTemplateSpecializationKind() !=
  11641. TSK_ExplicitSpecialization;
  11642. }
  11643. NamedDecl *Hidden = nullptr;
  11644. if (SkipBody && getLangOpts().CPlusPlus &&
  11645. !hasVisibleDefinition(Def, &Hidden)) {
  11646. // There is a definition of this tag, but it is not visible. We
  11647. // explicitly make use of C++'s one definition rule here, and
  11648. // assume that this definition is identical to the hidden one
  11649. // we already have. Make the existing definition visible and
  11650. // use it in place of this one.
  11651. SkipBody->ShouldSkip = true;
  11652. makeMergedDefinitionVisible(Hidden, KWLoc);
  11653. return Def;
  11654. } else if (!IsExplicitSpecializationAfterInstantiation) {
  11655. // A redeclaration in function prototype scope in C isn't
  11656. // visible elsewhere, so merely issue a warning.
  11657. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  11658. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  11659. else
  11660. Diag(NameLoc, diag::err_redefinition) << Name;
  11661. Diag(Def->getLocation(), diag::note_previous_definition);
  11662. // If this is a redefinition, recover by making this
  11663. // struct be anonymous, which will make any later
  11664. // references get the previous definition.
  11665. Name = nullptr;
  11666. Previous.clear();
  11667. Invalid = true;
  11668. }
  11669. } else {
  11670. // If the type is currently being defined, complain
  11671. // about a nested redefinition.
  11672. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  11673. if (TD->isBeingDefined()) {
  11674. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  11675. Diag(PrevTagDecl->getLocation(),
  11676. diag::note_previous_definition);
  11677. Name = nullptr;
  11678. Previous.clear();
  11679. Invalid = true;
  11680. }
  11681. }
  11682. // Okay, this is definition of a previously declared or referenced
  11683. // tag. We're going to create a new Decl for it.
  11684. }
  11685. // Okay, we're going to make a redeclaration. If this is some kind
  11686. // of reference, make sure we build the redeclaration in the same DC
  11687. // as the original, and ignore the current access specifier.
  11688. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  11689. SearchDC = PrevTagDecl->getDeclContext();
  11690. AS = AS_none;
  11691. }
  11692. }
  11693. // If we get here we have (another) forward declaration or we
  11694. // have a definition. Just create a new decl.
  11695. } else {
  11696. // If we get here, this is a definition of a new tag type in a nested
  11697. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  11698. // new decl/type. We set PrevDecl to NULL so that the entities
  11699. // have distinct types.
  11700. Previous.clear();
  11701. }
  11702. // If we get here, we're going to create a new Decl. If PrevDecl
  11703. // is non-NULL, it's a definition of the tag declared by
  11704. // PrevDecl. If it's NULL, we have a new definition.
  11705. // Otherwise, PrevDecl is not a tag, but was found with tag
  11706. // lookup. This is only actually possible in C++, where a few
  11707. // things like templates still live in the tag namespace.
  11708. } else {
  11709. // Use a better diagnostic if an elaborated-type-specifier
  11710. // found the wrong kind of type on the first
  11711. // (non-redeclaration) lookup.
  11712. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  11713. !Previous.isForRedeclaration()) {
  11714. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl);
  11715. Diag(NameLoc, diag::err_tag_reference_non_tag) << NTK;
  11716. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  11717. Invalid = true;
  11718. // Otherwise, only diagnose if the declaration is in scope.
  11719. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  11720. SS.isNotEmpty() || isExplicitSpecialization)) {
  11721. // do nothing
  11722. // Diagnose implicit declarations introduced by elaborated types.
  11723. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  11724. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl);
  11725. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  11726. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  11727. Invalid = true;
  11728. // Otherwise it's a declaration. Call out a particularly common
  11729. // case here.
  11730. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  11731. unsigned Kind = 0;
  11732. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  11733. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  11734. << Name << Kind << TND->getUnderlyingType();
  11735. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  11736. Invalid = true;
  11737. // Otherwise, diagnose.
  11738. } else {
  11739. // The tag name clashes with something else in the target scope,
  11740. // issue an error and recover by making this tag be anonymous.
  11741. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  11742. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  11743. Name = nullptr;
  11744. Invalid = true;
  11745. }
  11746. // The existing declaration isn't relevant to us; we're in a
  11747. // new scope, so clear out the previous declaration.
  11748. Previous.clear();
  11749. }
  11750. }
  11751. CreateNewDecl:
  11752. TagDecl *PrevDecl = nullptr;
  11753. if (Previous.isSingleResult())
  11754. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  11755. // If there is an identifier, use the location of the identifier as the
  11756. // location of the decl, otherwise use the location of the struct/union
  11757. // keyword.
  11758. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  11759. // Otherwise, create a new declaration. If there is a previous
  11760. // declaration of the same entity, the two will be linked via
  11761. // PrevDecl.
  11762. TagDecl *New;
  11763. bool IsForwardReference = false;
  11764. if (Kind == TTK_Enum) {
  11765. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  11766. // enum X { A, B, C } D; D should chain to X.
  11767. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  11768. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  11769. ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
  11770. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  11771. StdAlignValT = cast<EnumDecl>(New);
  11772. // If this is an undefined enum, warn.
  11773. if (TUK != TUK_Definition && !Invalid) {
  11774. TagDecl *Def;
  11775. if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
  11776. cast<EnumDecl>(New)->isFixed()) {
  11777. // C++0x: 7.2p2: opaque-enum-declaration.
  11778. // Conflicts are diagnosed above. Do nothing.
  11779. }
  11780. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  11781. Diag(Loc, diag::ext_forward_ref_enum_def)
  11782. << New;
  11783. Diag(Def->getLocation(), diag::note_previous_definition);
  11784. } else {
  11785. unsigned DiagID = diag::ext_forward_ref_enum;
  11786. if (getLangOpts().MSVCCompat)
  11787. DiagID = diag::ext_ms_forward_ref_enum;
  11788. else if (getLangOpts().CPlusPlus)
  11789. DiagID = diag::err_forward_ref_enum;
  11790. Diag(Loc, DiagID);
  11791. // If this is a forward-declared reference to an enumeration, make a
  11792. // note of it; we won't actually be introducing the declaration into
  11793. // the declaration context.
  11794. if (TUK == TUK_Reference)
  11795. IsForwardReference = true;
  11796. }
  11797. }
  11798. if (EnumUnderlying) {
  11799. EnumDecl *ED = cast<EnumDecl>(New);
  11800. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  11801. ED->setIntegerTypeSourceInfo(TI);
  11802. else
  11803. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  11804. ED->setPromotionType(ED->getIntegerType());
  11805. }
  11806. } else {
  11807. // struct/union/class
  11808. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  11809. // struct X { int A; } D; D should chain to X.
  11810. if (getLangOpts().CPlusPlus) {
  11811. // FIXME: Look for a way to use RecordDecl for simple structs.
  11812. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  11813. cast_or_null<CXXRecordDecl>(PrevDecl));
  11814. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  11815. StdBadAlloc = cast<CXXRecordDecl>(New);
  11816. } else
  11817. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  11818. cast_or_null<RecordDecl>(PrevDecl));
  11819. }
  11820. // C++11 [dcl.type]p3:
  11821. // A type-specifier-seq shall not define a class or enumeration [...].
  11822. if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
  11823. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  11824. << Context.getTagDeclType(New);
  11825. Invalid = true;
  11826. }
  11827. // Maybe add qualifier info.
  11828. if (SS.isNotEmpty()) {
  11829. if (SS.isSet()) {
  11830. // If this is either a declaration or a definition, check the
  11831. // nested-name-specifier against the current context. We don't do this
  11832. // for explicit specializations, because they have similar checking
  11833. // (with more specific diagnostics) in the call to
  11834. // CheckMemberSpecialization, below.
  11835. if (!isExplicitSpecialization &&
  11836. (TUK == TUK_Definition || TUK == TUK_Declaration) &&
  11837. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
  11838. Invalid = true;
  11839. New->setQualifierInfo(SS.getWithLocInContext(Context));
  11840. if (TemplateParameterLists.size() > 0) {
  11841. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  11842. }
  11843. }
  11844. else
  11845. Invalid = true;
  11846. }
  11847. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  11848. // Add alignment attributes if necessary; these attributes are checked when
  11849. // the ASTContext lays out the structure.
  11850. //
  11851. // It is important for implementing the correct semantics that this
  11852. // happen here (in act on tag decl). The #pragma pack stack is
  11853. // maintained as a result of parser callbacks which can occur at
  11854. // many points during the parsing of a struct declaration (because
  11855. // the #pragma tokens are effectively skipped over during the
  11856. // parsing of the struct).
  11857. if (TUK == TUK_Definition) {
  11858. AddAlignmentAttributesForRecord(RD);
  11859. AddMsStructLayoutForRecord(RD);
  11860. }
  11861. }
  11862. if (ModulePrivateLoc.isValid()) {
  11863. if (isExplicitSpecialization)
  11864. Diag(New->getLocation(), diag::err_module_private_specialization)
  11865. << 2
  11866. << FixItHint::CreateRemoval(ModulePrivateLoc);
  11867. // __module_private__ does not apply to local classes. However, we only
  11868. // diagnose this as an error when the declaration specifiers are
  11869. // freestanding. Here, we just ignore the __module_private__.
  11870. else if (!SearchDC->isFunctionOrMethod())
  11871. New->setModulePrivate();
  11872. }
  11873. // If this is a specialization of a member class (of a class template),
  11874. // check the specialization.
  11875. if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
  11876. Invalid = true;
  11877. // If we're declaring or defining a tag in function prototype scope in C,
  11878. // note that this type can only be used within the function and add it to
  11879. // the list of decls to inject into the function definition scope.
  11880. if ((Name || Kind == TTK_Enum) &&
  11881. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  11882. if (getLangOpts().CPlusPlus) {
  11883. // C++ [dcl.fct]p6:
  11884. // Types shall not be defined in return or parameter types.
  11885. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  11886. Diag(Loc, diag::err_type_defined_in_param_type)
  11887. << Name;
  11888. Invalid = true;
  11889. }
  11890. } else if (!PrevDecl) {
  11891. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  11892. }
  11893. DeclsInPrototypeScope.push_back(New);
  11894. }
  11895. if (Invalid)
  11896. New->setInvalidDecl();
  11897. if (Attr)
  11898. ProcessDeclAttributeList(S, New, Attr);
  11899. // Set the lexical context. If the tag has a C++ scope specifier, the
  11900. // lexical context will be different from the semantic context.
  11901. New->setLexicalDeclContext(CurContext);
  11902. // Mark this as a friend decl if applicable.
  11903. // In Microsoft mode, a friend declaration also acts as a forward
  11904. // declaration so we always pass true to setObjectOfFriendDecl to make
  11905. // the tag name visible.
  11906. if (TUK == TUK_Friend)
  11907. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  11908. // Set the access specifier.
  11909. if (!Invalid && SearchDC->isRecord())
  11910. SetMemberAccessSpecifier(New, PrevDecl, AS);
  11911. if (TUK == TUK_Definition)
  11912. New->startDefinition();
  11913. // If this has an identifier, add it to the scope stack.
  11914. if (TUK == TUK_Friend) {
  11915. // We might be replacing an existing declaration in the lookup tables;
  11916. // if so, borrow its access specifier.
  11917. if (PrevDecl)
  11918. New->setAccess(PrevDecl->getAccess());
  11919. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  11920. DC->makeDeclVisibleInContext(New);
  11921. if (Name) // can be null along some error paths
  11922. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  11923. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  11924. } else if (Name) {
  11925. S = getNonFieldDeclScope(S);
  11926. PushOnScopeChains(New, S, !IsForwardReference);
  11927. if (IsForwardReference)
  11928. SearchDC->makeDeclVisibleInContext(New);
  11929. } else {
  11930. CurContext->addDecl(New);
  11931. }
  11932. // If this is the C FILE type, notify the AST context.
  11933. if (IdentifierInfo *II = New->getIdentifier())
  11934. if (!New->isInvalidDecl() &&
  11935. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  11936. II->isStr("FILE"))
  11937. Context.setFILEDecl(New);
  11938. if (PrevDecl)
  11939. mergeDeclAttributes(New, PrevDecl);
  11940. // If there's a #pragma GCC visibility in scope, set the visibility of this
  11941. // record.
  11942. AddPushedVisibilityAttribute(New);
  11943. OwnedDecl = true;
  11944. // In C++, don't return an invalid declaration. We can't recover well from
  11945. // the cases where we make the type anonymous.
  11946. if (Invalid && getLangOpts().CPlusPlus) {
  11947. if (New->isBeingDefined())
  11948. if (auto RD = dyn_cast<RecordDecl>(New))
  11949. RD->completeDefinition();
  11950. return nullptr;
  11951. } else {
  11952. return New;
  11953. }
  11954. }
  11955. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  11956. AdjustDeclIfTemplate(TagD);
  11957. TagDecl *Tag = cast<TagDecl>(TagD);
  11958. // Enter the tag context.
  11959. PushDeclContext(S, Tag);
  11960. ActOnDocumentableDecl(TagD);
  11961. // If there's a #pragma GCC visibility in scope, set the visibility of this
  11962. // record.
  11963. AddPushedVisibilityAttribute(Tag);
  11964. }
  11965. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  11966. assert(isa<ObjCContainerDecl>(IDecl) &&
  11967. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  11968. DeclContext *OCD = cast<DeclContext>(IDecl);
  11969. assert(getContainingDC(OCD) == CurContext &&
  11970. "The next DeclContext should be lexically contained in the current one.");
  11971. CurContext = OCD;
  11972. return IDecl;
  11973. }
  11974. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  11975. SourceLocation FinalLoc,
  11976. bool IsFinalSpelledSealed,
  11977. SourceLocation LBraceLoc) {
  11978. AdjustDeclIfTemplate(TagD);
  11979. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  11980. FieldCollector->StartClass();
  11981. if (!Record->getIdentifier())
  11982. return;
  11983. if (FinalLoc.isValid())
  11984. Record->addAttr(new (Context)
  11985. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  11986. // C++ [class]p2:
  11987. // [...] The class-name is also inserted into the scope of the
  11988. // class itself; this is known as the injected-class-name. For
  11989. // purposes of access checking, the injected-class-name is treated
  11990. // as if it were a public member name.
  11991. CXXRecordDecl *InjectedClassName
  11992. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  11993. Record->getLocStart(), Record->getLocation(),
  11994. Record->getIdentifier(),
  11995. /*PrevDecl=*/nullptr,
  11996. /*DelayTypeCreation=*/true);
  11997. Context.getTypeDeclType(InjectedClassName, Record);
  11998. InjectedClassName->setImplicit();
  11999. InjectedClassName->setAccess(AS_public);
  12000. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  12001. InjectedClassName->setDescribedClassTemplate(Template);
  12002. PushOnScopeChains(InjectedClassName, S);
  12003. assert(InjectedClassName->isInjectedClassName() &&
  12004. "Broken injected-class-name");
  12005. }
  12006. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  12007. SourceRange BraceRange) {
  12008. AdjustDeclIfTemplate(TagD);
  12009. TagDecl *Tag = cast<TagDecl>(TagD);
  12010. Tag->setBraceRange(BraceRange);
  12011. // Make sure we "complete" the definition even it is invalid.
  12012. if (Tag->isBeingDefined()) {
  12013. assert(Tag->isInvalidDecl() && "We should already have completed it");
  12014. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  12015. RD->completeDefinition();
  12016. }
  12017. if (isa<CXXRecordDecl>(Tag))
  12018. FieldCollector->FinishClass();
  12019. // Exit this scope of this tag's definition.
  12020. PopDeclContext();
  12021. if (getCurLexicalContext()->isObjCContainer() &&
  12022. Tag->getDeclContext()->isFileContext())
  12023. Tag->setTopLevelDeclInObjCContainer();
  12024. // Notify the consumer that we've defined a tag.
  12025. if (!Tag->isInvalidDecl())
  12026. Consumer.HandleTagDeclDefinition(Tag);
  12027. }
  12028. void Sema::ActOnObjCContainerFinishDefinition() {
  12029. // Exit this scope of this interface definition.
  12030. PopDeclContext();
  12031. }
  12032. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  12033. assert(DC == CurContext && "Mismatch of container contexts");
  12034. OriginalLexicalContext = DC;
  12035. ActOnObjCContainerFinishDefinition();
  12036. }
  12037. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  12038. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  12039. OriginalLexicalContext = nullptr;
  12040. }
  12041. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  12042. AdjustDeclIfTemplate(TagD);
  12043. TagDecl *Tag = cast<TagDecl>(TagD);
  12044. Tag->setInvalidDecl();
  12045. // Make sure we "complete" the definition even it is invalid.
  12046. if (Tag->isBeingDefined()) {
  12047. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  12048. RD->completeDefinition();
  12049. }
  12050. // We're undoing ActOnTagStartDefinition here, not
  12051. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  12052. // the FieldCollector.
  12053. PopDeclContext();
  12054. }
  12055. // Note that FieldName may be null for anonymous bitfields.
  12056. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  12057. IdentifierInfo *FieldName,
  12058. QualType FieldTy, bool IsMsStruct,
  12059. Expr *BitWidth, bool *ZeroWidth) {
  12060. // Default to true; that shouldn't confuse checks for emptiness
  12061. if (ZeroWidth)
  12062. *ZeroWidth = true;
  12063. // C99 6.7.2.1p4 - verify the field type.
  12064. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  12065. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  12066. // Handle incomplete types with specific error.
  12067. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  12068. return ExprError();
  12069. if (FieldName)
  12070. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  12071. << FieldName << FieldTy << BitWidth->getSourceRange();
  12072. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  12073. << FieldTy << BitWidth->getSourceRange();
  12074. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  12075. UPPC_BitFieldWidth))
  12076. return ExprError();
  12077. // If the bit-width is type- or value-dependent, don't try to check
  12078. // it now.
  12079. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  12080. return BitWidth;
  12081. llvm::APSInt Value;
  12082. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  12083. if (ICE.isInvalid())
  12084. return ICE;
  12085. BitWidth = ICE.get();
  12086. if (Value != 0 && ZeroWidth)
  12087. *ZeroWidth = false;
  12088. // Zero-width bitfield is ok for anonymous field.
  12089. if (Value == 0 && FieldName)
  12090. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  12091. if (Value.isSigned() && Value.isNegative()) {
  12092. if (FieldName)
  12093. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  12094. << FieldName << Value.toString(10);
  12095. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  12096. << Value.toString(10);
  12097. }
  12098. if (!FieldTy->isDependentType()) {
  12099. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  12100. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  12101. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  12102. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  12103. // ABI.
  12104. bool CStdConstraintViolation =
  12105. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  12106. bool MSBitfieldViolation =
  12107. Value.ugt(TypeStorageSize) &&
  12108. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  12109. if (CStdConstraintViolation || MSBitfieldViolation) {
  12110. unsigned DiagWidth =
  12111. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  12112. if (FieldName)
  12113. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  12114. << FieldName << (unsigned)Value.getZExtValue()
  12115. << !CStdConstraintViolation << DiagWidth;
  12116. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  12117. << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
  12118. << DiagWidth;
  12119. }
  12120. // Warn on types where the user might conceivably expect to get all
  12121. // specified bits as value bits: that's all integral types other than
  12122. // 'bool'.
  12123. if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
  12124. if (FieldName)
  12125. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  12126. << FieldName << (unsigned)Value.getZExtValue()
  12127. << (unsigned)TypeWidth;
  12128. else
  12129. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  12130. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  12131. }
  12132. }
  12133. return BitWidth;
  12134. }
  12135. /// ActOnField - Each field of a C struct/union is passed into this in order
  12136. /// to create a FieldDecl object for it.
  12137. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  12138. Declarator &D, Expr *BitfieldWidth) {
  12139. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  12140. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  12141. /*InitStyle=*/ICIS_NoInit, AS_public);
  12142. return Res;
  12143. }
  12144. /// HandleField - Analyze a field of a C struct or a C++ data member.
  12145. ///
  12146. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  12147. SourceLocation DeclStart,
  12148. Declarator &D, Expr *BitWidth,
  12149. InClassInitStyle InitStyle,
  12150. AccessSpecifier AS) {
  12151. if (D.isDecompositionDeclarator()) {
  12152. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  12153. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  12154. << Decomp.getSourceRange();
  12155. return nullptr;
  12156. }
  12157. IdentifierInfo *II = D.getIdentifier();
  12158. SourceLocation Loc = DeclStart;
  12159. if (II) Loc = D.getIdentifierLoc();
  12160. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12161. QualType T = TInfo->getType();
  12162. if (getLangOpts().CPlusPlus) {
  12163. CheckExtraCXXDefaultArguments(D);
  12164. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  12165. UPPC_DataMemberType)) {
  12166. D.setInvalidType();
  12167. T = Context.IntTy;
  12168. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  12169. }
  12170. }
  12171. // TR 18037 does not allow fields to be declared with address spaces.
  12172. if (T.getQualifiers().hasAddressSpace()) {
  12173. Diag(Loc, diag::err_field_with_address_space);
  12174. D.setInvalidType();
  12175. }
  12176. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  12177. // used as structure or union field: image, sampler, event or block types.
  12178. if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
  12179. T->isSamplerT() || T->isBlockPointerType())) {
  12180. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  12181. D.setInvalidType();
  12182. }
  12183. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  12184. if (D.getDeclSpec().isInlineSpecified())
  12185. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  12186. << getLangOpts().CPlusPlus1z;
  12187. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  12188. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  12189. diag::err_invalid_thread)
  12190. << DeclSpec::getSpecifierName(TSCS);
  12191. // Check to see if this name was declared as a member previously
  12192. NamedDecl *PrevDecl = nullptr;
  12193. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  12194. LookupName(Previous, S);
  12195. switch (Previous.getResultKind()) {
  12196. case LookupResult::Found:
  12197. case LookupResult::FoundUnresolvedValue:
  12198. PrevDecl = Previous.getAsSingle<NamedDecl>();
  12199. break;
  12200. case LookupResult::FoundOverloaded:
  12201. PrevDecl = Previous.getRepresentativeDecl();
  12202. break;
  12203. case LookupResult::NotFound:
  12204. case LookupResult::NotFoundInCurrentInstantiation:
  12205. case LookupResult::Ambiguous:
  12206. break;
  12207. }
  12208. Previous.suppressDiagnostics();
  12209. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  12210. // Maybe we will complain about the shadowed template parameter.
  12211. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  12212. // Just pretend that we didn't see the previous declaration.
  12213. PrevDecl = nullptr;
  12214. }
  12215. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  12216. PrevDecl = nullptr;
  12217. bool Mutable
  12218. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  12219. SourceLocation TSSL = D.getLocStart();
  12220. FieldDecl *NewFD
  12221. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  12222. TSSL, AS, PrevDecl, &D);
  12223. if (NewFD->isInvalidDecl())
  12224. Record->setInvalidDecl();
  12225. if (D.getDeclSpec().isModulePrivateSpecified())
  12226. NewFD->setModulePrivate();
  12227. if (NewFD->isInvalidDecl() && PrevDecl) {
  12228. // Don't introduce NewFD into scope; there's already something
  12229. // with the same name in the same scope.
  12230. } else if (II) {
  12231. PushOnScopeChains(NewFD, S);
  12232. } else
  12233. Record->addDecl(NewFD);
  12234. return NewFD;
  12235. }
  12236. /// \brief Build a new FieldDecl and check its well-formedness.
  12237. ///
  12238. /// This routine builds a new FieldDecl given the fields name, type,
  12239. /// record, etc. \p PrevDecl should refer to any previous declaration
  12240. /// with the same name and in the same scope as the field to be
  12241. /// created.
  12242. ///
  12243. /// \returns a new FieldDecl.
  12244. ///
  12245. /// \todo The Declarator argument is a hack. It will be removed once
  12246. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  12247. TypeSourceInfo *TInfo,
  12248. RecordDecl *Record, SourceLocation Loc,
  12249. bool Mutable, Expr *BitWidth,
  12250. InClassInitStyle InitStyle,
  12251. SourceLocation TSSL,
  12252. AccessSpecifier AS, NamedDecl *PrevDecl,
  12253. Declarator *D) {
  12254. IdentifierInfo *II = Name.getAsIdentifierInfo();
  12255. bool InvalidDecl = false;
  12256. if (D) InvalidDecl = D->isInvalidType();
  12257. // If we receive a broken type, recover by assuming 'int' and
  12258. // marking this declaration as invalid.
  12259. if (T.isNull()) {
  12260. InvalidDecl = true;
  12261. T = Context.IntTy;
  12262. }
  12263. QualType EltTy = Context.getBaseElementType(T);
  12264. if (!EltTy->isDependentType()) {
  12265. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  12266. // Fields of incomplete type force their record to be invalid.
  12267. Record->setInvalidDecl();
  12268. InvalidDecl = true;
  12269. } else {
  12270. NamedDecl *Def;
  12271. EltTy->isIncompleteType(&Def);
  12272. if (Def && Def->isInvalidDecl()) {
  12273. Record->setInvalidDecl();
  12274. InvalidDecl = true;
  12275. }
  12276. }
  12277. }
  12278. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  12279. if (BitWidth && getLangOpts().OpenCL) {
  12280. Diag(Loc, diag::err_opencl_bitfields);
  12281. InvalidDecl = true;
  12282. }
  12283. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  12284. // than a variably modified type.
  12285. if (!InvalidDecl && T->isVariablyModifiedType()) {
  12286. bool SizeIsNegative;
  12287. llvm::APSInt Oversized;
  12288. TypeSourceInfo *FixedTInfo =
  12289. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  12290. SizeIsNegative,
  12291. Oversized);
  12292. if (FixedTInfo) {
  12293. Diag(Loc, diag::warn_illegal_constant_array_size);
  12294. TInfo = FixedTInfo;
  12295. T = FixedTInfo->getType();
  12296. } else {
  12297. if (SizeIsNegative)
  12298. Diag(Loc, diag::err_typecheck_negative_array_size);
  12299. else if (Oversized.getBoolValue())
  12300. Diag(Loc, diag::err_array_too_large)
  12301. << Oversized.toString(10);
  12302. else
  12303. Diag(Loc, diag::err_typecheck_field_variable_size);
  12304. InvalidDecl = true;
  12305. }
  12306. }
  12307. // Fields can not have abstract class types
  12308. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  12309. diag::err_abstract_type_in_decl,
  12310. AbstractFieldType))
  12311. InvalidDecl = true;
  12312. bool ZeroWidth = false;
  12313. if (InvalidDecl)
  12314. BitWidth = nullptr;
  12315. // If this is declared as a bit-field, check the bit-field.
  12316. if (BitWidth) {
  12317. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  12318. &ZeroWidth).get();
  12319. if (!BitWidth) {
  12320. InvalidDecl = true;
  12321. BitWidth = nullptr;
  12322. ZeroWidth = false;
  12323. }
  12324. }
  12325. // Check that 'mutable' is consistent with the type of the declaration.
  12326. if (!InvalidDecl && Mutable) {
  12327. unsigned DiagID = 0;
  12328. if (T->isReferenceType())
  12329. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  12330. : diag::err_mutable_reference;
  12331. else if (T.isConstQualified())
  12332. DiagID = diag::err_mutable_const;
  12333. if (DiagID) {
  12334. SourceLocation ErrLoc = Loc;
  12335. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  12336. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  12337. Diag(ErrLoc, DiagID);
  12338. if (DiagID != diag::ext_mutable_reference) {
  12339. Mutable = false;
  12340. InvalidDecl = true;
  12341. }
  12342. }
  12343. }
  12344. // C++11 [class.union]p8 (DR1460):
  12345. // At most one variant member of a union may have a
  12346. // brace-or-equal-initializer.
  12347. if (InitStyle != ICIS_NoInit)
  12348. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  12349. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  12350. BitWidth, Mutable, InitStyle);
  12351. if (InvalidDecl)
  12352. NewFD->setInvalidDecl();
  12353. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  12354. Diag(Loc, diag::err_duplicate_member) << II;
  12355. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  12356. NewFD->setInvalidDecl();
  12357. }
  12358. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  12359. if (Record->isUnion()) {
  12360. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  12361. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  12362. if (RDecl->getDefinition()) {
  12363. // C++ [class.union]p1: An object of a class with a non-trivial
  12364. // constructor, a non-trivial copy constructor, a non-trivial
  12365. // destructor, or a non-trivial copy assignment operator
  12366. // cannot be a member of a union, nor can an array of such
  12367. // objects.
  12368. if (CheckNontrivialField(NewFD))
  12369. NewFD->setInvalidDecl();
  12370. }
  12371. }
  12372. // C++ [class.union]p1: If a union contains a member of reference type,
  12373. // the program is ill-formed, except when compiling with MSVC extensions
  12374. // enabled.
  12375. if (EltTy->isReferenceType()) {
  12376. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  12377. diag::ext_union_member_of_reference_type :
  12378. diag::err_union_member_of_reference_type)
  12379. << NewFD->getDeclName() << EltTy;
  12380. if (!getLangOpts().MicrosoftExt)
  12381. NewFD->setInvalidDecl();
  12382. }
  12383. }
  12384. }
  12385. // FIXME: We need to pass in the attributes given an AST
  12386. // representation, not a parser representation.
  12387. if (D) {
  12388. // FIXME: The current scope is almost... but not entirely... correct here.
  12389. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  12390. if (NewFD->hasAttrs())
  12391. CheckAlignasUnderalignment(NewFD);
  12392. }
  12393. // In auto-retain/release, infer strong retension for fields of
  12394. // retainable type.
  12395. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  12396. NewFD->setInvalidDecl();
  12397. if (T.isObjCGCWeak())
  12398. Diag(Loc, diag::warn_attribute_weak_on_field);
  12399. NewFD->setAccess(AS);
  12400. return NewFD;
  12401. }
  12402. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  12403. assert(FD);
  12404. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  12405. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  12406. return false;
  12407. QualType EltTy = Context.getBaseElementType(FD->getType());
  12408. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  12409. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  12410. if (RDecl->getDefinition()) {
  12411. // We check for copy constructors before constructors
  12412. // because otherwise we'll never get complaints about
  12413. // copy constructors.
  12414. CXXSpecialMember member = CXXInvalid;
  12415. // We're required to check for any non-trivial constructors. Since the
  12416. // implicit default constructor is suppressed if there are any
  12417. // user-declared constructors, we just need to check that there is a
  12418. // trivial default constructor and a trivial copy constructor. (We don't
  12419. // worry about move constructors here, since this is a C++98 check.)
  12420. if (RDecl->hasNonTrivialCopyConstructor())
  12421. member = CXXCopyConstructor;
  12422. else if (!RDecl->hasTrivialDefaultConstructor())
  12423. member = CXXDefaultConstructor;
  12424. else if (RDecl->hasNonTrivialCopyAssignment())
  12425. member = CXXCopyAssignment;
  12426. else if (RDecl->hasNonTrivialDestructor())
  12427. member = CXXDestructor;
  12428. if (member != CXXInvalid) {
  12429. if (!getLangOpts().CPlusPlus11 &&
  12430. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  12431. // Objective-C++ ARC: it is an error to have a non-trivial field of
  12432. // a union. However, system headers in Objective-C programs
  12433. // occasionally have Objective-C lifetime objects within unions,
  12434. // and rather than cause the program to fail, we make those
  12435. // members unavailable.
  12436. SourceLocation Loc = FD->getLocation();
  12437. if (getSourceManager().isInSystemHeader(Loc)) {
  12438. if (!FD->hasAttr<UnavailableAttr>())
  12439. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  12440. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  12441. return false;
  12442. }
  12443. }
  12444. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  12445. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  12446. diag::err_illegal_union_or_anon_struct_member)
  12447. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  12448. DiagnoseNontrivial(RDecl, member);
  12449. return !getLangOpts().CPlusPlus11;
  12450. }
  12451. }
  12452. }
  12453. return false;
  12454. }
  12455. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  12456. /// AST enum value.
  12457. static ObjCIvarDecl::AccessControl
  12458. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  12459. switch (ivarVisibility) {
  12460. default: llvm_unreachable("Unknown visitibility kind");
  12461. case tok::objc_private: return ObjCIvarDecl::Private;
  12462. case tok::objc_public: return ObjCIvarDecl::Public;
  12463. case tok::objc_protected: return ObjCIvarDecl::Protected;
  12464. case tok::objc_package: return ObjCIvarDecl::Package;
  12465. }
  12466. }
  12467. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  12468. /// in order to create an IvarDecl object for it.
  12469. Decl *Sema::ActOnIvar(Scope *S,
  12470. SourceLocation DeclStart,
  12471. Declarator &D, Expr *BitfieldWidth,
  12472. tok::ObjCKeywordKind Visibility) {
  12473. IdentifierInfo *II = D.getIdentifier();
  12474. Expr *BitWidth = (Expr*)BitfieldWidth;
  12475. SourceLocation Loc = DeclStart;
  12476. if (II) Loc = D.getIdentifierLoc();
  12477. // FIXME: Unnamed fields can be handled in various different ways, for
  12478. // example, unnamed unions inject all members into the struct namespace!
  12479. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12480. QualType T = TInfo->getType();
  12481. if (BitWidth) {
  12482. // 6.7.2.1p3, 6.7.2.1p4
  12483. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  12484. if (!BitWidth)
  12485. D.setInvalidType();
  12486. } else {
  12487. // Not a bitfield.
  12488. // validate II.
  12489. }
  12490. if (T->isReferenceType()) {
  12491. Diag(Loc, diag::err_ivar_reference_type);
  12492. D.setInvalidType();
  12493. }
  12494. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  12495. // than a variably modified type.
  12496. else if (T->isVariablyModifiedType()) {
  12497. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  12498. D.setInvalidType();
  12499. }
  12500. // Get the visibility (access control) for this ivar.
  12501. ObjCIvarDecl::AccessControl ac =
  12502. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  12503. : ObjCIvarDecl::None;
  12504. // Must set ivar's DeclContext to its enclosing interface.
  12505. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  12506. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  12507. return nullptr;
  12508. ObjCContainerDecl *EnclosingContext;
  12509. if (ObjCImplementationDecl *IMPDecl =
  12510. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  12511. if (LangOpts.ObjCRuntime.isFragile()) {
  12512. // Case of ivar declared in an implementation. Context is that of its class.
  12513. EnclosingContext = IMPDecl->getClassInterface();
  12514. assert(EnclosingContext && "Implementation has no class interface!");
  12515. }
  12516. else
  12517. EnclosingContext = EnclosingDecl;
  12518. } else {
  12519. if (ObjCCategoryDecl *CDecl =
  12520. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  12521. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  12522. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  12523. return nullptr;
  12524. }
  12525. }
  12526. EnclosingContext = EnclosingDecl;
  12527. }
  12528. // Construct the decl.
  12529. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  12530. DeclStart, Loc, II, T,
  12531. TInfo, ac, (Expr *)BitfieldWidth);
  12532. if (II) {
  12533. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  12534. ForRedeclaration);
  12535. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  12536. && !isa<TagDecl>(PrevDecl)) {
  12537. Diag(Loc, diag::err_duplicate_member) << II;
  12538. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  12539. NewID->setInvalidDecl();
  12540. }
  12541. }
  12542. // Process attributes attached to the ivar.
  12543. ProcessDeclAttributes(S, NewID, D);
  12544. if (D.isInvalidType())
  12545. NewID->setInvalidDecl();
  12546. // In ARC, infer 'retaining' for ivars of retainable type.
  12547. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  12548. NewID->setInvalidDecl();
  12549. if (D.getDeclSpec().isModulePrivateSpecified())
  12550. NewID->setModulePrivate();
  12551. if (II) {
  12552. // FIXME: When interfaces are DeclContexts, we'll need to add
  12553. // these to the interface.
  12554. S->AddDecl(NewID);
  12555. IdResolver.AddDecl(NewID);
  12556. }
  12557. if (LangOpts.ObjCRuntime.isNonFragile() &&
  12558. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  12559. Diag(Loc, diag::warn_ivars_in_interface);
  12560. return NewID;
  12561. }
  12562. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  12563. /// class and class extensions. For every class \@interface and class
  12564. /// extension \@interface, if the last ivar is a bitfield of any type,
  12565. /// then add an implicit `char :0` ivar to the end of that interface.
  12566. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  12567. SmallVectorImpl<Decl *> &AllIvarDecls) {
  12568. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  12569. return;
  12570. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  12571. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  12572. if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
  12573. return;
  12574. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  12575. if (!ID) {
  12576. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  12577. if (!CD->IsClassExtension())
  12578. return;
  12579. }
  12580. // No need to add this to end of @implementation.
  12581. else
  12582. return;
  12583. }
  12584. // All conditions are met. Add a new bitfield to the tail end of ivars.
  12585. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  12586. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  12587. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  12588. DeclLoc, DeclLoc, nullptr,
  12589. Context.CharTy,
  12590. Context.getTrivialTypeSourceInfo(Context.CharTy,
  12591. DeclLoc),
  12592. ObjCIvarDecl::Private, BW,
  12593. true);
  12594. AllIvarDecls.push_back(Ivar);
  12595. }
  12596. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  12597. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  12598. SourceLocation RBrac, AttributeList *Attr) {
  12599. assert(EnclosingDecl && "missing record or interface decl");
  12600. // If this is an Objective-C @implementation or category and we have
  12601. // new fields here we should reset the layout of the interface since
  12602. // it will now change.
  12603. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  12604. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  12605. switch (DC->getKind()) {
  12606. default: break;
  12607. case Decl::ObjCCategory:
  12608. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  12609. break;
  12610. case Decl::ObjCImplementation:
  12611. Context.
  12612. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  12613. break;
  12614. }
  12615. }
  12616. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  12617. // Start counting up the number of named members; make sure to include
  12618. // members of anonymous structs and unions in the total.
  12619. unsigned NumNamedMembers = 0;
  12620. if (Record) {
  12621. for (const auto *I : Record->decls()) {
  12622. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  12623. if (IFD->getDeclName())
  12624. ++NumNamedMembers;
  12625. }
  12626. }
  12627. // Verify that all the fields are okay.
  12628. SmallVector<FieldDecl*, 32> RecFields;
  12629. bool ARCErrReported = false;
  12630. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  12631. i != end; ++i) {
  12632. FieldDecl *FD = cast<FieldDecl>(*i);
  12633. // Get the type for the field.
  12634. const Type *FDTy = FD->getType().getTypePtr();
  12635. if (!FD->isAnonymousStructOrUnion()) {
  12636. // Remember all fields written by the user.
  12637. RecFields.push_back(FD);
  12638. }
  12639. // If the field is already invalid for some reason, don't emit more
  12640. // diagnostics about it.
  12641. if (FD->isInvalidDecl()) {
  12642. EnclosingDecl->setInvalidDecl();
  12643. continue;
  12644. }
  12645. // C99 6.7.2.1p2:
  12646. // A structure or union shall not contain a member with
  12647. // incomplete or function type (hence, a structure shall not
  12648. // contain an instance of itself, but may contain a pointer to
  12649. // an instance of itself), except that the last member of a
  12650. // structure with more than one named member may have incomplete
  12651. // array type; such a structure (and any union containing,
  12652. // possibly recursively, a member that is such a structure)
  12653. // shall not be a member of a structure or an element of an
  12654. // array.
  12655. if (FDTy->isFunctionType()) {
  12656. // Field declared as a function.
  12657. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  12658. << FD->getDeclName();
  12659. FD->setInvalidDecl();
  12660. EnclosingDecl->setInvalidDecl();
  12661. continue;
  12662. } else if (FDTy->isIncompleteArrayType() && Record &&
  12663. ((i + 1 == Fields.end() && !Record->isUnion()) ||
  12664. ((getLangOpts().MicrosoftExt ||
  12665. getLangOpts().CPlusPlus) &&
  12666. (i + 1 == Fields.end() || Record->isUnion())))) {
  12667. // Flexible array member.
  12668. // Microsoft and g++ is more permissive regarding flexible array.
  12669. // It will accept flexible array in union and also
  12670. // as the sole element of a struct/class.
  12671. unsigned DiagID = 0;
  12672. if (Record->isUnion())
  12673. DiagID = getLangOpts().MicrosoftExt
  12674. ? diag::ext_flexible_array_union_ms
  12675. : getLangOpts().CPlusPlus
  12676. ? diag::ext_flexible_array_union_gnu
  12677. : diag::err_flexible_array_union;
  12678. else if (NumNamedMembers < 1)
  12679. DiagID = getLangOpts().MicrosoftExt
  12680. ? diag::ext_flexible_array_empty_aggregate_ms
  12681. : getLangOpts().CPlusPlus
  12682. ? diag::ext_flexible_array_empty_aggregate_gnu
  12683. : diag::err_flexible_array_empty_aggregate;
  12684. if (DiagID)
  12685. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  12686. << Record->getTagKind();
  12687. // While the layout of types that contain virtual bases is not specified
  12688. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  12689. // virtual bases after the derived members. This would make a flexible
  12690. // array member declared at the end of an object not adjacent to the end
  12691. // of the type.
  12692. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
  12693. if (RD->getNumVBases() != 0)
  12694. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  12695. << FD->getDeclName() << Record->getTagKind();
  12696. if (!getLangOpts().C99)
  12697. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  12698. << FD->getDeclName() << Record->getTagKind();
  12699. // If the element type has a non-trivial destructor, we would not
  12700. // implicitly destroy the elements, so disallow it for now.
  12701. //
  12702. // FIXME: GCC allows this. We should probably either implicitly delete
  12703. // the destructor of the containing class, or just allow this.
  12704. QualType BaseElem = Context.getBaseElementType(FD->getType());
  12705. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  12706. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  12707. << FD->getDeclName() << FD->getType();
  12708. FD->setInvalidDecl();
  12709. EnclosingDecl->setInvalidDecl();
  12710. continue;
  12711. }
  12712. // Okay, we have a legal flexible array member at the end of the struct.
  12713. Record->setHasFlexibleArrayMember(true);
  12714. } else if (!FDTy->isDependentType() &&
  12715. RequireCompleteType(FD->getLocation(), FD->getType(),
  12716. diag::err_field_incomplete)) {
  12717. // Incomplete type
  12718. FD->setInvalidDecl();
  12719. EnclosingDecl->setInvalidDecl();
  12720. continue;
  12721. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  12722. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  12723. // A type which contains a flexible array member is considered to be a
  12724. // flexible array member.
  12725. Record->setHasFlexibleArrayMember(true);
  12726. if (!Record->isUnion()) {
  12727. // If this is a struct/class and this is not the last element, reject
  12728. // it. Note that GCC supports variable sized arrays in the middle of
  12729. // structures.
  12730. if (i + 1 != Fields.end())
  12731. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  12732. << FD->getDeclName() << FD->getType();
  12733. else {
  12734. // We support flexible arrays at the end of structs in
  12735. // other structs as an extension.
  12736. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  12737. << FD->getDeclName();
  12738. }
  12739. }
  12740. }
  12741. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  12742. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  12743. diag::err_abstract_type_in_decl,
  12744. AbstractIvarType)) {
  12745. // Ivars can not have abstract class types
  12746. FD->setInvalidDecl();
  12747. }
  12748. if (Record && FDTTy->getDecl()->hasObjectMember())
  12749. Record->setHasObjectMember(true);
  12750. if (Record && FDTTy->getDecl()->hasVolatileMember())
  12751. Record->setHasVolatileMember(true);
  12752. } else if (FDTy->isObjCObjectType()) {
  12753. /// A field cannot be an Objective-c object
  12754. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  12755. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  12756. QualType T = Context.getObjCObjectPointerType(FD->getType());
  12757. FD->setType(T);
  12758. } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
  12759. (!getLangOpts().CPlusPlus || Record->isUnion())) {
  12760. // It's an error in ARC if a field has lifetime.
  12761. // We don't want to report this in a system header, though,
  12762. // so we just make the field unavailable.
  12763. // FIXME: that's really not sufficient; we need to make the type
  12764. // itself invalid to, say, initialize or copy.
  12765. QualType T = FD->getType();
  12766. Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
  12767. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
  12768. SourceLocation loc = FD->getLocation();
  12769. if (getSourceManager().isInSystemHeader(loc)) {
  12770. if (!FD->hasAttr<UnavailableAttr>()) {
  12771. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  12772. UnavailableAttr::IR_ARCFieldWithOwnership, loc));
  12773. }
  12774. } else {
  12775. Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
  12776. << T->isBlockPointerType() << Record->getTagKind();
  12777. }
  12778. ARCErrReported = true;
  12779. }
  12780. } else if (getLangOpts().ObjC1 &&
  12781. getLangOpts().getGC() != LangOptions::NonGC &&
  12782. Record && !Record->hasObjectMember()) {
  12783. if (FD->getType()->isObjCObjectPointerType() ||
  12784. FD->getType().isObjCGCStrong())
  12785. Record->setHasObjectMember(true);
  12786. else if (Context.getAsArrayType(FD->getType())) {
  12787. QualType BaseType = Context.getBaseElementType(FD->getType());
  12788. if (BaseType->isRecordType() &&
  12789. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  12790. Record->setHasObjectMember(true);
  12791. else if (BaseType->isObjCObjectPointerType() ||
  12792. BaseType.isObjCGCStrong())
  12793. Record->setHasObjectMember(true);
  12794. }
  12795. }
  12796. if (Record && FD->getType().isVolatileQualified())
  12797. Record->setHasVolatileMember(true);
  12798. // Keep track of the number of named members.
  12799. if (FD->getIdentifier())
  12800. ++NumNamedMembers;
  12801. }
  12802. // Okay, we successfully defined 'Record'.
  12803. if (Record) {
  12804. bool Completed = false;
  12805. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  12806. if (!CXXRecord->isInvalidDecl()) {
  12807. // Set access bits correctly on the directly-declared conversions.
  12808. for (CXXRecordDecl::conversion_iterator
  12809. I = CXXRecord->conversion_begin(),
  12810. E = CXXRecord->conversion_end(); I != E; ++I)
  12811. I.setAccess((*I)->getAccess());
  12812. }
  12813. if (!CXXRecord->isDependentType()) {
  12814. if (CXXRecord->hasUserDeclaredDestructor()) {
  12815. // Adjust user-defined destructor exception spec.
  12816. if (getLangOpts().CPlusPlus11)
  12817. AdjustDestructorExceptionSpec(CXXRecord,
  12818. CXXRecord->getDestructor());
  12819. }
  12820. if (!CXXRecord->isInvalidDecl()) {
  12821. // Add any implicitly-declared members to this class.
  12822. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  12823. // If we have virtual base classes, we may end up finding multiple
  12824. // final overriders for a given virtual function. Check for this
  12825. // problem now.
  12826. if (CXXRecord->getNumVBases()) {
  12827. CXXFinalOverriderMap FinalOverriders;
  12828. CXXRecord->getFinalOverriders(FinalOverriders);
  12829. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  12830. MEnd = FinalOverriders.end();
  12831. M != MEnd; ++M) {
  12832. for (OverridingMethods::iterator SO = M->second.begin(),
  12833. SOEnd = M->second.end();
  12834. SO != SOEnd; ++SO) {
  12835. assert(SO->second.size() > 0 &&
  12836. "Virtual function without overridding functions?");
  12837. if (SO->second.size() == 1)
  12838. continue;
  12839. // C++ [class.virtual]p2:
  12840. // In a derived class, if a virtual member function of a base
  12841. // class subobject has more than one final overrider the
  12842. // program is ill-formed.
  12843. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  12844. << (const NamedDecl *)M->first << Record;
  12845. Diag(M->first->getLocation(),
  12846. diag::note_overridden_virtual_function);
  12847. for (OverridingMethods::overriding_iterator
  12848. OM = SO->second.begin(),
  12849. OMEnd = SO->second.end();
  12850. OM != OMEnd; ++OM)
  12851. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  12852. << (const NamedDecl *)M->first << OM->Method->getParent();
  12853. Record->setInvalidDecl();
  12854. }
  12855. }
  12856. CXXRecord->completeDefinition(&FinalOverriders);
  12857. Completed = true;
  12858. }
  12859. }
  12860. }
  12861. }
  12862. if (!Completed)
  12863. Record->completeDefinition();
  12864. // We may have deferred checking for a deleted destructor. Check now.
  12865. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  12866. auto *Dtor = CXXRecord->getDestructor();
  12867. if (Dtor && Dtor->isImplicit() &&
  12868. ShouldDeleteSpecialMember(Dtor, CXXDestructor))
  12869. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  12870. }
  12871. if (Record->hasAttrs()) {
  12872. CheckAlignasUnderalignment(Record);
  12873. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  12874. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  12875. IA->getRange(), IA->getBestCase(),
  12876. IA->getSemanticSpelling());
  12877. }
  12878. // Check if the structure/union declaration is a type that can have zero
  12879. // size in C. For C this is a language extension, for C++ it may cause
  12880. // compatibility problems.
  12881. bool CheckForZeroSize;
  12882. if (!getLangOpts().CPlusPlus) {
  12883. CheckForZeroSize = true;
  12884. } else {
  12885. // For C++ filter out types that cannot be referenced in C code.
  12886. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  12887. CheckForZeroSize =
  12888. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  12889. !CXXRecord->isDependentType() &&
  12890. CXXRecord->isCLike();
  12891. }
  12892. if (CheckForZeroSize) {
  12893. bool ZeroSize = true;
  12894. bool IsEmpty = true;
  12895. unsigned NonBitFields = 0;
  12896. for (RecordDecl::field_iterator I = Record->field_begin(),
  12897. E = Record->field_end();
  12898. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  12899. IsEmpty = false;
  12900. if (I->isUnnamedBitfield()) {
  12901. if (I->getBitWidthValue(Context) > 0)
  12902. ZeroSize = false;
  12903. } else {
  12904. ++NonBitFields;
  12905. QualType FieldType = I->getType();
  12906. if (FieldType->isIncompleteType() ||
  12907. !Context.getTypeSizeInChars(FieldType).isZero())
  12908. ZeroSize = false;
  12909. }
  12910. }
  12911. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  12912. // allowed in C++, but warn if its declaration is inside
  12913. // extern "C" block.
  12914. if (ZeroSize) {
  12915. Diag(RecLoc, getLangOpts().CPlusPlus ?
  12916. diag::warn_zero_size_struct_union_in_extern_c :
  12917. diag::warn_zero_size_struct_union_compat)
  12918. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  12919. }
  12920. // Structs without named members are extension in C (C99 6.7.2.1p7),
  12921. // but are accepted by GCC.
  12922. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  12923. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  12924. diag::ext_no_named_members_in_struct_union)
  12925. << Record->isUnion();
  12926. }
  12927. }
  12928. } else {
  12929. ObjCIvarDecl **ClsFields =
  12930. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  12931. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  12932. ID->setEndOfDefinitionLoc(RBrac);
  12933. // Add ivar's to class's DeclContext.
  12934. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  12935. ClsFields[i]->setLexicalDeclContext(ID);
  12936. ID->addDecl(ClsFields[i]);
  12937. }
  12938. // Must enforce the rule that ivars in the base classes may not be
  12939. // duplicates.
  12940. if (ID->getSuperClass())
  12941. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  12942. } else if (ObjCImplementationDecl *IMPDecl =
  12943. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  12944. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  12945. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  12946. // Ivar declared in @implementation never belongs to the implementation.
  12947. // Only it is in implementation's lexical context.
  12948. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  12949. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  12950. IMPDecl->setIvarLBraceLoc(LBrac);
  12951. IMPDecl->setIvarRBraceLoc(RBrac);
  12952. } else if (ObjCCategoryDecl *CDecl =
  12953. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  12954. // case of ivars in class extension; all other cases have been
  12955. // reported as errors elsewhere.
  12956. // FIXME. Class extension does not have a LocEnd field.
  12957. // CDecl->setLocEnd(RBrac);
  12958. // Add ivar's to class extension's DeclContext.
  12959. // Diagnose redeclaration of private ivars.
  12960. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  12961. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  12962. if (IDecl) {
  12963. if (const ObjCIvarDecl *ClsIvar =
  12964. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  12965. Diag(ClsFields[i]->getLocation(),
  12966. diag::err_duplicate_ivar_declaration);
  12967. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  12968. continue;
  12969. }
  12970. for (const auto *Ext : IDecl->known_extensions()) {
  12971. if (const ObjCIvarDecl *ClsExtIvar
  12972. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  12973. Diag(ClsFields[i]->getLocation(),
  12974. diag::err_duplicate_ivar_declaration);
  12975. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  12976. continue;
  12977. }
  12978. }
  12979. }
  12980. ClsFields[i]->setLexicalDeclContext(CDecl);
  12981. CDecl->addDecl(ClsFields[i]);
  12982. }
  12983. CDecl->setIvarLBraceLoc(LBrac);
  12984. CDecl->setIvarRBraceLoc(RBrac);
  12985. }
  12986. }
  12987. if (Attr)
  12988. ProcessDeclAttributeList(S, Record, Attr);
  12989. }
  12990. /// \brief Determine whether the given integral value is representable within
  12991. /// the given type T.
  12992. static bool isRepresentableIntegerValue(ASTContext &Context,
  12993. llvm::APSInt &Value,
  12994. QualType T) {
  12995. assert(T->isIntegralType(Context) && "Integral type required!");
  12996. unsigned BitWidth = Context.getIntWidth(T);
  12997. if (Value.isUnsigned() || Value.isNonNegative()) {
  12998. if (T->isSignedIntegerOrEnumerationType())
  12999. --BitWidth;
  13000. return Value.getActiveBits() <= BitWidth;
  13001. }
  13002. return Value.getMinSignedBits() <= BitWidth;
  13003. }
  13004. // \brief Given an integral type, return the next larger integral type
  13005. // (or a NULL type of no such type exists).
  13006. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  13007. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  13008. // enum checking below.
  13009. assert(T->isIntegralType(Context) && "Integral type required!");
  13010. const unsigned NumTypes = 4;
  13011. QualType SignedIntegralTypes[NumTypes] = {
  13012. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  13013. };
  13014. QualType UnsignedIntegralTypes[NumTypes] = {
  13015. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  13016. Context.UnsignedLongLongTy
  13017. };
  13018. unsigned BitWidth = Context.getTypeSize(T);
  13019. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  13020. : UnsignedIntegralTypes;
  13021. for (unsigned I = 0; I != NumTypes; ++I)
  13022. if (Context.getTypeSize(Types[I]) > BitWidth)
  13023. return Types[I];
  13024. return QualType();
  13025. }
  13026. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  13027. EnumConstantDecl *LastEnumConst,
  13028. SourceLocation IdLoc,
  13029. IdentifierInfo *Id,
  13030. Expr *Val) {
  13031. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  13032. llvm::APSInt EnumVal(IntWidth);
  13033. QualType EltTy;
  13034. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  13035. Val = nullptr;
  13036. if (Val)
  13037. Val = DefaultLvalueConversion(Val).get();
  13038. if (Val) {
  13039. if (Enum->isDependentType() || Val->isTypeDependent())
  13040. EltTy = Context.DependentTy;
  13041. else {
  13042. SourceLocation ExpLoc;
  13043. if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
  13044. !getLangOpts().MSVCCompat) {
  13045. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  13046. // constant-expression in the enumerator-definition shall be a converted
  13047. // constant expression of the underlying type.
  13048. EltTy = Enum->getIntegerType();
  13049. ExprResult Converted =
  13050. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  13051. CCEK_Enumerator);
  13052. if (Converted.isInvalid())
  13053. Val = nullptr;
  13054. else
  13055. Val = Converted.get();
  13056. } else if (!Val->isValueDependent() &&
  13057. !(Val = VerifyIntegerConstantExpression(Val,
  13058. &EnumVal).get())) {
  13059. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  13060. } else {
  13061. if (Enum->isFixed()) {
  13062. EltTy = Enum->getIntegerType();
  13063. // In Obj-C and Microsoft mode, require the enumeration value to be
  13064. // representable in the underlying type of the enumeration. In C++11,
  13065. // we perform a non-narrowing conversion as part of converted constant
  13066. // expression checking.
  13067. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  13068. if (getLangOpts().MSVCCompat) {
  13069. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  13070. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  13071. } else
  13072. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  13073. } else
  13074. Val = ImpCastExprToType(Val, EltTy,
  13075. EltTy->isBooleanType() ?
  13076. CK_IntegralToBoolean : CK_IntegralCast)
  13077. .get();
  13078. } else if (getLangOpts().CPlusPlus) {
  13079. // C++11 [dcl.enum]p5:
  13080. // If the underlying type is not fixed, the type of each enumerator
  13081. // is the type of its initializing value:
  13082. // - If an initializer is specified for an enumerator, the
  13083. // initializing value has the same type as the expression.
  13084. EltTy = Val->getType();
  13085. } else {
  13086. // C99 6.7.2.2p2:
  13087. // The expression that defines the value of an enumeration constant
  13088. // shall be an integer constant expression that has a value
  13089. // representable as an int.
  13090. // Complain if the value is not representable in an int.
  13091. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  13092. Diag(IdLoc, diag::ext_enum_value_not_int)
  13093. << EnumVal.toString(10) << Val->getSourceRange()
  13094. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  13095. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  13096. // Force the type of the expression to 'int'.
  13097. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  13098. }
  13099. EltTy = Val->getType();
  13100. }
  13101. }
  13102. }
  13103. }
  13104. if (!Val) {
  13105. if (Enum->isDependentType())
  13106. EltTy = Context.DependentTy;
  13107. else if (!LastEnumConst) {
  13108. // C++0x [dcl.enum]p5:
  13109. // If the underlying type is not fixed, the type of each enumerator
  13110. // is the type of its initializing value:
  13111. // - If no initializer is specified for the first enumerator, the
  13112. // initializing value has an unspecified integral type.
  13113. //
  13114. // GCC uses 'int' for its unspecified integral type, as does
  13115. // C99 6.7.2.2p3.
  13116. if (Enum->isFixed()) {
  13117. EltTy = Enum->getIntegerType();
  13118. }
  13119. else {
  13120. EltTy = Context.IntTy;
  13121. }
  13122. } else {
  13123. // Assign the last value + 1.
  13124. EnumVal = LastEnumConst->getInitVal();
  13125. ++EnumVal;
  13126. EltTy = LastEnumConst->getType();
  13127. // Check for overflow on increment.
  13128. if (EnumVal < LastEnumConst->getInitVal()) {
  13129. // C++0x [dcl.enum]p5:
  13130. // If the underlying type is not fixed, the type of each enumerator
  13131. // is the type of its initializing value:
  13132. //
  13133. // - Otherwise the type of the initializing value is the same as
  13134. // the type of the initializing value of the preceding enumerator
  13135. // unless the incremented value is not representable in that type,
  13136. // in which case the type is an unspecified integral type
  13137. // sufficient to contain the incremented value. If no such type
  13138. // exists, the program is ill-formed.
  13139. QualType T = getNextLargerIntegralType(Context, EltTy);
  13140. if (T.isNull() || Enum->isFixed()) {
  13141. // There is no integral type larger enough to represent this
  13142. // value. Complain, then allow the value to wrap around.
  13143. EnumVal = LastEnumConst->getInitVal();
  13144. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  13145. ++EnumVal;
  13146. if (Enum->isFixed())
  13147. // When the underlying type is fixed, this is ill-formed.
  13148. Diag(IdLoc, diag::err_enumerator_wrapped)
  13149. << EnumVal.toString(10)
  13150. << EltTy;
  13151. else
  13152. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  13153. << EnumVal.toString(10);
  13154. } else {
  13155. EltTy = T;
  13156. }
  13157. // Retrieve the last enumerator's value, extent that type to the
  13158. // type that is supposed to be large enough to represent the incremented
  13159. // value, then increment.
  13160. EnumVal = LastEnumConst->getInitVal();
  13161. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  13162. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  13163. ++EnumVal;
  13164. // If we're not in C++, diagnose the overflow of enumerator values,
  13165. // which in C99 means that the enumerator value is not representable in
  13166. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  13167. // permits enumerator values that are representable in some larger
  13168. // integral type.
  13169. if (!getLangOpts().CPlusPlus && !T.isNull())
  13170. Diag(IdLoc, diag::warn_enum_value_overflow);
  13171. } else if (!getLangOpts().CPlusPlus &&
  13172. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  13173. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  13174. Diag(IdLoc, diag::ext_enum_value_not_int)
  13175. << EnumVal.toString(10) << 1;
  13176. }
  13177. }
  13178. }
  13179. if (!EltTy->isDependentType()) {
  13180. // Make the enumerator value match the signedness and size of the
  13181. // enumerator's type.
  13182. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  13183. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  13184. }
  13185. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  13186. Val, EnumVal);
  13187. }
  13188. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  13189. SourceLocation IILoc) {
  13190. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  13191. !getLangOpts().CPlusPlus)
  13192. return SkipBodyInfo();
  13193. // We have an anonymous enum definition. Look up the first enumerator to
  13194. // determine if we should merge the definition with an existing one and
  13195. // skip the body.
  13196. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  13197. ForRedeclaration);
  13198. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  13199. if (!PrevECD)
  13200. return SkipBodyInfo();
  13201. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  13202. NamedDecl *Hidden;
  13203. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  13204. SkipBodyInfo Skip;
  13205. Skip.Previous = Hidden;
  13206. return Skip;
  13207. }
  13208. return SkipBodyInfo();
  13209. }
  13210. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  13211. SourceLocation IdLoc, IdentifierInfo *Id,
  13212. AttributeList *Attr,
  13213. SourceLocation EqualLoc, Expr *Val) {
  13214. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  13215. EnumConstantDecl *LastEnumConst =
  13216. cast_or_null<EnumConstantDecl>(lastEnumConst);
  13217. // The scope passed in may not be a decl scope. Zip up the scope tree until
  13218. // we find one that is.
  13219. S = getNonFieldDeclScope(S);
  13220. // Verify that there isn't already something declared with this name in this
  13221. // scope.
  13222. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  13223. ForRedeclaration);
  13224. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13225. // Maybe we will complain about the shadowed template parameter.
  13226. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  13227. // Just pretend that we didn't see the previous declaration.
  13228. PrevDecl = nullptr;
  13229. }
  13230. // C++ [class.mem]p15:
  13231. // If T is the name of a class, then each of the following shall have a name
  13232. // different from T:
  13233. // - every enumerator of every member of class T that is an unscoped
  13234. // enumerated type
  13235. if (!TheEnumDecl->isScoped())
  13236. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  13237. DeclarationNameInfo(Id, IdLoc));
  13238. EnumConstantDecl *New =
  13239. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  13240. if (!New)
  13241. return nullptr;
  13242. if (PrevDecl) {
  13243. // When in C++, we may get a TagDecl with the same name; in this case the
  13244. // enum constant will 'hide' the tag.
  13245. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  13246. "Received TagDecl when not in C++!");
  13247. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
  13248. shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
  13249. if (isa<EnumConstantDecl>(PrevDecl))
  13250. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  13251. else
  13252. Diag(IdLoc, diag::err_redefinition) << Id;
  13253. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  13254. return nullptr;
  13255. }
  13256. }
  13257. // Process attributes.
  13258. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  13259. // Register this decl in the current scope stack.
  13260. New->setAccess(TheEnumDecl->getAccess());
  13261. PushOnScopeChains(New, S);
  13262. ActOnDocumentableDecl(New);
  13263. return New;
  13264. }
  13265. // Returns true when the enum initial expression does not trigger the
  13266. // duplicate enum warning. A few common cases are exempted as follows:
  13267. // Element2 = Element1
  13268. // Element2 = Element1 + 1
  13269. // Element2 = Element1 - 1
  13270. // Where Element2 and Element1 are from the same enum.
  13271. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  13272. Expr *InitExpr = ECD->getInitExpr();
  13273. if (!InitExpr)
  13274. return true;
  13275. InitExpr = InitExpr->IgnoreImpCasts();
  13276. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  13277. if (!BO->isAdditiveOp())
  13278. return true;
  13279. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  13280. if (!IL)
  13281. return true;
  13282. if (IL->getValue() != 1)
  13283. return true;
  13284. InitExpr = BO->getLHS();
  13285. }
  13286. // This checks if the elements are from the same enum.
  13287. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  13288. if (!DRE)
  13289. return true;
  13290. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  13291. if (!EnumConstant)
  13292. return true;
  13293. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  13294. Enum)
  13295. return true;
  13296. return false;
  13297. }
  13298. namespace {
  13299. struct DupKey {
  13300. int64_t val;
  13301. bool isTombstoneOrEmptyKey;
  13302. DupKey(int64_t val, bool isTombstoneOrEmptyKey)
  13303. : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
  13304. };
  13305. static DupKey GetDupKey(const llvm::APSInt& Val) {
  13306. return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
  13307. false);
  13308. }
  13309. struct DenseMapInfoDupKey {
  13310. static DupKey getEmptyKey() { return DupKey(0, true); }
  13311. static DupKey getTombstoneKey() { return DupKey(1, true); }
  13312. static unsigned getHashValue(const DupKey Key) {
  13313. return (unsigned)(Key.val * 37);
  13314. }
  13315. static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
  13316. return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
  13317. LHS.val == RHS.val;
  13318. }
  13319. };
  13320. } // end anonymous namespace
  13321. // Emits a warning when an element is implicitly set a value that
  13322. // a previous element has already been set to.
  13323. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  13324. EnumDecl *Enum,
  13325. QualType EnumType) {
  13326. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  13327. return;
  13328. // Avoid anonymous enums
  13329. if (!Enum->getIdentifier())
  13330. return;
  13331. // Only check for small enums.
  13332. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  13333. return;
  13334. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  13335. typedef SmallVector<ECDVector *, 3> DuplicatesVector;
  13336. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  13337. typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
  13338. ValueToVectorMap;
  13339. DuplicatesVector DupVector;
  13340. ValueToVectorMap EnumMap;
  13341. // Populate the EnumMap with all values represented by enum constants without
  13342. // an initialier.
  13343. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  13344. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  13345. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  13346. // this constant. Skip this enum since it may be ill-formed.
  13347. if (!ECD) {
  13348. return;
  13349. }
  13350. if (ECD->getInitExpr())
  13351. continue;
  13352. DupKey Key = GetDupKey(ECD->getInitVal());
  13353. DeclOrVector &Entry = EnumMap[Key];
  13354. // First time encountering this value.
  13355. if (Entry.isNull())
  13356. Entry = ECD;
  13357. }
  13358. // Create vectors for any values that has duplicates.
  13359. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  13360. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
  13361. if (!ValidDuplicateEnum(ECD, Enum))
  13362. continue;
  13363. DupKey Key = GetDupKey(ECD->getInitVal());
  13364. DeclOrVector& Entry = EnumMap[Key];
  13365. if (Entry.isNull())
  13366. continue;
  13367. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  13368. // Ensure constants are different.
  13369. if (D == ECD)
  13370. continue;
  13371. // Create new vector and push values onto it.
  13372. ECDVector *Vec = new ECDVector();
  13373. Vec->push_back(D);
  13374. Vec->push_back(ECD);
  13375. // Update entry to point to the duplicates vector.
  13376. Entry = Vec;
  13377. // Store the vector somewhere we can consult later for quick emission of
  13378. // diagnostics.
  13379. DupVector.push_back(Vec);
  13380. continue;
  13381. }
  13382. ECDVector *Vec = Entry.get<ECDVector*>();
  13383. // Make sure constants are not added more than once.
  13384. if (*Vec->begin() == ECD)
  13385. continue;
  13386. Vec->push_back(ECD);
  13387. }
  13388. // Emit diagnostics.
  13389. for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
  13390. DupVectorEnd = DupVector.end();
  13391. DupVectorIter != DupVectorEnd; ++DupVectorIter) {
  13392. ECDVector *Vec = *DupVectorIter;
  13393. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  13394. // Emit warning for one enum constant.
  13395. ECDVector::iterator I = Vec->begin();
  13396. S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
  13397. << (*I)->getName() << (*I)->getInitVal().toString(10)
  13398. << (*I)->getSourceRange();
  13399. ++I;
  13400. // Emit one note for each of the remaining enum constants with
  13401. // the same value.
  13402. for (ECDVector::iterator E = Vec->end(); I != E; ++I)
  13403. S.Diag((*I)->getLocation(), diag::note_duplicate_element)
  13404. << (*I)->getName() << (*I)->getInitVal().toString(10)
  13405. << (*I)->getSourceRange();
  13406. delete Vec;
  13407. }
  13408. }
  13409. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  13410. bool AllowMask) const {
  13411. assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
  13412. assert(ED->isCompleteDefinition() && "expected enum definition");
  13413. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  13414. llvm::APInt &FlagBits = R.first->second;
  13415. if (R.second) {
  13416. for (auto *E : ED->enumerators()) {
  13417. const auto &EVal = E->getInitVal();
  13418. // Only single-bit enumerators introduce new flag values.
  13419. if (EVal.isPowerOf2())
  13420. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  13421. }
  13422. }
  13423. // A value is in a flag enum if either its bits are a subset of the enum's
  13424. // flag bits (the first condition) or we are allowing masks and the same is
  13425. // true of its complement (the second condition). When masks are allowed, we
  13426. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  13427. //
  13428. // While it's true that any value could be used as a mask, the assumption is
  13429. // that a mask will have all of the insignificant bits set. Anything else is
  13430. // likely a logic error.
  13431. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  13432. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  13433. }
  13434. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  13435. Decl *EnumDeclX,
  13436. ArrayRef<Decl *> Elements,
  13437. Scope *S, AttributeList *Attr) {
  13438. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  13439. QualType EnumType = Context.getTypeDeclType(Enum);
  13440. if (Attr)
  13441. ProcessDeclAttributeList(S, Enum, Attr);
  13442. if (Enum->isDependentType()) {
  13443. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  13444. EnumConstantDecl *ECD =
  13445. cast_or_null<EnumConstantDecl>(Elements[i]);
  13446. if (!ECD) continue;
  13447. ECD->setType(EnumType);
  13448. }
  13449. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  13450. return;
  13451. }
  13452. // TODO: If the result value doesn't fit in an int, it must be a long or long
  13453. // long value. ISO C does not support this, but GCC does as an extension,
  13454. // emit a warning.
  13455. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  13456. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  13457. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  13458. // Verify that all the values are okay, compute the size of the values, and
  13459. // reverse the list.
  13460. unsigned NumNegativeBits = 0;
  13461. unsigned NumPositiveBits = 0;
  13462. // Keep track of whether all elements have type int.
  13463. bool AllElementsInt = true;
  13464. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  13465. EnumConstantDecl *ECD =
  13466. cast_or_null<EnumConstantDecl>(Elements[i]);
  13467. if (!ECD) continue; // Already issued a diagnostic.
  13468. const llvm::APSInt &InitVal = ECD->getInitVal();
  13469. // Keep track of the size of positive and negative values.
  13470. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  13471. NumPositiveBits = std::max(NumPositiveBits,
  13472. (unsigned)InitVal.getActiveBits());
  13473. else
  13474. NumNegativeBits = std::max(NumNegativeBits,
  13475. (unsigned)InitVal.getMinSignedBits());
  13476. // Keep track of whether every enum element has type int (very commmon).
  13477. if (AllElementsInt)
  13478. AllElementsInt = ECD->getType() == Context.IntTy;
  13479. }
  13480. // Figure out the type that should be used for this enum.
  13481. QualType BestType;
  13482. unsigned BestWidth;
  13483. // C++0x N3000 [conv.prom]p3:
  13484. // An rvalue of an unscoped enumeration type whose underlying
  13485. // type is not fixed can be converted to an rvalue of the first
  13486. // of the following types that can represent all the values of
  13487. // the enumeration: int, unsigned int, long int, unsigned long
  13488. // int, long long int, or unsigned long long int.
  13489. // C99 6.4.4.3p2:
  13490. // An identifier declared as an enumeration constant has type int.
  13491. // The C99 rule is modified by a gcc extension
  13492. QualType BestPromotionType;
  13493. bool Packed = Enum->hasAttr<PackedAttr>();
  13494. // -fshort-enums is the equivalent to specifying the packed attribute on all
  13495. // enum definitions.
  13496. if (LangOpts.ShortEnums)
  13497. Packed = true;
  13498. if (Enum->isFixed()) {
  13499. BestType = Enum->getIntegerType();
  13500. if (BestType->isPromotableIntegerType())
  13501. BestPromotionType = Context.getPromotedIntegerType(BestType);
  13502. else
  13503. BestPromotionType = BestType;
  13504. BestWidth = Context.getIntWidth(BestType);
  13505. }
  13506. else if (NumNegativeBits) {
  13507. // If there is a negative value, figure out the smallest integer type (of
  13508. // int/long/longlong) that fits.
  13509. // If it's packed, check also if it fits a char or a short.
  13510. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  13511. BestType = Context.SignedCharTy;
  13512. BestWidth = CharWidth;
  13513. } else if (Packed && NumNegativeBits <= ShortWidth &&
  13514. NumPositiveBits < ShortWidth) {
  13515. BestType = Context.ShortTy;
  13516. BestWidth = ShortWidth;
  13517. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  13518. BestType = Context.IntTy;
  13519. BestWidth = IntWidth;
  13520. } else {
  13521. BestWidth = Context.getTargetInfo().getLongWidth();
  13522. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  13523. BestType = Context.LongTy;
  13524. } else {
  13525. BestWidth = Context.getTargetInfo().getLongLongWidth();
  13526. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  13527. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  13528. BestType = Context.LongLongTy;
  13529. }
  13530. }
  13531. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  13532. } else {
  13533. // If there is no negative value, figure out the smallest type that fits
  13534. // all of the enumerator values.
  13535. // If it's packed, check also if it fits a char or a short.
  13536. if (Packed && NumPositiveBits <= CharWidth) {
  13537. BestType = Context.UnsignedCharTy;
  13538. BestPromotionType = Context.IntTy;
  13539. BestWidth = CharWidth;
  13540. } else if (Packed && NumPositiveBits <= ShortWidth) {
  13541. BestType = Context.UnsignedShortTy;
  13542. BestPromotionType = Context.IntTy;
  13543. BestWidth = ShortWidth;
  13544. } else if (NumPositiveBits <= IntWidth) {
  13545. BestType = Context.UnsignedIntTy;
  13546. BestWidth = IntWidth;
  13547. BestPromotionType
  13548. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  13549. ? Context.UnsignedIntTy : Context.IntTy;
  13550. } else if (NumPositiveBits <=
  13551. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  13552. BestType = Context.UnsignedLongTy;
  13553. BestPromotionType
  13554. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  13555. ? Context.UnsignedLongTy : Context.LongTy;
  13556. } else {
  13557. BestWidth = Context.getTargetInfo().getLongLongWidth();
  13558. assert(NumPositiveBits <= BestWidth &&
  13559. "How could an initializer get larger than ULL?");
  13560. BestType = Context.UnsignedLongLongTy;
  13561. BestPromotionType
  13562. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  13563. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  13564. }
  13565. }
  13566. // Loop over all of the enumerator constants, changing their types to match
  13567. // the type of the enum if needed.
  13568. for (auto *D : Elements) {
  13569. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  13570. if (!ECD) continue; // Already issued a diagnostic.
  13571. // Standard C says the enumerators have int type, but we allow, as an
  13572. // extension, the enumerators to be larger than int size. If each
  13573. // enumerator value fits in an int, type it as an int, otherwise type it the
  13574. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  13575. // that X has type 'int', not 'unsigned'.
  13576. // Determine whether the value fits into an int.
  13577. llvm::APSInt InitVal = ECD->getInitVal();
  13578. // If it fits into an integer type, force it. Otherwise force it to match
  13579. // the enum decl type.
  13580. QualType NewTy;
  13581. unsigned NewWidth;
  13582. bool NewSign;
  13583. if (!getLangOpts().CPlusPlus &&
  13584. !Enum->isFixed() &&
  13585. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  13586. NewTy = Context.IntTy;
  13587. NewWidth = IntWidth;
  13588. NewSign = true;
  13589. } else if (ECD->getType() == BestType) {
  13590. // Already the right type!
  13591. if (getLangOpts().CPlusPlus)
  13592. // C++ [dcl.enum]p4: Following the closing brace of an
  13593. // enum-specifier, each enumerator has the type of its
  13594. // enumeration.
  13595. ECD->setType(EnumType);
  13596. continue;
  13597. } else {
  13598. NewTy = BestType;
  13599. NewWidth = BestWidth;
  13600. NewSign = BestType->isSignedIntegerOrEnumerationType();
  13601. }
  13602. // Adjust the APSInt value.
  13603. InitVal = InitVal.extOrTrunc(NewWidth);
  13604. InitVal.setIsSigned(NewSign);
  13605. ECD->setInitVal(InitVal);
  13606. // Adjust the Expr initializer and type.
  13607. if (ECD->getInitExpr() &&
  13608. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  13609. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  13610. CK_IntegralCast,
  13611. ECD->getInitExpr(),
  13612. /*base paths*/ nullptr,
  13613. VK_RValue));
  13614. if (getLangOpts().CPlusPlus)
  13615. // C++ [dcl.enum]p4: Following the closing brace of an
  13616. // enum-specifier, each enumerator has the type of its
  13617. // enumeration.
  13618. ECD->setType(EnumType);
  13619. else
  13620. ECD->setType(NewTy);
  13621. }
  13622. Enum->completeDefinition(BestType, BestPromotionType,
  13623. NumPositiveBits, NumNegativeBits);
  13624. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  13625. if (Enum->hasAttr<FlagEnumAttr>()) {
  13626. for (Decl *D : Elements) {
  13627. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  13628. if (!ECD) continue; // Already issued a diagnostic.
  13629. llvm::APSInt InitVal = ECD->getInitVal();
  13630. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  13631. !IsValueInFlagEnum(Enum, InitVal, true))
  13632. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  13633. << ECD << Enum;
  13634. }
  13635. }
  13636. // Now that the enum type is defined, ensure it's not been underaligned.
  13637. if (Enum->hasAttrs())
  13638. CheckAlignasUnderalignment(Enum);
  13639. }
  13640. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  13641. SourceLocation StartLoc,
  13642. SourceLocation EndLoc) {
  13643. StringLiteral *AsmString = cast<StringLiteral>(expr);
  13644. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  13645. AsmString, StartLoc,
  13646. EndLoc);
  13647. CurContext->addDecl(New);
  13648. return New;
  13649. }
  13650. static void checkModuleImportContext(Sema &S, Module *M,
  13651. SourceLocation ImportLoc, DeclContext *DC,
  13652. bool FromInclude = false) {
  13653. SourceLocation ExternCLoc;
  13654. if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
  13655. switch (LSD->getLanguage()) {
  13656. case LinkageSpecDecl::lang_c:
  13657. if (ExternCLoc.isInvalid())
  13658. ExternCLoc = LSD->getLocStart();
  13659. break;
  13660. case LinkageSpecDecl::lang_cxx:
  13661. break;
  13662. }
  13663. DC = LSD->getParent();
  13664. }
  13665. while (isa<LinkageSpecDecl>(DC))
  13666. DC = DC->getParent();
  13667. if (!isa<TranslationUnitDecl>(DC)) {
  13668. S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
  13669. ? diag::ext_module_import_not_at_top_level_noop
  13670. : diag::err_module_import_not_at_top_level_fatal)
  13671. << M->getFullModuleName() << DC;
  13672. S.Diag(cast<Decl>(DC)->getLocStart(),
  13673. diag::note_module_import_not_at_top_level) << DC;
  13674. } else if (!M->IsExternC && ExternCLoc.isValid()) {
  13675. S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
  13676. << M->getFullModuleName();
  13677. S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
  13678. }
  13679. }
  13680. Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc,
  13681. ModuleDeclKind MDK,
  13682. ModuleIdPath Path) {
  13683. // 'module implementation' requires that we are not compiling a module of any
  13684. // kind. 'module' and 'module partition' require that we are compiling a
  13685. // module inteface (not a module map).
  13686. auto CMK = getLangOpts().getCompilingModule();
  13687. if (MDK == ModuleDeclKind::Implementation
  13688. ? CMK != LangOptions::CMK_None
  13689. : CMK != LangOptions::CMK_ModuleInterface) {
  13690. Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
  13691. << (unsigned)MDK;
  13692. return nullptr;
  13693. }
  13694. // FIXME: Create a ModuleDecl and return it.
  13695. // FIXME: Most of this work should be done by the preprocessor rather than
  13696. // here, in case we look ahead across something where the current
  13697. // module matters (eg a #include).
  13698. // The dots in a module name in the Modules TS are a lie. Unlike Clang's
  13699. // hierarchical module map modules, the dots here are just another character
  13700. // that can appear in a module name. Flatten down to the actual module name.
  13701. std::string ModuleName;
  13702. for (auto &Piece : Path) {
  13703. if (!ModuleName.empty())
  13704. ModuleName += ".";
  13705. ModuleName += Piece.first->getName();
  13706. }
  13707. // If a module name was explicitly specified on the command line, it must be
  13708. // correct.
  13709. if (!getLangOpts().CurrentModule.empty() &&
  13710. getLangOpts().CurrentModule != ModuleName) {
  13711. Diag(Path.front().second, diag::err_current_module_name_mismatch)
  13712. << SourceRange(Path.front().second, Path.back().second)
  13713. << getLangOpts().CurrentModule;
  13714. return nullptr;
  13715. }
  13716. const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
  13717. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  13718. switch (MDK) {
  13719. case ModuleDeclKind::Module: {
  13720. // FIXME: Check we're not in a submodule.
  13721. // We can't have imported a definition of this module or parsed a module
  13722. // map defining it already.
  13723. if (auto *M = Map.findModule(ModuleName)) {
  13724. Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
  13725. if (M->DefinitionLoc.isValid())
  13726. Diag(M->DefinitionLoc, diag::note_prev_module_definition);
  13727. else if (const auto *FE = M->getASTFile())
  13728. Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
  13729. << FE->getName();
  13730. return nullptr;
  13731. }
  13732. // Create a Module for the module that we're defining.
  13733. Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
  13734. assert(Mod && "module creation should not fail");
  13735. // Enter the semantic scope of the module.
  13736. ActOnModuleBegin(ModuleLoc, Mod);
  13737. return nullptr;
  13738. }
  13739. case ModuleDeclKind::Partition:
  13740. // FIXME: Check we are in a submodule of the named module.
  13741. return nullptr;
  13742. case ModuleDeclKind::Implementation:
  13743. std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
  13744. PP.getIdentifierInfo(ModuleName), Path[0].second);
  13745. DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
  13746. if (Import.isInvalid())
  13747. return nullptr;
  13748. return ConvertDeclToDeclGroup(Import.get());
  13749. }
  13750. llvm_unreachable("unexpected module decl kind");
  13751. }
  13752. DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
  13753. SourceLocation ImportLoc,
  13754. ModuleIdPath Path) {
  13755. Module *Mod =
  13756. getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
  13757. /*IsIncludeDirective=*/false);
  13758. if (!Mod)
  13759. return true;
  13760. VisibleModules.setVisible(Mod, ImportLoc);
  13761. checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
  13762. // FIXME: we should support importing a submodule within a different submodule
  13763. // of the same top-level module. Until we do, make it an error rather than
  13764. // silently ignoring the import.
  13765. // Import-from-implementation is valid in the Modules TS. FIXME: Should we
  13766. // warn on a redundant import of the current module?
  13767. if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  13768. (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
  13769. Diag(ImportLoc, getLangOpts().isCompilingModule()
  13770. ? diag::err_module_self_import
  13771. : diag::err_module_import_in_implementation)
  13772. << Mod->getFullModuleName() << getLangOpts().CurrentModule;
  13773. SmallVector<SourceLocation, 2> IdentifierLocs;
  13774. Module *ModCheck = Mod;
  13775. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  13776. // If we've run out of module parents, just drop the remaining identifiers.
  13777. // We need the length to be consistent.
  13778. if (!ModCheck)
  13779. break;
  13780. ModCheck = ModCheck->Parent;
  13781. IdentifierLocs.push_back(Path[I].second);
  13782. }
  13783. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  13784. ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
  13785. Mod, IdentifierLocs);
  13786. if (!ModuleScopes.empty())
  13787. Context.addModuleInitializer(ModuleScopes.back().Module, Import);
  13788. TU->addDecl(Import);
  13789. return Import;
  13790. }
  13791. void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  13792. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  13793. BuildModuleInclude(DirectiveLoc, Mod);
  13794. }
  13795. void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  13796. // Determine whether we're in the #include buffer for a module. The #includes
  13797. // in that buffer do not qualify as module imports; they're just an
  13798. // implementation detail of us building the module.
  13799. //
  13800. // FIXME: Should we even get ActOnModuleInclude calls for those?
  13801. bool IsInModuleIncludes =
  13802. TUKind == TU_Module &&
  13803. getSourceManager().isWrittenInMainFile(DirectiveLoc);
  13804. bool ShouldAddImport = !IsInModuleIncludes;
  13805. // If this module import was due to an inclusion directive, create an
  13806. // implicit import declaration to capture it in the AST.
  13807. if (ShouldAddImport) {
  13808. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  13809. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  13810. DirectiveLoc, Mod,
  13811. DirectiveLoc);
  13812. if (!ModuleScopes.empty())
  13813. Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
  13814. TU->addDecl(ImportD);
  13815. Consumer.HandleImplicitImportDecl(ImportD);
  13816. }
  13817. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
  13818. VisibleModules.setVisible(Mod, DirectiveLoc);
  13819. }
  13820. void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
  13821. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  13822. ModuleScopes.push_back({});
  13823. ModuleScopes.back().Module = Mod;
  13824. if (getLangOpts().ModulesLocalVisibility)
  13825. ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
  13826. VisibleModules.setVisible(Mod, DirectiveLoc);
  13827. }
  13828. void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
  13829. if (getLangOpts().ModulesLocalVisibility) {
  13830. VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
  13831. // Leaving a module hides namespace names, so our visible namespace cache
  13832. // is now out of date.
  13833. VisibleNamespaceCache.clear();
  13834. }
  13835. assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
  13836. "left the wrong module scope");
  13837. ModuleScopes.pop_back();
  13838. // We got to the end of processing a #include of a local module. Create an
  13839. // ImportDecl as we would for an imported module.
  13840. FileID File = getSourceManager().getFileID(EofLoc);
  13841. assert(File != getSourceManager().getMainFileID() &&
  13842. "end of submodule in main source file");
  13843. SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
  13844. BuildModuleInclude(DirectiveLoc, Mod);
  13845. }
  13846. void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
  13847. Module *Mod) {
  13848. // Bail if we're not allowed to implicitly import a module here.
  13849. if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
  13850. return;
  13851. // Create the implicit import declaration.
  13852. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  13853. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  13854. Loc, Mod, Loc);
  13855. TU->addDecl(ImportD);
  13856. Consumer.HandleImplicitImportDecl(ImportD);
  13857. // Make the module visible.
  13858. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
  13859. VisibleModules.setVisible(Mod, Loc);
  13860. }
  13861. /// We have parsed the start of an export declaration, including the '{'
  13862. /// (if present).
  13863. Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
  13864. SourceLocation LBraceLoc) {
  13865. ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
  13866. // C++ Modules TS draft:
  13867. // An export-declaration [...] shall not contain more than one
  13868. // export keyword.
  13869. //
  13870. // The intent here is that an export-declaration cannot appear within another
  13871. // export-declaration.
  13872. if (D->isExported())
  13873. Diag(ExportLoc, diag::err_export_within_export);
  13874. CurContext->addDecl(D);
  13875. PushDeclContext(S, D);
  13876. return D;
  13877. }
  13878. /// Complete the definition of an export declaration.
  13879. Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
  13880. auto *ED = cast<ExportDecl>(D);
  13881. if (RBraceLoc.isValid())
  13882. ED->setRBraceLoc(RBraceLoc);
  13883. // FIXME: Diagnose export of internal-linkage declaration (including
  13884. // anonymous namespace).
  13885. PopDeclContext();
  13886. return D;
  13887. }
  13888. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  13889. IdentifierInfo* AliasName,
  13890. SourceLocation PragmaLoc,
  13891. SourceLocation NameLoc,
  13892. SourceLocation AliasNameLoc) {
  13893. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  13894. LookupOrdinaryName);
  13895. AsmLabelAttr *Attr =
  13896. AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
  13897. // If a declaration that:
  13898. // 1) declares a function or a variable
  13899. // 2) has external linkage
  13900. // already exists, add a label attribute to it.
  13901. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  13902. if (isDeclExternC(PrevDecl))
  13903. PrevDecl->addAttr(Attr);
  13904. else
  13905. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  13906. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  13907. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  13908. } else
  13909. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  13910. }
  13911. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  13912. SourceLocation PragmaLoc,
  13913. SourceLocation NameLoc) {
  13914. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  13915. if (PrevDecl) {
  13916. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  13917. } else {
  13918. (void)WeakUndeclaredIdentifiers.insert(
  13919. std::pair<IdentifierInfo*,WeakInfo>
  13920. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  13921. }
  13922. }
  13923. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  13924. IdentifierInfo* AliasName,
  13925. SourceLocation PragmaLoc,
  13926. SourceLocation NameLoc,
  13927. SourceLocation AliasNameLoc) {
  13928. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  13929. LookupOrdinaryName);
  13930. WeakInfo W = WeakInfo(Name, NameLoc);
  13931. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  13932. if (!PrevDecl->hasAttr<AliasAttr>())
  13933. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  13934. DeclApplyPragmaWeak(TUScope, ND, W);
  13935. } else {
  13936. (void)WeakUndeclaredIdentifiers.insert(
  13937. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  13938. }
  13939. }
  13940. Decl *Sema::getObjCDeclContext() const {
  13941. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  13942. }