SemaDecl.cpp 619 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967
  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. AllowTemplates(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 = AllowTemplates && getAsTypeTemplateDecl(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 AllowTemplates;
  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. bool IsClassTemplateDeductionContext,
  234. IdentifierInfo **CorrectedII) {
  235. // FIXME: Consider allowing this outside C++1z mode as an extension.
  236. bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
  237. getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
  238. !isClassName && !HasTrailingDot;
  239. // Determine where we will perform name lookup.
  240. DeclContext *LookupCtx = nullptr;
  241. if (ObjectTypePtr) {
  242. QualType ObjectType = ObjectTypePtr.get();
  243. if (ObjectType->isRecordType())
  244. LookupCtx = computeDeclContext(ObjectType);
  245. } else if (SS && SS->isNotEmpty()) {
  246. LookupCtx = computeDeclContext(*SS, false);
  247. if (!LookupCtx) {
  248. if (isDependentScopeSpecifier(*SS)) {
  249. // C++ [temp.res]p3:
  250. // A qualified-id that refers to a type and in which the
  251. // nested-name-specifier depends on a template-parameter (14.6.2)
  252. // shall be prefixed by the keyword typename to indicate that the
  253. // qualified-id denotes a type, forming an
  254. // elaborated-type-specifier (7.1.5.3).
  255. //
  256. // We therefore do not perform any name lookup if the result would
  257. // refer to a member of an unknown specialization.
  258. if (!isClassName && !IsCtorOrDtorName)
  259. return nullptr;
  260. // We know from the grammar that this name refers to a type,
  261. // so build a dependent node to describe the type.
  262. if (WantNontrivialTypeSourceInfo)
  263. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  264. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  265. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  266. II, NameLoc);
  267. return ParsedType::make(T);
  268. }
  269. return nullptr;
  270. }
  271. if (!LookupCtx->isDependentContext() &&
  272. RequireCompleteDeclContext(*SS, LookupCtx))
  273. return nullptr;
  274. }
  275. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  276. // lookup for class-names.
  277. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  278. LookupOrdinaryName;
  279. LookupResult Result(*this, &II, NameLoc, Kind);
  280. if (LookupCtx) {
  281. // Perform "qualified" name lookup into the declaration context we
  282. // computed, which is either the type of the base of a member access
  283. // expression or the declaration context associated with a prior
  284. // nested-name-specifier.
  285. LookupQualifiedName(Result, LookupCtx);
  286. if (ObjectTypePtr && Result.empty()) {
  287. // C++ [basic.lookup.classref]p3:
  288. // If the unqualified-id is ~type-name, the type-name is looked up
  289. // in the context of the entire postfix-expression. If the type T of
  290. // the object expression is of a class type C, the type-name is also
  291. // looked up in the scope of class C. At least one of the lookups shall
  292. // find a name that refers to (possibly cv-qualified) T.
  293. LookupName(Result, S);
  294. }
  295. } else {
  296. // Perform unqualified name lookup.
  297. LookupName(Result, S);
  298. // For unqualified lookup in a class template in MSVC mode, look into
  299. // dependent base classes where the primary class template is known.
  300. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  301. if (ParsedType TypeInBase =
  302. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  303. return TypeInBase;
  304. }
  305. }
  306. NamedDecl *IIDecl = nullptr;
  307. switch (Result.getResultKind()) {
  308. case LookupResult::NotFound:
  309. case LookupResult::NotFoundInCurrentInstantiation:
  310. if (CorrectedII) {
  311. TypoCorrection Correction =
  312. CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
  313. llvm::make_unique<TypeNameValidatorCCC>(
  314. true, isClassName, AllowDeducedTemplate),
  315. CTK_ErrorRecovery);
  316. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  317. TemplateTy Template;
  318. bool MemberOfUnknownSpecialization;
  319. UnqualifiedId TemplateName;
  320. TemplateName.setIdentifier(NewII, NameLoc);
  321. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  322. CXXScopeSpec NewSS, *NewSSPtr = SS;
  323. if (SS && NNS) {
  324. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  325. NewSSPtr = &NewSS;
  326. }
  327. if (Correction && (NNS || NewII != &II) &&
  328. // Ignore a correction to a template type as the to-be-corrected
  329. // identifier is not a template (typo correction for template names
  330. // is handled elsewhere).
  331. !(getLangOpts().CPlusPlus && NewSSPtr &&
  332. isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
  333. Template, MemberOfUnknownSpecialization))) {
  334. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  335. isClassName, HasTrailingDot, ObjectTypePtr,
  336. IsCtorOrDtorName,
  337. WantNontrivialTypeSourceInfo,
  338. IsClassTemplateDeductionContext);
  339. if (Ty) {
  340. diagnoseTypo(Correction,
  341. PDiag(diag::err_unknown_type_or_class_name_suggest)
  342. << Result.getLookupName() << isClassName);
  343. if (SS && NNS)
  344. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  345. *CorrectedII = NewII;
  346. return Ty;
  347. }
  348. }
  349. }
  350. // If typo correction failed or was not performed, fall through
  351. case LookupResult::FoundOverloaded:
  352. case LookupResult::FoundUnresolvedValue:
  353. Result.suppressDiagnostics();
  354. return nullptr;
  355. case LookupResult::Ambiguous:
  356. // Recover from type-hiding ambiguities by hiding the type. We'll
  357. // do the lookup again when looking for an object, and we can
  358. // diagnose the error then. If we don't do this, then the error
  359. // about hiding the type will be immediately followed by an error
  360. // that only makes sense if the identifier was treated like a type.
  361. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  362. Result.suppressDiagnostics();
  363. return nullptr;
  364. }
  365. // Look to see if we have a type anywhere in the list of results.
  366. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  367. Res != ResEnd; ++Res) {
  368. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
  369. (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
  370. if (!IIDecl ||
  371. (*Res)->getLocation().getRawEncoding() <
  372. IIDecl->getLocation().getRawEncoding())
  373. IIDecl = *Res;
  374. }
  375. }
  376. if (!IIDecl) {
  377. // None of the entities we found is a type, so there is no way
  378. // to even assume that the result is a type. In this case, don't
  379. // complain about the ambiguity. The parser will either try to
  380. // perform this lookup again (e.g., as an object name), which
  381. // will produce the ambiguity, or will complain that it expected
  382. // a type name.
  383. Result.suppressDiagnostics();
  384. return nullptr;
  385. }
  386. // We found a type within the ambiguous lookup; diagnose the
  387. // ambiguity and then return that type. This might be the right
  388. // answer, or it might not be, but it suppresses any attempt to
  389. // perform the name lookup again.
  390. break;
  391. case LookupResult::Found:
  392. IIDecl = Result.getFoundDecl();
  393. break;
  394. }
  395. assert(IIDecl && "Didn't find decl");
  396. QualType T;
  397. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  398. // C++ [class.qual]p2: A lookup that would find the injected-class-name
  399. // instead names the constructors of the class, except when naming a class.
  400. // This is ill-formed when we're not actually forming a ctor or dtor name.
  401. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  402. auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
  403. if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
  404. FoundRD->isInjectedClassName() &&
  405. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  406. Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
  407. << &II << /*Type*/1;
  408. DiagnoseUseOfDecl(IIDecl, NameLoc);
  409. T = Context.getTypeDeclType(TD);
  410. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  411. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  412. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  413. if (!HasTrailingDot)
  414. T = Context.getObjCInterfaceType(IDecl);
  415. } else if (AllowDeducedTemplate) {
  416. if (auto *TD = getAsTypeTemplateDecl(IIDecl))
  417. T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  418. QualType(), false);
  419. }
  420. if (T.isNull()) {
  421. // If it's not plausibly a type, suppress diagnostics.
  422. Result.suppressDiagnostics();
  423. return nullptr;
  424. }
  425. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  426. // constructor or destructor name (in such a case, the scope specifier
  427. // will be attached to the enclosing Expr or Decl node).
  428. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
  429. !isa<ObjCInterfaceDecl>(IIDecl)) {
  430. if (WantNontrivialTypeSourceInfo) {
  431. // Construct a type with type-source information.
  432. TypeLocBuilder Builder;
  433. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  434. T = getElaboratedType(ETK_None, *SS, T);
  435. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  436. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  437. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  438. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  439. } else {
  440. T = getElaboratedType(ETK_None, *SS, T);
  441. }
  442. }
  443. return ParsedType::make(T);
  444. }
  445. // Builds a fake NNS for the given decl context.
  446. static NestedNameSpecifier *
  447. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  448. for (;; DC = DC->getLookupParent()) {
  449. DC = DC->getPrimaryContext();
  450. auto *ND = dyn_cast<NamespaceDecl>(DC);
  451. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  452. return NestedNameSpecifier::Create(Context, nullptr, ND);
  453. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  454. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  455. RD->getTypeForDecl());
  456. else if (isa<TranslationUnitDecl>(DC))
  457. return NestedNameSpecifier::GlobalSpecifier(Context);
  458. }
  459. llvm_unreachable("something isn't in TU scope?");
  460. }
  461. /// Find the parent class with dependent bases of the innermost enclosing method
  462. /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
  463. /// up allowing unqualified dependent type names at class-level, which MSVC
  464. /// correctly rejects.
  465. static const CXXRecordDecl *
  466. findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
  467. for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
  468. DC = DC->getPrimaryContext();
  469. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  470. if (MD->getParent()->hasAnyDependentBases())
  471. return MD->getParent();
  472. }
  473. return nullptr;
  474. }
  475. ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
  476. SourceLocation NameLoc,
  477. bool IsTemplateTypeArg) {
  478. assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
  479. NestedNameSpecifier *NNS = nullptr;
  480. if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
  481. // If we weren't able to parse a default template argument, delay lookup
  482. // until instantiation time by making a non-dependent DependentTypeName. We
  483. // pretend we saw a NestedNameSpecifier referring to the current scope, and
  484. // lookup is retried.
  485. // FIXME: This hurts our diagnostic quality, since we get errors like "no
  486. // type named 'Foo' in 'current_namespace'" when the user didn't write any
  487. // name specifiers.
  488. NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  489. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  490. } else if (const CXXRecordDecl *RD =
  491. findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
  492. // Build a DependentNameType that will perform lookup into RD at
  493. // instantiation time.
  494. NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  495. RD->getTypeForDecl());
  496. // Diagnose that this identifier was undeclared, and retry the lookup during
  497. // template instantiation.
  498. Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
  499. << RD;
  500. } else {
  501. // This is not a situation that we should recover from.
  502. return ParsedType();
  503. }
  504. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  505. // Build type location information. We synthesized the qualifier, so we have
  506. // to build a fake NestedNameSpecifierLoc.
  507. NestedNameSpecifierLocBuilder NNSLocBuilder;
  508. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  509. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  510. TypeLocBuilder Builder;
  511. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  512. DepTL.setNameLoc(NameLoc);
  513. DepTL.setElaboratedKeywordLoc(SourceLocation());
  514. DepTL.setQualifierLoc(QualifierLoc);
  515. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  516. }
  517. /// isTagName() - This method is called *for error recovery purposes only*
  518. /// to determine if the specified name is a valid tag name ("struct foo"). If
  519. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  520. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  521. /// cases in C where the user forgot to specify the tag.
  522. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  523. // Do a tag name lookup in this scope.
  524. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  525. LookupName(R, S, false);
  526. R.suppressDiagnostics();
  527. if (R.getResultKind() == LookupResult::Found)
  528. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  529. switch (TD->getTagKind()) {
  530. case TTK_Struct: return DeclSpec::TST_struct;
  531. case TTK_Interface: return DeclSpec::TST_interface;
  532. case TTK_Union: return DeclSpec::TST_union;
  533. case TTK_Class: return DeclSpec::TST_class;
  534. case TTK_Enum: return DeclSpec::TST_enum;
  535. }
  536. }
  537. return DeclSpec::TST_unspecified;
  538. }
  539. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  540. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  541. /// then downgrade the missing typename error to a warning.
  542. /// This is needed for MSVC compatibility; Example:
  543. /// @code
  544. /// template<class T> class A {
  545. /// public:
  546. /// typedef int TYPE;
  547. /// };
  548. /// template<class T> class B : public A<T> {
  549. /// public:
  550. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  551. /// };
  552. /// @endcode
  553. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  554. if (CurContext->isRecord()) {
  555. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  556. return true;
  557. const Type *Ty = SS->getScopeRep()->getAsType();
  558. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  559. for (const auto &Base : RD->bases())
  560. if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  561. return true;
  562. return S->isFunctionPrototypeScope();
  563. }
  564. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  565. }
  566. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  567. SourceLocation IILoc,
  568. Scope *S,
  569. CXXScopeSpec *SS,
  570. ParsedType &SuggestedType,
  571. bool AllowClassTemplates) {
  572. // We don't have anything to suggest (yet).
  573. SuggestedType = nullptr;
  574. // There may have been a typo in the name of the type. Look up typo
  575. // results, in case we have something that we can suggest.
  576. if (TypoCorrection Corrected =
  577. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  578. llvm::make_unique<TypeNameValidatorCCC>(
  579. false, false, AllowClassTemplates),
  580. CTK_ErrorRecovery)) {
  581. if (Corrected.isKeyword()) {
  582. // We corrected to a keyword.
  583. diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
  584. II = Corrected.getCorrectionAsIdentifierInfo();
  585. } else {
  586. // We found a similarly-named type or interface; suggest that.
  587. if (!SS || !SS->isSet()) {
  588. diagnoseTypo(Corrected,
  589. PDiag(diag::err_unknown_typename_suggest) << II);
  590. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  591. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  592. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  593. II->getName().equals(CorrectedStr);
  594. diagnoseTypo(Corrected,
  595. PDiag(diag::err_unknown_nested_typename_suggest)
  596. << II << DC << DroppedSpecifier << SS->getRange());
  597. } else {
  598. llvm_unreachable("could not have corrected a typo here");
  599. }
  600. CXXScopeSpec tmpSS;
  601. if (Corrected.getCorrectionSpecifier())
  602. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  603. SourceRange(IILoc));
  604. // FIXME: Support class template argument deduction here.
  605. SuggestedType =
  606. getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
  607. tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
  608. /*IsCtorOrDtorName=*/false,
  609. /*NonTrivialTypeSourceInfo=*/true);
  610. }
  611. return;
  612. }
  613. if (getLangOpts().CPlusPlus) {
  614. // See if II is a class template that the user forgot to pass arguments to.
  615. UnqualifiedId Name;
  616. Name.setIdentifier(II, IILoc);
  617. CXXScopeSpec EmptySS;
  618. TemplateTy TemplateResult;
  619. bool MemberOfUnknownSpecialization;
  620. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  621. Name, nullptr, true, TemplateResult,
  622. MemberOfUnknownSpecialization) == TNK_Type_template) {
  623. TemplateName TplName = TemplateResult.get();
  624. Diag(IILoc, diag::err_template_missing_args)
  625. << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
  626. if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
  627. Diag(TplDecl->getLocation(), diag::note_template_decl_here)
  628. << TplDecl->getTemplateParameters()->getSourceRange();
  629. }
  630. return;
  631. }
  632. }
  633. // FIXME: Should we move the logic that tries to recover from a missing tag
  634. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  635. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  636. Diag(IILoc, diag::err_unknown_typename) << II;
  637. else if (DeclContext *DC = computeDeclContext(*SS, false))
  638. Diag(IILoc, diag::err_typename_nested_not_found)
  639. << II << DC << SS->getRange();
  640. else if (isDependentScopeSpecifier(*SS)) {
  641. unsigned DiagID = diag::err_typename_missing;
  642. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  643. DiagID = diag::ext_typename_missing;
  644. Diag(SS->getRange().getBegin(), DiagID)
  645. << SS->getScopeRep() << II->getName()
  646. << SourceRange(SS->getRange().getBegin(), IILoc)
  647. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  648. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  649. *SS, *II, IILoc).get();
  650. } else {
  651. assert(SS && SS->isInvalid() &&
  652. "Invalid scope specifier has already been diagnosed");
  653. }
  654. }
  655. /// \brief Determine whether the given result set contains either a type name
  656. /// or
  657. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  658. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  659. NextToken.is(tok::less);
  660. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  661. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  662. return true;
  663. if (CheckTemplate && isa<TemplateDecl>(*I))
  664. return true;
  665. }
  666. return false;
  667. }
  668. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  669. Scope *S, CXXScopeSpec &SS,
  670. IdentifierInfo *&Name,
  671. SourceLocation NameLoc) {
  672. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  673. SemaRef.LookupParsedName(R, S, &SS);
  674. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  675. StringRef FixItTagName;
  676. switch (Tag->getTagKind()) {
  677. case TTK_Class:
  678. FixItTagName = "class ";
  679. break;
  680. case TTK_Enum:
  681. FixItTagName = "enum ";
  682. break;
  683. case TTK_Struct:
  684. FixItTagName = "struct ";
  685. break;
  686. case TTK_Interface:
  687. FixItTagName = "__interface ";
  688. break;
  689. case TTK_Union:
  690. FixItTagName = "union ";
  691. break;
  692. }
  693. StringRef TagName = FixItTagName.drop_back();
  694. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  695. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  696. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  697. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  698. I != IEnd; ++I)
  699. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  700. << Name << TagName;
  701. // Replace lookup results with just the tag decl.
  702. Result.clear(Sema::LookupTagName);
  703. SemaRef.LookupParsedName(Result, S, &SS);
  704. return true;
  705. }
  706. return false;
  707. }
  708. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  709. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  710. QualType T, SourceLocation NameLoc) {
  711. ASTContext &Context = S.Context;
  712. TypeLocBuilder Builder;
  713. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  714. T = S.getElaboratedType(ETK_None, SS, T);
  715. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  716. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  717. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  718. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  719. }
  720. Sema::NameClassification
  721. Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
  722. SourceLocation NameLoc, const Token &NextToken,
  723. bool IsAddressOfOperand,
  724. std::unique_ptr<CorrectionCandidateCallback> CCC) {
  725. DeclarationNameInfo NameInfo(Name, NameLoc);
  726. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  727. if (NextToken.is(tok::coloncolon)) {
  728. NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
  729. BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
  730. } else if (getLangOpts().CPlusPlus && SS.isSet() &&
  731. isCurrentClassName(*Name, S, &SS)) {
  732. // Per [class.qual]p2, this names the constructors of SS, not the
  733. // injected-class-name. We don't have a classification for that.
  734. // There's not much point caching this result, since the parser
  735. // will reject it later.
  736. return NameClassification::Unknown();
  737. }
  738. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  739. LookupParsedName(Result, S, &SS, !CurMethod);
  740. // For unqualified lookup in a class template in MSVC mode, look into
  741. // dependent base classes where the primary class template is known.
  742. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  743. if (ParsedType TypeInBase =
  744. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  745. return TypeInBase;
  746. }
  747. // Perform lookup for Objective-C instance variables (including automatically
  748. // synthesized instance variables), if we're in an Objective-C method.
  749. // FIXME: This lookup really, really needs to be folded in to the normal
  750. // unqualified lookup mechanism.
  751. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  752. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  753. if (E.get() || E.isInvalid())
  754. return E;
  755. }
  756. bool SecondTry = false;
  757. bool IsFilteredTemplateName = false;
  758. Corrected:
  759. switch (Result.getResultKind()) {
  760. case LookupResult::NotFound:
  761. // If an unqualified-id is followed by a '(', then we have a function
  762. // call.
  763. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  764. // In C++, this is an ADL-only call.
  765. // FIXME: Reference?
  766. if (getLangOpts().CPlusPlus)
  767. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  768. // C90 6.3.2.2:
  769. // If the expression that precedes the parenthesized argument list in a
  770. // function call consists solely of an identifier, and if no
  771. // declaration is visible for this identifier, the identifier is
  772. // implicitly declared exactly as if, in the innermost block containing
  773. // the function call, the declaration
  774. //
  775. // extern int identifier ();
  776. //
  777. // appeared.
  778. //
  779. // We also allow this in C99 as an extension.
  780. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  781. Result.addDecl(D);
  782. Result.resolveKind();
  783. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  784. }
  785. }
  786. // In C, we first see whether there is a tag type by the same name, in
  787. // which case it's likely that the user just forgot to write "enum",
  788. // "struct", or "union".
  789. if (!getLangOpts().CPlusPlus && !SecondTry &&
  790. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  791. break;
  792. }
  793. // Perform typo correction to determine if there is another name that is
  794. // close to this name.
  795. if (!SecondTry && CCC) {
  796. SecondTry = true;
  797. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  798. Result.getLookupKind(), S,
  799. &SS, std::move(CCC),
  800. CTK_ErrorRecovery)) {
  801. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  802. unsigned QualifiedDiag = diag::err_no_member_suggest;
  803. NamedDecl *FirstDecl = Corrected.getFoundDecl();
  804. NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
  805. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  806. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  807. UnqualifiedDiag = diag::err_no_template_suggest;
  808. QualifiedDiag = diag::err_no_member_template_suggest;
  809. } else if (UnderlyingFirstDecl &&
  810. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  811. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  812. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  813. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  814. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  815. }
  816. if (SS.isEmpty()) {
  817. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  818. } else {// FIXME: is this even reachable? Test it.
  819. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  820. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  821. Name->getName().equals(CorrectedStr);
  822. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  823. << Name << computeDeclContext(SS, false)
  824. << DroppedSpecifier << SS.getRange());
  825. }
  826. // Update the name, so that the caller has the new name.
  827. Name = Corrected.getCorrectionAsIdentifierInfo();
  828. // Typo correction corrected to a keyword.
  829. if (Corrected.isKeyword())
  830. return Name;
  831. // Also update the LookupResult...
  832. // FIXME: This should probably go away at some point
  833. Result.clear();
  834. Result.setLookupName(Corrected.getCorrection());
  835. if (FirstDecl)
  836. Result.addDecl(FirstDecl);
  837. // If we found an Objective-C instance variable, let
  838. // LookupInObjCMethod build the appropriate expression to
  839. // reference the ivar.
  840. // FIXME: This is a gross hack.
  841. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  842. Result.clear();
  843. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  844. return E;
  845. }
  846. goto Corrected;
  847. }
  848. }
  849. // We failed to correct; just fall through and let the parser deal with it.
  850. Result.suppressDiagnostics();
  851. return NameClassification::Unknown();
  852. case LookupResult::NotFoundInCurrentInstantiation: {
  853. // We performed name lookup into the current instantiation, and there were
  854. // dependent bases, so we treat this result the same way as any other
  855. // dependent nested-name-specifier.
  856. // C++ [temp.res]p2:
  857. // A name used in a template declaration or definition and that is
  858. // dependent on a template-parameter is assumed not to name a type
  859. // unless the applicable name lookup finds a type name or the name is
  860. // qualified by the keyword typename.
  861. //
  862. // FIXME: If the next token is '<', we might want to ask the parser to
  863. // perform some heroics to see if we actually have a
  864. // template-argument-list, which would indicate a missing 'template'
  865. // keyword here.
  866. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  867. NameInfo, IsAddressOfOperand,
  868. /*TemplateArgs=*/nullptr);
  869. }
  870. case LookupResult::Found:
  871. case LookupResult::FoundOverloaded:
  872. case LookupResult::FoundUnresolvedValue:
  873. break;
  874. case LookupResult::Ambiguous:
  875. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  876. hasAnyAcceptableTemplateNames(Result)) {
  877. // C++ [temp.local]p3:
  878. // A lookup that finds an injected-class-name (10.2) can result in an
  879. // ambiguity in certain cases (for example, if it is found in more than
  880. // one base class). If all of the injected-class-names that are found
  881. // refer to specializations of the same class template, and if the name
  882. // is followed by a template-argument-list, the reference refers to the
  883. // class template itself and not a specialization thereof, and is not
  884. // ambiguous.
  885. //
  886. // This filtering can make an ambiguous result into an unambiguous one,
  887. // so try again after filtering out template names.
  888. FilterAcceptableTemplateNames(Result);
  889. if (!Result.isAmbiguous()) {
  890. IsFilteredTemplateName = true;
  891. break;
  892. }
  893. }
  894. // Diagnose the ambiguity and return an error.
  895. return NameClassification::Error();
  896. }
  897. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  898. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  899. // C++ [temp.names]p3:
  900. // After name lookup (3.4) finds that a name is a template-name or that
  901. // an operator-function-id or a literal- operator-id refers to a set of
  902. // overloaded functions any member of which is a function template if
  903. // this is followed by a <, the < is always taken as the delimiter of a
  904. // template-argument-list and never as the less-than operator.
  905. if (!IsFilteredTemplateName)
  906. FilterAcceptableTemplateNames(Result);
  907. if (!Result.empty()) {
  908. bool IsFunctionTemplate;
  909. bool IsVarTemplate;
  910. TemplateName Template;
  911. if (Result.end() - Result.begin() > 1) {
  912. IsFunctionTemplate = true;
  913. Template = Context.getOverloadedTemplateName(Result.begin(),
  914. Result.end());
  915. } else {
  916. TemplateDecl *TD
  917. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  918. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  919. IsVarTemplate = isa<VarTemplateDecl>(TD);
  920. if (SS.isSet() && !SS.isInvalid())
  921. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  922. /*TemplateKeyword=*/false,
  923. TD);
  924. else
  925. Template = TemplateName(TD);
  926. }
  927. if (IsFunctionTemplate) {
  928. // Function templates always go through overload resolution, at which
  929. // point we'll perform the various checks (e.g., accessibility) we need
  930. // to based on which function we selected.
  931. Result.suppressDiagnostics();
  932. return NameClassification::FunctionTemplate(Template);
  933. }
  934. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  935. : NameClassification::TypeTemplate(Template);
  936. }
  937. }
  938. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  939. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  940. DiagnoseUseOfDecl(Type, NameLoc);
  941. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  942. QualType T = Context.getTypeDeclType(Type);
  943. if (SS.isNotEmpty())
  944. return buildNestedType(*this, SS, T, NameLoc);
  945. return ParsedType::make(T);
  946. }
  947. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  948. if (!Class) {
  949. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  950. if (ObjCCompatibleAliasDecl *Alias =
  951. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  952. Class = Alias->getClassInterface();
  953. }
  954. if (Class) {
  955. DiagnoseUseOfDecl(Class, NameLoc);
  956. if (NextToken.is(tok::period)) {
  957. // Interface. <something> is parsed as a property reference expression.
  958. // Just return "unknown" as a fall-through for now.
  959. Result.suppressDiagnostics();
  960. return NameClassification::Unknown();
  961. }
  962. QualType T = Context.getObjCInterfaceType(Class);
  963. return ParsedType::make(T);
  964. }
  965. // We can have a type template here if we're classifying a template argument.
  966. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
  967. !isa<VarTemplateDecl>(FirstDecl))
  968. return NameClassification::TypeTemplate(
  969. TemplateName(cast<TemplateDecl>(FirstDecl)));
  970. // Check for a tag type hidden by a non-type decl in a few cases where it
  971. // seems likely a type is wanted instead of the non-type that was found.
  972. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  973. if ((NextToken.is(tok::identifier) ||
  974. (NextIsOp &&
  975. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  976. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  977. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  978. DiagnoseUseOfDecl(Type, NameLoc);
  979. QualType T = Context.getTypeDeclType(Type);
  980. if (SS.isNotEmpty())
  981. return buildNestedType(*this, SS, T, NameLoc);
  982. return ParsedType::make(T);
  983. }
  984. if (FirstDecl->isCXXClassMember())
  985. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  986. nullptr, S);
  987. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  988. return BuildDeclarationNameExpr(SS, Result, ADL);
  989. }
  990. Sema::TemplateNameKindForDiagnostics
  991. Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
  992. auto *TD = Name.getAsTemplateDecl();
  993. if (!TD)
  994. return TemplateNameKindForDiagnostics::DependentTemplate;
  995. if (isa<ClassTemplateDecl>(TD))
  996. return TemplateNameKindForDiagnostics::ClassTemplate;
  997. if (isa<FunctionTemplateDecl>(TD))
  998. return TemplateNameKindForDiagnostics::FunctionTemplate;
  999. if (isa<VarTemplateDecl>(TD))
  1000. return TemplateNameKindForDiagnostics::VarTemplate;
  1001. if (isa<TypeAliasTemplateDecl>(TD))
  1002. return TemplateNameKindForDiagnostics::AliasTemplate;
  1003. if (isa<TemplateTemplateParmDecl>(TD))
  1004. return TemplateNameKindForDiagnostics::TemplateTemplateParam;
  1005. return TemplateNameKindForDiagnostics::DependentTemplate;
  1006. }
  1007. // Determines the context to return to after temporarily entering a
  1008. // context. This depends in an unnecessarily complicated way on the
  1009. // exact ordering of callbacks from the parser.
  1010. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  1011. // Functions defined inline within classes aren't parsed until we've
  1012. // finished parsing the top-level class, so the top-level class is
  1013. // the context we'll need to return to.
  1014. // A Lambda call operator whose parent is a class must not be treated
  1015. // as an inline member function. A Lambda can be used legally
  1016. // either as an in-class member initializer or a default argument. These
  1017. // are parsed once the class has been marked complete and so the containing
  1018. // context would be the nested class (when the lambda is defined in one);
  1019. // If the class is not complete, then the lambda is being used in an
  1020. // ill-formed fashion (such as to specify the width of a bit-field, or
  1021. // in an array-bound) - in which case we still want to return the
  1022. // lexically containing DC (which could be a nested class).
  1023. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  1024. DC = DC->getLexicalParent();
  1025. // A function not defined within a class will always return to its
  1026. // lexical context.
  1027. if (!isa<CXXRecordDecl>(DC))
  1028. return DC;
  1029. // A C++ inline method/friend is parsed *after* the topmost class
  1030. // it was declared in is fully parsed ("complete"); the topmost
  1031. // class is the context we need to return to.
  1032. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  1033. DC = RD;
  1034. // Return the declaration context of the topmost class the inline method is
  1035. // declared in.
  1036. return DC;
  1037. }
  1038. return DC->getLexicalParent();
  1039. }
  1040. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  1041. assert(getContainingDC(DC) == CurContext &&
  1042. "The next DeclContext should be lexically contained in the current one.");
  1043. CurContext = DC;
  1044. S->setEntity(DC);
  1045. }
  1046. void Sema::PopDeclContext() {
  1047. assert(CurContext && "DeclContext imbalance!");
  1048. CurContext = getContainingDC(CurContext);
  1049. assert(CurContext && "Popped translation unit!");
  1050. }
  1051. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  1052. Decl *D) {
  1053. // Unlike PushDeclContext, the context to which we return is not necessarily
  1054. // the containing DC of TD, because the new context will be some pre-existing
  1055. // TagDecl definition instead of a fresh one.
  1056. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  1057. CurContext = cast<TagDecl>(D)->getDefinition();
  1058. assert(CurContext && "skipping definition of undefined tag");
  1059. // Start lookups from the parent of the current context; we don't want to look
  1060. // into the pre-existing complete definition.
  1061. S->setEntity(CurContext->getLookupParent());
  1062. return Result;
  1063. }
  1064. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  1065. CurContext = static_cast<decltype(CurContext)>(Context);
  1066. }
  1067. /// EnterDeclaratorContext - Used when we must lookup names in the context
  1068. /// of a declarator's nested name specifier.
  1069. ///
  1070. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  1071. // C++0x [basic.lookup.unqual]p13:
  1072. // A name used in the definition of a static data member of class
  1073. // X (after the qualified-id of the static member) is looked up as
  1074. // if the name was used in a member function of X.
  1075. // C++0x [basic.lookup.unqual]p14:
  1076. // If a variable member of a namespace is defined outside of the
  1077. // scope of its namespace then any name used in the definition of
  1078. // the variable member (after the declarator-id) is looked up as
  1079. // if the definition of the variable member occurred in its
  1080. // namespace.
  1081. // Both of these imply that we should push a scope whose context
  1082. // is the semantic context of the declaration. We can't use
  1083. // PushDeclContext here because that context is not necessarily
  1084. // lexically contained in the current context. Fortunately,
  1085. // the containing scope should have the appropriate information.
  1086. assert(!S->getEntity() && "scope already has entity");
  1087. #ifndef NDEBUG
  1088. Scope *Ancestor = S->getParent();
  1089. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1090. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1091. #endif
  1092. CurContext = DC;
  1093. S->setEntity(DC);
  1094. }
  1095. void Sema::ExitDeclaratorContext(Scope *S) {
  1096. assert(S->getEntity() == CurContext && "Context imbalance!");
  1097. // Switch back to the lexical context. The safety of this is
  1098. // enforced by an assert in EnterDeclaratorContext.
  1099. Scope *Ancestor = S->getParent();
  1100. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1101. CurContext = Ancestor->getEntity();
  1102. // We don't need to do anything with the scope, which is going to
  1103. // disappear.
  1104. }
  1105. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1106. // We assume that the caller has already called
  1107. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1108. FunctionDecl *FD = D->getAsFunction();
  1109. if (!FD)
  1110. return;
  1111. // Same implementation as PushDeclContext, but enters the context
  1112. // from the lexical parent, rather than the top-level class.
  1113. assert(CurContext == FD->getLexicalParent() &&
  1114. "The next DeclContext should be lexically contained in the current one.");
  1115. CurContext = FD;
  1116. S->setEntity(CurContext);
  1117. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1118. ParmVarDecl *Param = FD->getParamDecl(P);
  1119. // If the parameter has an identifier, then add it to the scope
  1120. if (Param->getIdentifier()) {
  1121. S->AddDecl(Param);
  1122. IdResolver.AddDecl(Param);
  1123. }
  1124. }
  1125. }
  1126. void Sema::ActOnExitFunctionContext() {
  1127. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1128. // rather than the top-level class.
  1129. assert(CurContext && "DeclContext imbalance!");
  1130. CurContext = CurContext->getLexicalParent();
  1131. assert(CurContext && "Popped translation unit!");
  1132. }
  1133. /// \brief Determine whether we allow overloading of the function
  1134. /// PrevDecl with another declaration.
  1135. ///
  1136. /// This routine determines whether overloading is possible, not
  1137. /// whether some new function is actually an overload. It will return
  1138. /// true in C++ (where we can always provide overloads) or, as an
  1139. /// extension, in C when the previous function is already an
  1140. /// overloaded function declaration or has the "overloadable"
  1141. /// attribute.
  1142. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1143. ASTContext &Context) {
  1144. if (Context.getLangOpts().CPlusPlus)
  1145. return true;
  1146. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1147. return true;
  1148. return (Previous.getResultKind() == LookupResult::Found
  1149. && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
  1150. }
  1151. /// Add this decl to the scope shadowed decl chains.
  1152. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1153. // Move up the scope chain until we find the nearest enclosing
  1154. // non-transparent context. The declaration will be introduced into this
  1155. // scope.
  1156. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1157. S = S->getParent();
  1158. // Add scoped declarations into their context, so that they can be
  1159. // found later. Declarations without a context won't be inserted
  1160. // into any context.
  1161. if (AddToContext)
  1162. CurContext->addDecl(D);
  1163. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1164. // are function-local declarations.
  1165. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1166. !D->getDeclContext()->getRedeclContext()->Equals(
  1167. D->getLexicalDeclContext()->getRedeclContext()) &&
  1168. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1169. return;
  1170. // Template instantiations should also not be pushed into scope.
  1171. if (isa<FunctionDecl>(D) &&
  1172. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1173. return;
  1174. // If this replaces anything in the current scope,
  1175. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1176. IEnd = IdResolver.end();
  1177. for (; I != IEnd; ++I) {
  1178. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1179. S->RemoveDecl(*I);
  1180. IdResolver.RemoveDecl(*I);
  1181. // Should only need to replace one decl.
  1182. break;
  1183. }
  1184. }
  1185. S->AddDecl(D);
  1186. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1187. // Implicitly-generated labels may end up getting generated in an order that
  1188. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1189. // the label at the appropriate place in the identifier chain.
  1190. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1191. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1192. if (IDC == CurContext) {
  1193. if (!S->isDeclScope(*I))
  1194. continue;
  1195. } else if (IDC->Encloses(CurContext))
  1196. break;
  1197. }
  1198. IdResolver.InsertDeclAfter(I, D);
  1199. } else {
  1200. IdResolver.AddDecl(D);
  1201. }
  1202. }
  1203. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  1204. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  1205. TUScope->AddDecl(D);
  1206. }
  1207. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1208. bool AllowInlineNamespace) {
  1209. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1210. }
  1211. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1212. DeclContext *TargetDC = DC->getPrimaryContext();
  1213. do {
  1214. if (DeclContext *ScopeDC = S->getEntity())
  1215. if (ScopeDC->getPrimaryContext() == TargetDC)
  1216. return S;
  1217. } while ((S = S->getParent()));
  1218. return nullptr;
  1219. }
  1220. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1221. DeclContext*,
  1222. ASTContext&);
  1223. /// Filters out lookup results that don't fall within the given scope
  1224. /// as determined by isDeclInScope.
  1225. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1226. bool ConsiderLinkage,
  1227. bool AllowInlineNamespace) {
  1228. LookupResult::Filter F = R.makeFilter();
  1229. while (F.hasNext()) {
  1230. NamedDecl *D = F.next();
  1231. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1232. continue;
  1233. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1234. continue;
  1235. F.erase();
  1236. }
  1237. F.done();
  1238. }
  1239. static bool isUsingDecl(NamedDecl *D) {
  1240. return isa<UsingShadowDecl>(D) ||
  1241. isa<UnresolvedUsingTypenameDecl>(D) ||
  1242. isa<UnresolvedUsingValueDecl>(D);
  1243. }
  1244. /// Removes using shadow declarations from the lookup results.
  1245. static void RemoveUsingDecls(LookupResult &R) {
  1246. LookupResult::Filter F = R.makeFilter();
  1247. while (F.hasNext())
  1248. if (isUsingDecl(F.next()))
  1249. F.erase();
  1250. F.done();
  1251. }
  1252. /// \brief Check for this common pattern:
  1253. /// @code
  1254. /// class S {
  1255. /// S(const S&); // DO NOT IMPLEMENT
  1256. /// void operator=(const S&); // DO NOT IMPLEMENT
  1257. /// };
  1258. /// @endcode
  1259. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1260. // FIXME: Should check for private access too but access is set after we get
  1261. // the decl here.
  1262. if (D->doesThisDeclarationHaveABody())
  1263. return false;
  1264. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1265. return CD->isCopyConstructor();
  1266. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  1267. return Method->isCopyAssignmentOperator();
  1268. return false;
  1269. }
  1270. // We need this to handle
  1271. //
  1272. // typedef struct {
  1273. // void *foo() { return 0; }
  1274. // } A;
  1275. //
  1276. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1277. // for example. If 'A', foo will have external linkage. If we have '*A',
  1278. // foo will have no linkage. Since we can't know until we get to the end
  1279. // of the typedef, this function finds out if D might have non-external linkage.
  1280. // Callers should verify at the end of the TU if it D has external linkage or
  1281. // not.
  1282. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1283. const DeclContext *DC = D->getDeclContext();
  1284. while (!DC->isTranslationUnit()) {
  1285. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1286. if (!RD->hasNameForLinkage())
  1287. return true;
  1288. }
  1289. DC = DC->getParent();
  1290. }
  1291. return !D->isExternallyVisible();
  1292. }
  1293. // FIXME: This needs to be refactored; some other isInMainFile users want
  1294. // these semantics.
  1295. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1296. if (S.TUKind != TU_Complete)
  1297. return false;
  1298. return S.SourceMgr.isInMainFile(Loc);
  1299. }
  1300. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1301. assert(D);
  1302. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1303. return false;
  1304. // Ignore all entities declared within templates, and out-of-line definitions
  1305. // of members of class templates.
  1306. if (D->getDeclContext()->isDependentContext() ||
  1307. D->getLexicalDeclContext()->isDependentContext())
  1308. return false;
  1309. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1310. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1311. return false;
  1312. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1313. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1314. return false;
  1315. } else {
  1316. // 'static inline' functions are defined in headers; don't warn.
  1317. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1318. return false;
  1319. }
  1320. if (FD->doesThisDeclarationHaveABody() &&
  1321. Context.DeclMustBeEmitted(FD))
  1322. return false;
  1323. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1324. // Constants and utility variables are defined in headers with internal
  1325. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1326. // like "inline".)
  1327. if (!isMainFileLoc(*this, VD->getLocation()))
  1328. return false;
  1329. if (Context.DeclMustBeEmitted(VD))
  1330. return false;
  1331. if (VD->isStaticDataMember() &&
  1332. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1333. return false;
  1334. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1335. return false;
  1336. } else {
  1337. return false;
  1338. }
  1339. // Only warn for unused decls internal to the translation unit.
  1340. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1341. // for inline functions defined in the main source file, for instance.
  1342. return mightHaveNonExternalLinkage(D);
  1343. }
  1344. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1345. if (!D)
  1346. return;
  1347. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1348. const FunctionDecl *First = FD->getFirstDecl();
  1349. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1350. return; // First should already be in the vector.
  1351. }
  1352. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1353. const VarDecl *First = VD->getFirstDecl();
  1354. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1355. return; // First should already be in the vector.
  1356. }
  1357. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1358. UnusedFileScopedDecls.push_back(D);
  1359. }
  1360. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1361. if (D->isInvalidDecl())
  1362. return false;
  1363. if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
  1364. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1365. return false;
  1366. if (isa<LabelDecl>(D))
  1367. return true;
  1368. // Except for labels, we only care about unused decls that are local to
  1369. // functions.
  1370. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1371. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1372. // For dependent types, the diagnostic is deferred.
  1373. WithinFunction =
  1374. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1375. if (!WithinFunction)
  1376. return false;
  1377. if (isa<TypedefNameDecl>(D))
  1378. return true;
  1379. // White-list anything that isn't a local variable.
  1380. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1381. return false;
  1382. // Types of valid local variables should be complete, so this should succeed.
  1383. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1384. // White-list anything with an __attribute__((unused)) type.
  1385. const auto *Ty = VD->getType().getTypePtr();
  1386. // Only look at the outermost level of typedef.
  1387. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1388. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1389. return false;
  1390. }
  1391. // If we failed to complete the type for some reason, or if the type is
  1392. // dependent, don't diagnose the variable.
  1393. if (Ty->isIncompleteType() || Ty->isDependentType())
  1394. return false;
  1395. // Look at the element type to ensure that the warning behaviour is
  1396. // consistent for both scalars and arrays.
  1397. Ty = Ty->getBaseElementTypeUnsafe();
  1398. if (const TagType *TT = Ty->getAs<TagType>()) {
  1399. const TagDecl *Tag = TT->getDecl();
  1400. if (Tag->hasAttr<UnusedAttr>())
  1401. return false;
  1402. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1403. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1404. return false;
  1405. if (const Expr *Init = VD->getInit()) {
  1406. if (const ExprWithCleanups *Cleanups =
  1407. dyn_cast<ExprWithCleanups>(Init))
  1408. Init = Cleanups->getSubExpr();
  1409. const CXXConstructExpr *Construct =
  1410. dyn_cast<CXXConstructExpr>(Init);
  1411. if (Construct && !Construct->isElidable()) {
  1412. CXXConstructorDecl *CD = Construct->getConstructor();
  1413. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
  1414. return false;
  1415. }
  1416. }
  1417. }
  1418. }
  1419. // TODO: __attribute__((unused)) templates?
  1420. }
  1421. return true;
  1422. }
  1423. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1424. FixItHint &Hint) {
  1425. if (isa<LabelDecl>(D)) {
  1426. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1427. tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
  1428. if (AfterColon.isInvalid())
  1429. return;
  1430. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1431. getCharRange(D->getLocStart(), AfterColon));
  1432. }
  1433. }
  1434. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1435. if (D->getTypeForDecl()->isDependentType())
  1436. return;
  1437. for (auto *TmpD : D->decls()) {
  1438. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1439. DiagnoseUnusedDecl(T);
  1440. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1441. DiagnoseUnusedNestedTypedefs(R);
  1442. }
  1443. }
  1444. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1445. /// unless they are marked attr(unused).
  1446. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1447. if (!ShouldDiagnoseUnusedDecl(D))
  1448. return;
  1449. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1450. // typedefs can be referenced later on, so the diagnostics are emitted
  1451. // at end-of-translation-unit.
  1452. UnusedLocalTypedefNameCandidates.insert(TD);
  1453. return;
  1454. }
  1455. FixItHint Hint;
  1456. GenerateFixForUnusedDecl(D, Context, Hint);
  1457. unsigned DiagID;
  1458. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1459. DiagID = diag::warn_unused_exception_param;
  1460. else if (isa<LabelDecl>(D))
  1461. DiagID = diag::warn_unused_label;
  1462. else
  1463. DiagID = diag::warn_unused_variable;
  1464. Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
  1465. }
  1466. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1467. // Verify that we have no forward references left. If so, there was a goto
  1468. // or address of a label taken, but no definition of it. Label fwd
  1469. // definitions are indicated with a null substmt which is also not a resolved
  1470. // MS inline assembly label name.
  1471. bool Diagnose = false;
  1472. if (L->isMSAsmLabel())
  1473. Diagnose = !L->isResolvedMSAsmLabel();
  1474. else
  1475. Diagnose = L->getStmt() == nullptr;
  1476. if (Diagnose)
  1477. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1478. }
  1479. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1480. S->mergeNRVOIntoParent();
  1481. if (S->decl_empty()) return;
  1482. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1483. "Scope shouldn't contain decls!");
  1484. for (auto *TmpD : S->decls()) {
  1485. assert(TmpD && "This decl didn't get pushed??");
  1486. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1487. NamedDecl *D = cast<NamedDecl>(TmpD);
  1488. if (!D->getDeclName()) continue;
  1489. // Diagnose unused variables in this scope.
  1490. if (!S->hasUnrecoverableErrorOccurred()) {
  1491. DiagnoseUnusedDecl(D);
  1492. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1493. DiagnoseUnusedNestedTypedefs(RD);
  1494. }
  1495. // If this was a forward reference to a label, verify it was defined.
  1496. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1497. CheckPoppedLabel(LD, *this);
  1498. // Remove this name from our lexical scope, and warn on it if we haven't
  1499. // already.
  1500. IdResolver.RemoveDecl(D);
  1501. auto ShadowI = ShadowingDecls.find(D);
  1502. if (ShadowI != ShadowingDecls.end()) {
  1503. if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
  1504. Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
  1505. << D << FD << FD->getParent();
  1506. Diag(FD->getLocation(), diag::note_previous_declaration);
  1507. }
  1508. ShadowingDecls.erase(ShadowI);
  1509. }
  1510. }
  1511. }
  1512. /// \brief Look for an Objective-C class in the translation unit.
  1513. ///
  1514. /// \param Id The name of the Objective-C class we're looking for. If
  1515. /// typo-correction fixes this name, the Id will be updated
  1516. /// to the fixed name.
  1517. ///
  1518. /// \param IdLoc The location of the name in the translation unit.
  1519. ///
  1520. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1521. /// if there is no class with the given name.
  1522. ///
  1523. /// \returns The declaration of the named Objective-C class, or NULL if the
  1524. /// class could not be found.
  1525. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1526. SourceLocation IdLoc,
  1527. bool DoTypoCorrection) {
  1528. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1529. // creation from this context.
  1530. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1531. if (!IDecl && DoTypoCorrection) {
  1532. // Perform typo correction at the given location, but only if we
  1533. // find an Objective-C class name.
  1534. if (TypoCorrection C = CorrectTypo(
  1535. DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
  1536. llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
  1537. CTK_ErrorRecovery)) {
  1538. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1539. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1540. Id = IDecl->getIdentifier();
  1541. }
  1542. }
  1543. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1544. // This routine must always return a class definition, if any.
  1545. if (Def && Def->getDefinition())
  1546. Def = Def->getDefinition();
  1547. return Def;
  1548. }
  1549. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1550. /// from S, where a non-field would be declared. This routine copes
  1551. /// with the difference between C and C++ scoping rules in structs and
  1552. /// unions. For example, the following code is well-formed in C but
  1553. /// ill-formed in C++:
  1554. /// @code
  1555. /// struct S6 {
  1556. /// enum { BAR } e;
  1557. /// };
  1558. ///
  1559. /// void test_S6() {
  1560. /// struct S6 a;
  1561. /// a.e = BAR;
  1562. /// }
  1563. /// @endcode
  1564. /// For the declaration of BAR, this routine will return a different
  1565. /// scope. The scope S will be the scope of the unnamed enumeration
  1566. /// within S6. In C++, this routine will return the scope associated
  1567. /// with S6, because the enumeration's scope is a transparent
  1568. /// context but structures can contain non-field names. In C, this
  1569. /// routine will return the translation unit scope, since the
  1570. /// enumeration's scope is a transparent context and structures cannot
  1571. /// contain non-field names.
  1572. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1573. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1574. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1575. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1576. S = S->getParent();
  1577. return S;
  1578. }
  1579. /// \brief Looks up the declaration of "struct objc_super" and
  1580. /// saves it for later use in building builtin declaration of
  1581. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1582. /// pre-existing declaration exists no action takes place.
  1583. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1584. IdentifierInfo *II) {
  1585. if (!II->isStr("objc_msgSendSuper"))
  1586. return;
  1587. ASTContext &Context = ThisSema.Context;
  1588. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1589. SourceLocation(), Sema::LookupTagName);
  1590. ThisSema.LookupName(Result, S);
  1591. if (Result.getResultKind() == LookupResult::Found)
  1592. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1593. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1594. }
  1595. static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
  1596. switch (Error) {
  1597. case ASTContext::GE_None:
  1598. return "";
  1599. case ASTContext::GE_Missing_stdio:
  1600. return "stdio.h";
  1601. case ASTContext::GE_Missing_setjmp:
  1602. return "setjmp.h";
  1603. case ASTContext::GE_Missing_ucontext:
  1604. return "ucontext.h";
  1605. }
  1606. llvm_unreachable("unhandled error kind");
  1607. }
  1608. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1609. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1610. /// if we're creating this built-in in anticipation of redeclaring the
  1611. /// built-in.
  1612. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1613. Scope *S, bool ForRedeclaration,
  1614. SourceLocation Loc) {
  1615. LookupPredefedObjCSuperType(*this, S, II);
  1616. ASTContext::GetBuiltinTypeError Error;
  1617. QualType R = Context.GetBuiltinType(ID, Error);
  1618. if (Error) {
  1619. if (ForRedeclaration)
  1620. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1621. << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
  1622. return nullptr;
  1623. }
  1624. if (!ForRedeclaration &&
  1625. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1626. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1627. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1628. << Context.BuiltinInfo.getName(ID) << R;
  1629. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1630. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1631. Diag(Loc, diag::note_include_header_or_declare)
  1632. << Context.BuiltinInfo.getHeaderName(ID)
  1633. << Context.BuiltinInfo.getName(ID);
  1634. }
  1635. if (R.isNull())
  1636. return nullptr;
  1637. DeclContext *Parent = Context.getTranslationUnitDecl();
  1638. if (getLangOpts().CPlusPlus) {
  1639. LinkageSpecDecl *CLinkageDecl =
  1640. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1641. LinkageSpecDecl::lang_c, false);
  1642. CLinkageDecl->setImplicit();
  1643. Parent->addDecl(CLinkageDecl);
  1644. Parent = CLinkageDecl;
  1645. }
  1646. FunctionDecl *New = FunctionDecl::Create(Context,
  1647. Parent,
  1648. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1649. SC_Extern,
  1650. false,
  1651. R->isFunctionProtoType());
  1652. New->setImplicit();
  1653. // Create Decl objects for each parameter, adding them to the
  1654. // FunctionDecl.
  1655. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1656. SmallVector<ParmVarDecl*, 16> Params;
  1657. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1658. ParmVarDecl *parm =
  1659. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1660. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1661. SC_None, nullptr);
  1662. parm->setScopeInfo(0, i);
  1663. Params.push_back(parm);
  1664. }
  1665. New->setParams(Params);
  1666. }
  1667. AddKnownFunctionAttributes(New);
  1668. RegisterLocallyScopedExternCDecl(New, S);
  1669. // TUScope is the translation-unit scope to insert this function into.
  1670. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1671. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1672. // entirely, but we're not there yet.
  1673. DeclContext *SavedContext = CurContext;
  1674. CurContext = Parent;
  1675. PushOnScopeChains(New, TUScope);
  1676. CurContext = SavedContext;
  1677. return New;
  1678. }
  1679. /// Typedef declarations don't have linkage, but they still denote the same
  1680. /// entity if their types are the same.
  1681. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1682. /// isSameEntity.
  1683. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1684. TypedefNameDecl *Decl,
  1685. LookupResult &Previous) {
  1686. // This is only interesting when modules are enabled.
  1687. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1688. return;
  1689. // Empty sets are uninteresting.
  1690. if (Previous.empty())
  1691. return;
  1692. LookupResult::Filter Filter = Previous.makeFilter();
  1693. while (Filter.hasNext()) {
  1694. NamedDecl *Old = Filter.next();
  1695. // Non-hidden declarations are never ignored.
  1696. if (S.isVisible(Old))
  1697. continue;
  1698. // Declarations of the same entity are not ignored, even if they have
  1699. // different linkages.
  1700. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1701. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1702. Decl->getUnderlyingType()))
  1703. continue;
  1704. // If both declarations give a tag declaration a typedef name for linkage
  1705. // purposes, then they declare the same entity.
  1706. if (S.getLangOpts().CPlusPlus &&
  1707. OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1708. Decl->getAnonDeclWithTypedefName())
  1709. continue;
  1710. }
  1711. Filter.erase();
  1712. }
  1713. Filter.done();
  1714. }
  1715. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1716. QualType OldType;
  1717. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1718. OldType = OldTypedef->getUnderlyingType();
  1719. else
  1720. OldType = Context.getTypeDeclType(Old);
  1721. QualType NewType = New->getUnderlyingType();
  1722. if (NewType->isVariablyModifiedType()) {
  1723. // Must not redefine a typedef with a variably-modified type.
  1724. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1725. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1726. << Kind << NewType;
  1727. if (Old->getLocation().isValid())
  1728. Diag(Old->getLocation(), diag::note_previous_definition);
  1729. New->setInvalidDecl();
  1730. return true;
  1731. }
  1732. if (OldType != NewType &&
  1733. !OldType->isDependentType() &&
  1734. !NewType->isDependentType() &&
  1735. !Context.hasSameType(OldType, NewType)) {
  1736. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1737. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1738. << Kind << NewType << OldType;
  1739. if (Old->getLocation().isValid())
  1740. Diag(Old->getLocation(), diag::note_previous_definition);
  1741. New->setInvalidDecl();
  1742. return true;
  1743. }
  1744. return false;
  1745. }
  1746. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1747. /// same name and scope as a previous declaration 'Old'. Figure out
  1748. /// how to resolve this situation, merging decls or emitting
  1749. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1750. ///
  1751. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  1752. LookupResult &OldDecls) {
  1753. // If the new decl is known invalid already, don't bother doing any
  1754. // merging checks.
  1755. if (New->isInvalidDecl()) return;
  1756. // Allow multiple definitions for ObjC built-in typedefs.
  1757. // FIXME: Verify the underlying types are equivalent!
  1758. if (getLangOpts().ObjC1) {
  1759. const IdentifierInfo *TypeID = New->getIdentifier();
  1760. switch (TypeID->getLength()) {
  1761. default: break;
  1762. case 2:
  1763. {
  1764. if (!TypeID->isStr("id"))
  1765. break;
  1766. QualType T = New->getUnderlyingType();
  1767. if (!T->isPointerType())
  1768. break;
  1769. if (!T->isVoidPointerType()) {
  1770. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1771. if (!PT->isStructureType())
  1772. break;
  1773. }
  1774. Context.setObjCIdRedefinitionType(T);
  1775. // Install the built-in type for 'id', ignoring the current definition.
  1776. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1777. return;
  1778. }
  1779. case 5:
  1780. if (!TypeID->isStr("Class"))
  1781. break;
  1782. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1783. // Install the built-in type for 'Class', ignoring the current definition.
  1784. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1785. return;
  1786. case 3:
  1787. if (!TypeID->isStr("SEL"))
  1788. break;
  1789. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1790. // Install the built-in type for 'SEL', ignoring the current definition.
  1791. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1792. return;
  1793. }
  1794. // Fall through - the typedef name was not a builtin type.
  1795. }
  1796. // Verify the old decl was also a type.
  1797. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1798. if (!Old) {
  1799. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1800. << New->getDeclName();
  1801. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1802. if (OldD->getLocation().isValid())
  1803. Diag(OldD->getLocation(), diag::note_previous_definition);
  1804. return New->setInvalidDecl();
  1805. }
  1806. // If the old declaration is invalid, just give up here.
  1807. if (Old->isInvalidDecl())
  1808. return New->setInvalidDecl();
  1809. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1810. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1811. auto *NewTag = New->getAnonDeclWithTypedefName();
  1812. NamedDecl *Hidden = nullptr;
  1813. if (getLangOpts().CPlusPlus && OldTag && NewTag &&
  1814. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1815. !hasVisibleDefinition(OldTag, &Hidden)) {
  1816. // There is a definition of this tag, but it is not visible. Use it
  1817. // instead of our tag.
  1818. New->setTypeForDecl(OldTD->getTypeForDecl());
  1819. if (OldTD->isModed())
  1820. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1821. OldTD->getUnderlyingType());
  1822. else
  1823. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1824. // Make the old tag definition visible.
  1825. makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
  1826. // If this was an unscoped enumeration, yank all of its enumerators
  1827. // out of the scope.
  1828. if (isa<EnumDecl>(NewTag)) {
  1829. Scope *EnumScope = getNonFieldDeclScope(S);
  1830. for (auto *D : NewTag->decls()) {
  1831. auto *ED = cast<EnumConstantDecl>(D);
  1832. assert(EnumScope->isDeclScope(ED));
  1833. EnumScope->RemoveDecl(ED);
  1834. IdResolver.RemoveDecl(ED);
  1835. ED->getLexicalDeclContext()->removeDecl(ED);
  1836. }
  1837. }
  1838. }
  1839. }
  1840. // If the typedef types are not identical, reject them in all languages and
  1841. // with any extensions enabled.
  1842. if (isIncompatibleTypedef(Old, New))
  1843. return;
  1844. // The types match. Link up the redeclaration chain and merge attributes if
  1845. // the old declaration was a typedef.
  1846. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1847. New->setPreviousDecl(Typedef);
  1848. mergeDeclAttributes(New, Old);
  1849. }
  1850. if (getLangOpts().MicrosoftExt)
  1851. return;
  1852. if (getLangOpts().CPlusPlus) {
  1853. // C++ [dcl.typedef]p2:
  1854. // In a given non-class scope, a typedef specifier can be used to
  1855. // redefine the name of any type declared in that scope to refer
  1856. // to the type to which it already refers.
  1857. if (!isa<CXXRecordDecl>(CurContext))
  1858. return;
  1859. // C++0x [dcl.typedef]p4:
  1860. // In a given class scope, a typedef specifier can be used to redefine
  1861. // any class-name declared in that scope that is not also a typedef-name
  1862. // to refer to the type to which it already refers.
  1863. //
  1864. // This wording came in via DR424, which was a correction to the
  1865. // wording in DR56, which accidentally banned code like:
  1866. //
  1867. // struct S {
  1868. // typedef struct A { } A;
  1869. // };
  1870. //
  1871. // in the C++03 standard. We implement the C++0x semantics, which
  1872. // allow the above but disallow
  1873. //
  1874. // struct S {
  1875. // typedef int I;
  1876. // typedef int I;
  1877. // };
  1878. //
  1879. // since that was the intent of DR56.
  1880. if (!isa<TypedefNameDecl>(Old))
  1881. return;
  1882. Diag(New->getLocation(), diag::err_redefinition)
  1883. << New->getDeclName();
  1884. Diag(Old->getLocation(), diag::note_previous_definition);
  1885. return New->setInvalidDecl();
  1886. }
  1887. // Modules always permit redefinition of typedefs, as does C11.
  1888. if (getLangOpts().Modules || getLangOpts().C11)
  1889. return;
  1890. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1891. // is normally mapped to an error, but can be controlled with
  1892. // -Wtypedef-redefinition. If either the original or the redefinition is
  1893. // in a system header, don't emit this for compatibility with GCC.
  1894. if (getDiagnostics().getSuppressSystemWarnings() &&
  1895. (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1896. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1897. return;
  1898. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  1899. << New->getDeclName();
  1900. Diag(Old->getLocation(), diag::note_previous_definition);
  1901. }
  1902. /// DeclhasAttr - returns true if decl Declaration already has the target
  1903. /// attribute.
  1904. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  1905. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  1906. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  1907. for (const auto *i : D->attrs())
  1908. if (i->getKind() == A->getKind()) {
  1909. if (Ann) {
  1910. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  1911. return true;
  1912. continue;
  1913. }
  1914. // FIXME: Don't hardcode this check
  1915. if (OA && isa<OwnershipAttr>(i))
  1916. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  1917. return true;
  1918. }
  1919. return false;
  1920. }
  1921. static bool isAttributeTargetADefinition(Decl *D) {
  1922. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  1923. return VD->isThisDeclarationADefinition();
  1924. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  1925. return TD->isCompleteDefinition() || TD->isBeingDefined();
  1926. return true;
  1927. }
  1928. /// Merge alignment attributes from \p Old to \p New, taking into account the
  1929. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  1930. ///
  1931. /// \return \c true if any attributes were added to \p New.
  1932. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  1933. // Look for alignas attributes on Old, and pick out whichever attribute
  1934. // specifies the strictest alignment requirement.
  1935. AlignedAttr *OldAlignasAttr = nullptr;
  1936. AlignedAttr *OldStrictestAlignAttr = nullptr;
  1937. unsigned OldAlign = 0;
  1938. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  1939. // FIXME: We have no way of representing inherited dependent alignments
  1940. // in a case like:
  1941. // template<int A, int B> struct alignas(A) X;
  1942. // template<int A, int B> struct alignas(B) X {};
  1943. // For now, we just ignore any alignas attributes which are not on the
  1944. // definition in such a case.
  1945. if (I->isAlignmentDependent())
  1946. return false;
  1947. if (I->isAlignas())
  1948. OldAlignasAttr = I;
  1949. unsigned Align = I->getAlignment(S.Context);
  1950. if (Align > OldAlign) {
  1951. OldAlign = Align;
  1952. OldStrictestAlignAttr = I;
  1953. }
  1954. }
  1955. // Look for alignas attributes on New.
  1956. AlignedAttr *NewAlignasAttr = nullptr;
  1957. unsigned NewAlign = 0;
  1958. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  1959. if (I->isAlignmentDependent())
  1960. return false;
  1961. if (I->isAlignas())
  1962. NewAlignasAttr = I;
  1963. unsigned Align = I->getAlignment(S.Context);
  1964. if (Align > NewAlign)
  1965. NewAlign = Align;
  1966. }
  1967. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  1968. // Both declarations have 'alignas' attributes. We require them to match.
  1969. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  1970. // fall short. (If two declarations both have alignas, they must both match
  1971. // every definition, and so must match each other if there is a definition.)
  1972. // If either declaration only contains 'alignas(0)' specifiers, then it
  1973. // specifies the natural alignment for the type.
  1974. if (OldAlign == 0 || NewAlign == 0) {
  1975. QualType Ty;
  1976. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  1977. Ty = VD->getType();
  1978. else
  1979. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  1980. if (OldAlign == 0)
  1981. OldAlign = S.Context.getTypeAlign(Ty);
  1982. if (NewAlign == 0)
  1983. NewAlign = S.Context.getTypeAlign(Ty);
  1984. }
  1985. if (OldAlign != NewAlign) {
  1986. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  1987. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  1988. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  1989. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  1990. }
  1991. }
  1992. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  1993. // C++11 [dcl.align]p6:
  1994. // if any declaration of an entity has an alignment-specifier,
  1995. // every defining declaration of that entity shall specify an
  1996. // equivalent alignment.
  1997. // C11 6.7.5/7:
  1998. // If the definition of an object does not have an alignment
  1999. // specifier, any other declaration of that object shall also
  2000. // have no alignment specifier.
  2001. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2002. << OldAlignasAttr;
  2003. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2004. << OldAlignasAttr;
  2005. }
  2006. bool AnyAdded = false;
  2007. // Ensure we have an attribute representing the strictest alignment.
  2008. if (OldAlign > NewAlign) {
  2009. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2010. Clone->setInherited(true);
  2011. New->addAttr(Clone);
  2012. AnyAdded = true;
  2013. }
  2014. // Ensure we have an alignas attribute if the old declaration had one.
  2015. if (OldAlignasAttr && !NewAlignasAttr &&
  2016. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2017. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2018. Clone->setInherited(true);
  2019. New->addAttr(Clone);
  2020. AnyAdded = true;
  2021. }
  2022. return AnyAdded;
  2023. }
  2024. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2025. const InheritableAttr *Attr,
  2026. Sema::AvailabilityMergeKind AMK) {
  2027. // This function copies an attribute Attr from a previous declaration to the
  2028. // new declaration D if the new declaration doesn't itself have that attribute
  2029. // yet or if that attribute allows duplicates.
  2030. // If you're adding a new attribute that requires logic different from
  2031. // "use explicit attribute on decl if present, else use attribute from
  2032. // previous decl", for example if the attribute needs to be consistent
  2033. // between redeclarations, you need to call a custom merge function here.
  2034. InheritableAttr *NewAttr = nullptr;
  2035. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  2036. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2037. NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
  2038. AA->isImplicit(), AA->getIntroduced(),
  2039. AA->getDeprecated(),
  2040. AA->getObsoleted(), AA->getUnavailable(),
  2041. AA->getMessage(), AA->getStrict(),
  2042. AA->getReplacement(), AMK,
  2043. AttrSpellingListIndex);
  2044. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2045. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2046. AttrSpellingListIndex);
  2047. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2048. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2049. AttrSpellingListIndex);
  2050. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2051. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  2052. AttrSpellingListIndex);
  2053. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2054. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  2055. AttrSpellingListIndex);
  2056. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2057. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  2058. FA->getFormatIdx(), FA->getFirstArg(),
  2059. AttrSpellingListIndex);
  2060. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2061. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  2062. AttrSpellingListIndex);
  2063. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2064. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  2065. AttrSpellingListIndex,
  2066. IA->getSemanticSpelling());
  2067. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2068. NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
  2069. &S.Context.Idents.get(AA->getSpelling()),
  2070. AttrSpellingListIndex);
  2071. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2072. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2073. isa<CUDAGlobalAttr>(Attr))) {
  2074. // CUDA target attributes are part of function signature for
  2075. // overloading purposes and must not be merged.
  2076. return false;
  2077. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2078. NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
  2079. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2080. NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
  2081. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2082. NewAttr = S.mergeInternalLinkageAttr(
  2083. D, InternalLinkageA->getRange(),
  2084. &S.Context.Idents.get(InternalLinkageA->getSpelling()),
  2085. AttrSpellingListIndex);
  2086. else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
  2087. NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
  2088. &S.Context.Idents.get(CommonA->getSpelling()),
  2089. AttrSpellingListIndex);
  2090. else if (isa<AlignedAttr>(Attr))
  2091. // AlignedAttrs are handled separately, because we need to handle all
  2092. // such attributes on a declaration at the same time.
  2093. NewAttr = nullptr;
  2094. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2095. (AMK == Sema::AMK_Override ||
  2096. AMK == Sema::AMK_ProtocolImplementation))
  2097. NewAttr = nullptr;
  2098. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2099. NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
  2100. UA->getGuid());
  2101. else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
  2102. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2103. if (NewAttr) {
  2104. NewAttr->setInherited(true);
  2105. D->addAttr(NewAttr);
  2106. if (isa<MSInheritanceAttr>(NewAttr))
  2107. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2108. return true;
  2109. }
  2110. return false;
  2111. }
  2112. static const Decl *getDefinition(const Decl *D) {
  2113. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2114. return TD->getDefinition();
  2115. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2116. const VarDecl *Def = VD->getDefinition();
  2117. if (Def)
  2118. return Def;
  2119. return VD->getActingDefinition();
  2120. }
  2121. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2122. return FD->getDefinition();
  2123. return nullptr;
  2124. }
  2125. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2126. for (const auto *Attribute : D->attrs())
  2127. if (Attribute->getKind() == Kind)
  2128. return true;
  2129. return false;
  2130. }
  2131. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2132. /// there are no new attributes in this declaration.
  2133. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2134. if (!New->hasAttrs())
  2135. return;
  2136. const Decl *Def = getDefinition(Old);
  2137. if (!Def || Def == New)
  2138. return;
  2139. AttrVec &NewAttributes = New->getAttrs();
  2140. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2141. const Attr *NewAttribute = NewAttributes[I];
  2142. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2143. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2144. Sema::SkipBodyInfo SkipBody;
  2145. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2146. // If we're skipping this definition, drop the "alias" attribute.
  2147. if (SkipBody.ShouldSkip) {
  2148. NewAttributes.erase(NewAttributes.begin() + I);
  2149. --E;
  2150. continue;
  2151. }
  2152. } else {
  2153. VarDecl *VD = cast<VarDecl>(New);
  2154. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2155. VarDecl::TentativeDefinition
  2156. ? diag::err_alias_after_tentative
  2157. : diag::err_redefinition;
  2158. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2159. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2160. VD->setInvalidDecl();
  2161. }
  2162. ++I;
  2163. continue;
  2164. }
  2165. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2166. // Tentative definitions are only interesting for the alias check above.
  2167. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2168. ++I;
  2169. continue;
  2170. }
  2171. }
  2172. if (hasAttribute(Def, NewAttribute->getKind())) {
  2173. ++I;
  2174. continue; // regular attr merging will take care of validating this.
  2175. }
  2176. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2177. // C's _Noreturn is allowed to be added to a function after it is defined.
  2178. ++I;
  2179. continue;
  2180. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2181. if (AA->isAlignas()) {
  2182. // C++11 [dcl.align]p6:
  2183. // if any declaration of an entity has an alignment-specifier,
  2184. // every defining declaration of that entity shall specify an
  2185. // equivalent alignment.
  2186. // C11 6.7.5/7:
  2187. // If the definition of an object does not have an alignment
  2188. // specifier, any other declaration of that object shall also
  2189. // have no alignment specifier.
  2190. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2191. << AA;
  2192. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2193. << AA;
  2194. NewAttributes.erase(NewAttributes.begin() + I);
  2195. --E;
  2196. continue;
  2197. }
  2198. }
  2199. S.Diag(NewAttribute->getLocation(),
  2200. diag::warn_attribute_precede_definition);
  2201. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2202. NewAttributes.erase(NewAttributes.begin() + I);
  2203. --E;
  2204. }
  2205. }
  2206. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2207. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2208. AvailabilityMergeKind AMK) {
  2209. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2210. UsedAttr *NewAttr = OldAttr->clone(Context);
  2211. NewAttr->setInherited(true);
  2212. New->addAttr(NewAttr);
  2213. }
  2214. if (!Old->hasAttrs() && !New->hasAttrs())
  2215. return;
  2216. // Attributes declared post-definition are currently ignored.
  2217. checkNewAttributesAfterDef(*this, New, Old);
  2218. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2219. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2220. if (OldA->getLabel() != NewA->getLabel()) {
  2221. // This redeclaration changes __asm__ label.
  2222. Diag(New->getLocation(), diag::err_different_asm_label);
  2223. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2224. }
  2225. } else if (Old->isUsed()) {
  2226. // This redeclaration adds an __asm__ label to a declaration that has
  2227. // already been ODR-used.
  2228. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2229. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2230. }
  2231. }
  2232. // Re-declaration cannot add abi_tag's.
  2233. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2234. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2235. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2236. if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
  2237. NewTag) == OldAbiTagAttr->tags_end()) {
  2238. Diag(NewAbiTagAttr->getLocation(),
  2239. diag::err_new_abi_tag_on_redeclaration)
  2240. << NewTag;
  2241. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2242. }
  2243. }
  2244. } else {
  2245. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2246. Diag(Old->getLocation(), diag::note_previous_declaration);
  2247. }
  2248. }
  2249. if (!Old->hasAttrs())
  2250. return;
  2251. bool foundAny = New->hasAttrs();
  2252. // Ensure that any moving of objects within the allocated map is done before
  2253. // we process them.
  2254. if (!foundAny) New->setAttrs(AttrVec());
  2255. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2256. // Ignore deprecated/unavailable/availability attributes if requested.
  2257. AvailabilityMergeKind LocalAMK = AMK_None;
  2258. if (isa<DeprecatedAttr>(I) ||
  2259. isa<UnavailableAttr>(I) ||
  2260. isa<AvailabilityAttr>(I)) {
  2261. switch (AMK) {
  2262. case AMK_None:
  2263. continue;
  2264. case AMK_Redeclaration:
  2265. case AMK_Override:
  2266. case AMK_ProtocolImplementation:
  2267. LocalAMK = AMK;
  2268. break;
  2269. }
  2270. }
  2271. // Already handled.
  2272. if (isa<UsedAttr>(I))
  2273. continue;
  2274. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2275. foundAny = true;
  2276. }
  2277. if (mergeAlignedAttrs(*this, New, Old))
  2278. foundAny = true;
  2279. if (!foundAny) New->dropAttrs();
  2280. }
  2281. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2282. /// to the new one.
  2283. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2284. const ParmVarDecl *oldDecl,
  2285. Sema &S) {
  2286. // C++11 [dcl.attr.depend]p2:
  2287. // The first declaration of a function shall specify the
  2288. // carries_dependency attribute for its declarator-id if any declaration
  2289. // of the function specifies the carries_dependency attribute.
  2290. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2291. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2292. S.Diag(CDA->getLocation(),
  2293. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2294. // Find the first declaration of the parameter.
  2295. // FIXME: Should we build redeclaration chains for function parameters?
  2296. const FunctionDecl *FirstFD =
  2297. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2298. const ParmVarDecl *FirstVD =
  2299. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2300. S.Diag(FirstVD->getLocation(),
  2301. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2302. }
  2303. if (!oldDecl->hasAttrs())
  2304. return;
  2305. bool foundAny = newDecl->hasAttrs();
  2306. // Ensure that any moving of objects within the allocated map is
  2307. // done before we process them.
  2308. if (!foundAny) newDecl->setAttrs(AttrVec());
  2309. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2310. if (!DeclHasAttr(newDecl, I)) {
  2311. InheritableAttr *newAttr =
  2312. cast<InheritableParamAttr>(I->clone(S.Context));
  2313. newAttr->setInherited(true);
  2314. newDecl->addAttr(newAttr);
  2315. foundAny = true;
  2316. }
  2317. }
  2318. if (!foundAny) newDecl->dropAttrs();
  2319. }
  2320. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2321. const ParmVarDecl *OldParam,
  2322. Sema &S) {
  2323. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2324. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2325. if (*Oldnullability != *Newnullability) {
  2326. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2327. << DiagNullabilityKind(
  2328. *Newnullability,
  2329. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2330. != 0))
  2331. << DiagNullabilityKind(
  2332. *Oldnullability,
  2333. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2334. != 0));
  2335. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2336. }
  2337. } else {
  2338. QualType NewT = NewParam->getType();
  2339. NewT = S.Context.getAttributedType(
  2340. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2341. NewT, NewT);
  2342. NewParam->setType(NewT);
  2343. }
  2344. }
  2345. }
  2346. namespace {
  2347. /// Used in MergeFunctionDecl to keep track of function parameters in
  2348. /// C.
  2349. struct GNUCompatibleParamWarning {
  2350. ParmVarDecl *OldParm;
  2351. ParmVarDecl *NewParm;
  2352. QualType PromotedType;
  2353. };
  2354. } // end anonymous namespace
  2355. /// getSpecialMember - get the special member enum for a method.
  2356. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2357. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2358. if (Ctor->isDefaultConstructor())
  2359. return Sema::CXXDefaultConstructor;
  2360. if (Ctor->isCopyConstructor())
  2361. return Sema::CXXCopyConstructor;
  2362. if (Ctor->isMoveConstructor())
  2363. return Sema::CXXMoveConstructor;
  2364. } else if (isa<CXXDestructorDecl>(MD)) {
  2365. return Sema::CXXDestructor;
  2366. } else if (MD->isCopyAssignmentOperator()) {
  2367. return Sema::CXXCopyAssignment;
  2368. } else if (MD->isMoveAssignmentOperator()) {
  2369. return Sema::CXXMoveAssignment;
  2370. }
  2371. return Sema::CXXInvalid;
  2372. }
  2373. // Determine whether the previous declaration was a definition, implicit
  2374. // declaration, or a declaration.
  2375. template <typename T>
  2376. static std::pair<diag::kind, SourceLocation>
  2377. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2378. diag::kind PrevDiag;
  2379. SourceLocation OldLocation = Old->getLocation();
  2380. if (Old->isThisDeclarationADefinition())
  2381. PrevDiag = diag::note_previous_definition;
  2382. else if (Old->isImplicit()) {
  2383. PrevDiag = diag::note_previous_implicit_declaration;
  2384. if (OldLocation.isInvalid())
  2385. OldLocation = New->getLocation();
  2386. } else
  2387. PrevDiag = diag::note_previous_declaration;
  2388. return std::make_pair(PrevDiag, OldLocation);
  2389. }
  2390. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2391. /// only extern inline functions can be redefined, and even then only in
  2392. /// GNU89 mode.
  2393. static bool canRedefineFunction(const FunctionDecl *FD,
  2394. const LangOptions& LangOpts) {
  2395. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2396. !LangOpts.CPlusPlus &&
  2397. FD->isInlineSpecified() &&
  2398. FD->getStorageClass() == SC_Extern);
  2399. }
  2400. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2401. const AttributedType *AT = T->getAs<AttributedType>();
  2402. while (AT && !AT->isCallingConv())
  2403. AT = AT->getModifiedType()->getAs<AttributedType>();
  2404. return AT;
  2405. }
  2406. template <typename T>
  2407. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2408. const DeclContext *DC = Old->getDeclContext();
  2409. if (DC->isRecord())
  2410. return false;
  2411. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2412. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2413. return true;
  2414. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2415. return true;
  2416. return false;
  2417. }
  2418. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2419. static bool isExternC(VarTemplateDecl *) { return false; }
  2420. /// \brief Check whether a redeclaration of an entity introduced by a
  2421. /// using-declaration is valid, given that we know it's not an overload
  2422. /// (nor a hidden tag declaration).
  2423. template<typename ExpectedDecl>
  2424. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2425. ExpectedDecl *New) {
  2426. // C++11 [basic.scope.declarative]p4:
  2427. // Given a set of declarations in a single declarative region, each of
  2428. // which specifies the same unqualified name,
  2429. // -- they shall all refer to the same entity, or all refer to functions
  2430. // and function templates; or
  2431. // -- exactly one declaration shall declare a class name or enumeration
  2432. // name that is not a typedef name and the other declarations shall all
  2433. // refer to the same variable or enumerator, or all refer to functions
  2434. // and function templates; in this case the class name or enumeration
  2435. // name is hidden (3.3.10).
  2436. // C++11 [namespace.udecl]p14:
  2437. // If a function declaration in namespace scope or block scope has the
  2438. // same name and the same parameter-type-list as a function introduced
  2439. // by a using-declaration, and the declarations do not declare the same
  2440. // function, the program is ill-formed.
  2441. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2442. if (Old &&
  2443. !Old->getDeclContext()->getRedeclContext()->Equals(
  2444. New->getDeclContext()->getRedeclContext()) &&
  2445. !(isExternC(Old) && isExternC(New)))
  2446. Old = nullptr;
  2447. if (!Old) {
  2448. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2449. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2450. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2451. return true;
  2452. }
  2453. return false;
  2454. }
  2455. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2456. const FunctionDecl *B) {
  2457. assert(A->getNumParams() == B->getNumParams());
  2458. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2459. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2460. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2461. if (AttrA == AttrB)
  2462. return true;
  2463. return AttrA && AttrB && AttrA->getType() == AttrB->getType();
  2464. };
  2465. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2466. }
  2467. /// MergeFunctionDecl - We just parsed a function 'New' from
  2468. /// declarator D which has the same name and scope as a previous
  2469. /// declaration 'Old'. Figure out how to resolve this situation,
  2470. /// merging decls or emitting diagnostics as appropriate.
  2471. ///
  2472. /// In C++, New and Old must be declarations that are not
  2473. /// overloaded. Use IsOverload to determine whether New and Old are
  2474. /// overloaded, and to select the Old declaration that New should be
  2475. /// merged with.
  2476. ///
  2477. /// Returns true if there was an error, false otherwise.
  2478. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2479. Scope *S, bool MergeTypeWithOld) {
  2480. // Verify the old decl was also a function.
  2481. FunctionDecl *Old = OldD->getAsFunction();
  2482. if (!Old) {
  2483. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2484. if (New->getFriendObjectKind()) {
  2485. Diag(New->getLocation(), diag::err_using_decl_friend);
  2486. Diag(Shadow->getTargetDecl()->getLocation(),
  2487. diag::note_using_decl_target);
  2488. Diag(Shadow->getUsingDecl()->getLocation(),
  2489. diag::note_using_decl) << 0;
  2490. return true;
  2491. }
  2492. // Check whether the two declarations might declare the same function.
  2493. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2494. return true;
  2495. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2496. } else {
  2497. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2498. << New->getDeclName();
  2499. Diag(OldD->getLocation(), diag::note_previous_definition);
  2500. return true;
  2501. }
  2502. }
  2503. // If the old declaration is invalid, just give up here.
  2504. if (Old->isInvalidDecl())
  2505. return true;
  2506. diag::kind PrevDiag;
  2507. SourceLocation OldLocation;
  2508. std::tie(PrevDiag, OldLocation) =
  2509. getNoteDiagForInvalidRedeclaration(Old, New);
  2510. // Don't complain about this if we're in GNU89 mode and the old function
  2511. // is an extern inline function.
  2512. // Don't complain about specializations. They are not supposed to have
  2513. // storage classes.
  2514. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2515. New->getStorageClass() == SC_Static &&
  2516. Old->hasExternalFormalLinkage() &&
  2517. !New->getTemplateSpecializationInfo() &&
  2518. !canRedefineFunction(Old, getLangOpts())) {
  2519. if (getLangOpts().MicrosoftExt) {
  2520. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2521. Diag(OldLocation, PrevDiag);
  2522. } else {
  2523. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2524. Diag(OldLocation, PrevDiag);
  2525. return true;
  2526. }
  2527. }
  2528. if (New->hasAttr<InternalLinkageAttr>() &&
  2529. !Old->hasAttr<InternalLinkageAttr>()) {
  2530. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  2531. << New->getDeclName();
  2532. Diag(Old->getLocation(), diag::note_previous_definition);
  2533. New->dropAttr<InternalLinkageAttr>();
  2534. }
  2535. // If a function is first declared with a calling convention, but is later
  2536. // declared or defined without one, all following decls assume the calling
  2537. // convention of the first.
  2538. //
  2539. // It's OK if a function is first declared without a calling convention,
  2540. // but is later declared or defined with the default calling convention.
  2541. //
  2542. // To test if either decl has an explicit calling convention, we look for
  2543. // AttributedType sugar nodes on the type as written. If they are missing or
  2544. // were canonicalized away, we assume the calling convention was implicit.
  2545. //
  2546. // Note also that we DO NOT return at this point, because we still have
  2547. // other tests to run.
  2548. QualType OldQType = Context.getCanonicalType(Old->getType());
  2549. QualType NewQType = Context.getCanonicalType(New->getType());
  2550. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2551. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2552. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2553. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2554. bool RequiresAdjustment = false;
  2555. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2556. FunctionDecl *First = Old->getFirstDecl();
  2557. const FunctionType *FT =
  2558. First->getType().getCanonicalType()->castAs<FunctionType>();
  2559. FunctionType::ExtInfo FI = FT->getExtInfo();
  2560. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2561. if (!NewCCExplicit) {
  2562. // Inherit the CC from the previous declaration if it was specified
  2563. // there but not here.
  2564. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2565. RequiresAdjustment = true;
  2566. } else {
  2567. // Calling conventions aren't compatible, so complain.
  2568. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2569. Diag(New->getLocation(), diag::err_cconv_change)
  2570. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2571. << !FirstCCExplicit
  2572. << (!FirstCCExplicit ? "" :
  2573. FunctionType::getNameForCallConv(FI.getCC()));
  2574. // Put the note on the first decl, since it is the one that matters.
  2575. Diag(First->getLocation(), diag::note_previous_declaration);
  2576. return true;
  2577. }
  2578. }
  2579. // FIXME: diagnose the other way around?
  2580. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2581. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2582. RequiresAdjustment = true;
  2583. }
  2584. // Merge regparm attribute.
  2585. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2586. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2587. if (NewTypeInfo.getHasRegParm()) {
  2588. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2589. << NewType->getRegParmType()
  2590. << OldType->getRegParmType();
  2591. Diag(OldLocation, diag::note_previous_declaration);
  2592. return true;
  2593. }
  2594. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2595. RequiresAdjustment = true;
  2596. }
  2597. // Merge ns_returns_retained attribute.
  2598. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2599. if (NewTypeInfo.getProducesResult()) {
  2600. Diag(New->getLocation(), diag::err_returns_retained_mismatch);
  2601. Diag(OldLocation, diag::note_previous_declaration);
  2602. return true;
  2603. }
  2604. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2605. RequiresAdjustment = true;
  2606. }
  2607. if (RequiresAdjustment) {
  2608. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2609. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2610. New->setType(QualType(AdjustedType, 0));
  2611. NewQType = Context.getCanonicalType(New->getType());
  2612. NewType = cast<FunctionType>(NewQType);
  2613. }
  2614. // If this redeclaration makes the function inline, we may need to add it to
  2615. // UndefinedButUsed.
  2616. if (!Old->isInlined() && New->isInlined() &&
  2617. !New->hasAttr<GNUInlineAttr>() &&
  2618. !getLangOpts().GNUInline &&
  2619. Old->isUsed(false) &&
  2620. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2621. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2622. SourceLocation()));
  2623. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2624. // about it.
  2625. if (New->hasAttr<GNUInlineAttr>() &&
  2626. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2627. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2628. }
  2629. // If pass_object_size params don't match up perfectly, this isn't a valid
  2630. // redeclaration.
  2631. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  2632. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  2633. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  2634. << New->getDeclName();
  2635. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2636. return true;
  2637. }
  2638. if (getLangOpts().CPlusPlus) {
  2639. // C++1z [over.load]p2
  2640. // Certain function declarations cannot be overloaded:
  2641. // -- Function declarations that differ only in the return type,
  2642. // the exception specification, or both cannot be overloaded.
  2643. // Check the exception specifications match. This may recompute the type of
  2644. // both Old and New if it resolved exception specifications, so grab the
  2645. // types again after this. Because this updates the type, we do this before
  2646. // any of the other checks below, which may update the "de facto" NewQType
  2647. // but do not necessarily update the type of New.
  2648. if (CheckEquivalentExceptionSpec(Old, New))
  2649. return true;
  2650. OldQType = Context.getCanonicalType(Old->getType());
  2651. NewQType = Context.getCanonicalType(New->getType());
  2652. // Go back to the type source info to compare the declared return types,
  2653. // per C++1y [dcl.type.auto]p13:
  2654. // Redeclarations or specializations of a function or function template
  2655. // with a declared return type that uses a placeholder type shall also
  2656. // use that placeholder, not a deduced type.
  2657. QualType OldDeclaredReturnType =
  2658. (Old->getTypeSourceInfo()
  2659. ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2660. : OldType)->getReturnType();
  2661. QualType NewDeclaredReturnType =
  2662. (New->getTypeSourceInfo()
  2663. ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2664. : NewType)->getReturnType();
  2665. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  2666. !((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2667. New->isLocalExternDecl())) {
  2668. QualType ResQT;
  2669. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  2670. OldDeclaredReturnType->isObjCObjectPointerType())
  2671. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  2672. if (ResQT.isNull()) {
  2673. if (New->isCXXClassMember() && New->isOutOfLine())
  2674. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  2675. << New << New->getReturnTypeSourceRange();
  2676. else
  2677. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  2678. << New->getReturnTypeSourceRange();
  2679. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  2680. << Old->getReturnTypeSourceRange();
  2681. return true;
  2682. }
  2683. else
  2684. NewQType = ResQT;
  2685. }
  2686. QualType OldReturnType = OldType->getReturnType();
  2687. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  2688. if (OldReturnType != NewReturnType) {
  2689. // If this function has a deduced return type and has already been
  2690. // defined, copy the deduced value from the old declaration.
  2691. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  2692. if (OldAT && OldAT->isDeduced()) {
  2693. New->setType(
  2694. SubstAutoType(New->getType(),
  2695. OldAT->isDependentType() ? Context.DependentTy
  2696. : OldAT->getDeducedType()));
  2697. NewQType = Context.getCanonicalType(
  2698. SubstAutoType(NewQType,
  2699. OldAT->isDependentType() ? Context.DependentTy
  2700. : OldAT->getDeducedType()));
  2701. }
  2702. }
  2703. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  2704. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  2705. if (OldMethod && NewMethod) {
  2706. // Preserve triviality.
  2707. NewMethod->setTrivial(OldMethod->isTrivial());
  2708. // MSVC allows explicit template specialization at class scope:
  2709. // 2 CXXMethodDecls referring to the same function will be injected.
  2710. // We don't want a redeclaration error.
  2711. bool IsClassScopeExplicitSpecialization =
  2712. OldMethod->isFunctionTemplateSpecialization() &&
  2713. NewMethod->isFunctionTemplateSpecialization();
  2714. bool isFriend = NewMethod->getFriendObjectKind();
  2715. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  2716. !IsClassScopeExplicitSpecialization) {
  2717. // -- Member function declarations with the same name and the
  2718. // same parameter types cannot be overloaded if any of them
  2719. // is a static member function declaration.
  2720. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  2721. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  2722. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2723. return true;
  2724. }
  2725. // C++ [class.mem]p1:
  2726. // [...] A member shall not be declared twice in the
  2727. // member-specification, except that a nested class or member
  2728. // class template can be declared and then later defined.
  2729. if (ActiveTemplateInstantiations.empty()) {
  2730. unsigned NewDiag;
  2731. if (isa<CXXConstructorDecl>(OldMethod))
  2732. NewDiag = diag::err_constructor_redeclared;
  2733. else if (isa<CXXDestructorDecl>(NewMethod))
  2734. NewDiag = diag::err_destructor_redeclared;
  2735. else if (isa<CXXConversionDecl>(NewMethod))
  2736. NewDiag = diag::err_conv_function_redeclared;
  2737. else
  2738. NewDiag = diag::err_member_redeclared;
  2739. Diag(New->getLocation(), NewDiag);
  2740. } else {
  2741. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2742. << New << New->getType();
  2743. }
  2744. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2745. return true;
  2746. // Complain if this is an explicit declaration of a special
  2747. // member that was initially declared implicitly.
  2748. //
  2749. // As an exception, it's okay to befriend such methods in order
  2750. // to permit the implicit constructor/destructor/operator calls.
  2751. } else if (OldMethod->isImplicit()) {
  2752. if (isFriend) {
  2753. NewMethod->setImplicit();
  2754. } else {
  2755. Diag(NewMethod->getLocation(),
  2756. diag::err_definition_of_implicitly_declared_member)
  2757. << New << getSpecialMember(OldMethod);
  2758. return true;
  2759. }
  2760. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  2761. Diag(NewMethod->getLocation(),
  2762. diag::err_definition_of_explicitly_defaulted_member)
  2763. << getSpecialMember(OldMethod);
  2764. return true;
  2765. }
  2766. }
  2767. // C++11 [dcl.attr.noreturn]p1:
  2768. // The first declaration of a function shall specify the noreturn
  2769. // attribute if any declaration of that function specifies the noreturn
  2770. // attribute.
  2771. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  2772. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  2773. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  2774. Diag(Old->getFirstDecl()->getLocation(),
  2775. diag::note_noreturn_missing_first_decl);
  2776. }
  2777. // C++11 [dcl.attr.depend]p2:
  2778. // The first declaration of a function shall specify the
  2779. // carries_dependency attribute for its declarator-id if any declaration
  2780. // of the function specifies the carries_dependency attribute.
  2781. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  2782. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  2783. Diag(CDA->getLocation(),
  2784. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  2785. Diag(Old->getFirstDecl()->getLocation(),
  2786. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  2787. }
  2788. // (C++98 8.3.5p3):
  2789. // All declarations for a function shall agree exactly in both the
  2790. // return type and the parameter-type-list.
  2791. // We also want to respect all the extended bits except noreturn.
  2792. // noreturn should now match unless the old type info didn't have it.
  2793. QualType OldQTypeForComparison = OldQType;
  2794. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  2795. auto *OldType = OldQType->castAs<FunctionProtoType>();
  2796. const FunctionType *OldTypeForComparison
  2797. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  2798. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  2799. assert(OldQTypeForComparison.isCanonical());
  2800. }
  2801. if (haveIncompatibleLanguageLinkages(Old, New)) {
  2802. // As a special case, retain the language linkage from previous
  2803. // declarations of a friend function as an extension.
  2804. //
  2805. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  2806. // and is useful because there's otherwise no way to specify language
  2807. // linkage within class scope.
  2808. //
  2809. // Check cautiously as the friend object kind isn't yet complete.
  2810. if (New->getFriendObjectKind() != Decl::FOK_None) {
  2811. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  2812. Diag(OldLocation, PrevDiag);
  2813. } else {
  2814. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  2815. Diag(OldLocation, PrevDiag);
  2816. return true;
  2817. }
  2818. }
  2819. if (OldQTypeForComparison == NewQType)
  2820. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2821. if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2822. New->isLocalExternDecl()) {
  2823. // It's OK if we couldn't merge types for a local function declaraton
  2824. // if either the old or new type is dependent. We'll merge the types
  2825. // when we instantiate the function.
  2826. return false;
  2827. }
  2828. // Fall through for conflicting redeclarations and redefinitions.
  2829. }
  2830. // C: Function types need to be compatible, not identical. This handles
  2831. // duplicate function decls like "void f(int); void f(enum X);" properly.
  2832. if (!getLangOpts().CPlusPlus &&
  2833. Context.typesAreCompatible(OldQType, NewQType)) {
  2834. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  2835. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  2836. const FunctionProtoType *OldProto = nullptr;
  2837. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  2838. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  2839. // The old declaration provided a function prototype, but the
  2840. // new declaration does not. Merge in the prototype.
  2841. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  2842. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  2843. NewQType =
  2844. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  2845. OldProto->getExtProtoInfo());
  2846. New->setType(NewQType);
  2847. New->setHasInheritedPrototype();
  2848. // Synthesize parameters with the same types.
  2849. SmallVector<ParmVarDecl*, 16> Params;
  2850. for (const auto &ParamType : OldProto->param_types()) {
  2851. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  2852. SourceLocation(), nullptr,
  2853. ParamType, /*TInfo=*/nullptr,
  2854. SC_None, nullptr);
  2855. Param->setScopeInfo(0, Params.size());
  2856. Param->setImplicit();
  2857. Params.push_back(Param);
  2858. }
  2859. New->setParams(Params);
  2860. }
  2861. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2862. }
  2863. // GNU C permits a K&R definition to follow a prototype declaration
  2864. // if the declared types of the parameters in the K&R definition
  2865. // match the types in the prototype declaration, even when the
  2866. // promoted types of the parameters from the K&R definition differ
  2867. // from the types in the prototype. GCC then keeps the types from
  2868. // the prototype.
  2869. //
  2870. // If a variadic prototype is followed by a non-variadic K&R definition,
  2871. // the K&R definition becomes variadic. This is sort of an edge case, but
  2872. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  2873. // C99 6.9.1p8.
  2874. if (!getLangOpts().CPlusPlus &&
  2875. Old->hasPrototype() && !New->hasPrototype() &&
  2876. New->getType()->getAs<FunctionProtoType>() &&
  2877. Old->getNumParams() == New->getNumParams()) {
  2878. SmallVector<QualType, 16> ArgTypes;
  2879. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  2880. const FunctionProtoType *OldProto
  2881. = Old->getType()->getAs<FunctionProtoType>();
  2882. const FunctionProtoType *NewProto
  2883. = New->getType()->getAs<FunctionProtoType>();
  2884. // Determine whether this is the GNU C extension.
  2885. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  2886. NewProto->getReturnType());
  2887. bool LooseCompatible = !MergedReturn.isNull();
  2888. for (unsigned Idx = 0, End = Old->getNumParams();
  2889. LooseCompatible && Idx != End; ++Idx) {
  2890. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  2891. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  2892. if (Context.typesAreCompatible(OldParm->getType(),
  2893. NewProto->getParamType(Idx))) {
  2894. ArgTypes.push_back(NewParm->getType());
  2895. } else if (Context.typesAreCompatible(OldParm->getType(),
  2896. NewParm->getType(),
  2897. /*CompareUnqualified=*/true)) {
  2898. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  2899. NewProto->getParamType(Idx) };
  2900. Warnings.push_back(Warn);
  2901. ArgTypes.push_back(NewParm->getType());
  2902. } else
  2903. LooseCompatible = false;
  2904. }
  2905. if (LooseCompatible) {
  2906. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  2907. Diag(Warnings[Warn].NewParm->getLocation(),
  2908. diag::ext_param_promoted_not_compatible_with_prototype)
  2909. << Warnings[Warn].PromotedType
  2910. << Warnings[Warn].OldParm->getType();
  2911. if (Warnings[Warn].OldParm->getLocation().isValid())
  2912. Diag(Warnings[Warn].OldParm->getLocation(),
  2913. diag::note_previous_declaration);
  2914. }
  2915. if (MergeTypeWithOld)
  2916. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  2917. OldProto->getExtProtoInfo()));
  2918. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2919. }
  2920. // Fall through to diagnose conflicting types.
  2921. }
  2922. // A function that has already been declared has been redeclared or
  2923. // defined with a different type; show an appropriate diagnostic.
  2924. // If the previous declaration was an implicitly-generated builtin
  2925. // declaration, then at the very least we should use a specialized note.
  2926. unsigned BuiltinID;
  2927. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  2928. // If it's actually a library-defined builtin function like 'malloc'
  2929. // or 'printf', just warn about the incompatible redeclaration.
  2930. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  2931. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  2932. Diag(OldLocation, diag::note_previous_builtin_declaration)
  2933. << Old << Old->getType();
  2934. // If this is a global redeclaration, just forget hereafter
  2935. // about the "builtin-ness" of the function.
  2936. //
  2937. // Doing this for local extern declarations is problematic. If
  2938. // the builtin declaration remains visible, a second invalid
  2939. // local declaration will produce a hard error; if it doesn't
  2940. // remain visible, a single bogus local redeclaration (which is
  2941. // actually only a warning) could break all the downstream code.
  2942. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  2943. New->getIdentifier()->revertBuiltin();
  2944. return false;
  2945. }
  2946. PrevDiag = diag::note_previous_builtin_declaration;
  2947. }
  2948. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  2949. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2950. return true;
  2951. }
  2952. /// \brief Completes the merge of two function declarations that are
  2953. /// known to be compatible.
  2954. ///
  2955. /// This routine handles the merging of attributes and other
  2956. /// properties of function declarations from the old declaration to
  2957. /// the new declaration, once we know that New is in fact a
  2958. /// redeclaration of Old.
  2959. ///
  2960. /// \returns false
  2961. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  2962. Scope *S, bool MergeTypeWithOld) {
  2963. // Merge the attributes
  2964. mergeDeclAttributes(New, Old);
  2965. // Merge "pure" flag.
  2966. if (Old->isPure())
  2967. New->setPure();
  2968. // Merge "used" flag.
  2969. if (Old->getMostRecentDecl()->isUsed(false))
  2970. New->setIsUsed();
  2971. // Merge attributes from the parameters. These can mismatch with K&R
  2972. // declarations.
  2973. if (New->getNumParams() == Old->getNumParams())
  2974. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  2975. ParmVarDecl *NewParam = New->getParamDecl(i);
  2976. ParmVarDecl *OldParam = Old->getParamDecl(i);
  2977. mergeParamDeclAttributes(NewParam, OldParam, *this);
  2978. mergeParamDeclTypes(NewParam, OldParam, *this);
  2979. }
  2980. if (getLangOpts().CPlusPlus)
  2981. return MergeCXXFunctionDecl(New, Old, S);
  2982. // Merge the function types so the we get the composite types for the return
  2983. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  2984. // was visible.
  2985. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  2986. if (!Merged.isNull() && MergeTypeWithOld)
  2987. New->setType(Merged);
  2988. return false;
  2989. }
  2990. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  2991. ObjCMethodDecl *oldMethod) {
  2992. // Merge the attributes, including deprecated/unavailable
  2993. AvailabilityMergeKind MergeKind =
  2994. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  2995. ? AMK_ProtocolImplementation
  2996. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  2997. : AMK_Override;
  2998. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  2999. // Merge attributes from the parameters.
  3000. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3001. oe = oldMethod->param_end();
  3002. for (ObjCMethodDecl::param_iterator
  3003. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3004. ni != ne && oi != oe; ++ni, ++oi)
  3005. mergeParamDeclAttributes(*ni, *oi, *this);
  3006. CheckObjCMethodOverride(newMethod, oldMethod);
  3007. }
  3008. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3009. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3010. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3011. ? diag::err_redefinition_different_type
  3012. : diag::err_redeclaration_different_type)
  3013. << New->getDeclName() << New->getType() << Old->getType();
  3014. diag::kind PrevDiag;
  3015. SourceLocation OldLocation;
  3016. std::tie(PrevDiag, OldLocation)
  3017. = getNoteDiagForInvalidRedeclaration(Old, New);
  3018. S.Diag(OldLocation, PrevDiag);
  3019. New->setInvalidDecl();
  3020. }
  3021. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3022. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3023. /// emitting diagnostics as appropriate.
  3024. ///
  3025. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3026. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3027. /// is attached.
  3028. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3029. bool MergeTypeWithOld) {
  3030. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3031. return;
  3032. QualType MergedT;
  3033. if (getLangOpts().CPlusPlus) {
  3034. if (New->getType()->isUndeducedType()) {
  3035. // We don't know what the new type is until the initializer is attached.
  3036. return;
  3037. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3038. // These could still be something that needs exception specs checked.
  3039. return MergeVarDeclExceptionSpecs(New, Old);
  3040. }
  3041. // C++ [basic.link]p10:
  3042. // [...] the types specified by all declarations referring to a given
  3043. // object or function shall be identical, except that declarations for an
  3044. // array object can specify array types that differ by the presence or
  3045. // absence of a major array bound (8.3.4).
  3046. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3047. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3048. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3049. // We are merging a variable declaration New into Old. If it has an array
  3050. // bound, and that bound differs from Old's bound, we should diagnose the
  3051. // mismatch.
  3052. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3053. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3054. PrevVD = PrevVD->getPreviousDecl()) {
  3055. const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
  3056. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3057. continue;
  3058. if (!Context.hasSameType(NewArray, PrevVDTy))
  3059. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3060. }
  3061. }
  3062. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3063. if (Context.hasSameType(OldArray->getElementType(),
  3064. NewArray->getElementType()))
  3065. MergedT = New->getType();
  3066. }
  3067. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3068. // has no array bound, it should not inherit one from Old, if Old is not
  3069. // visible.
  3070. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3071. if (Context.hasSameType(OldArray->getElementType(),
  3072. NewArray->getElementType()))
  3073. MergedT = Old->getType();
  3074. }
  3075. }
  3076. else if (New->getType()->isObjCObjectPointerType() &&
  3077. Old->getType()->isObjCObjectPointerType()) {
  3078. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3079. Old->getType());
  3080. }
  3081. } else {
  3082. // C 6.2.7p2:
  3083. // All declarations that refer to the same object or function shall have
  3084. // compatible type.
  3085. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3086. }
  3087. if (MergedT.isNull()) {
  3088. // It's OK if we couldn't merge types if either type is dependent, for a
  3089. // block-scope variable. In other cases (static data members of class
  3090. // templates, variable templates, ...), we require the types to be
  3091. // equivalent.
  3092. // FIXME: The C++ standard doesn't say anything about this.
  3093. if ((New->getType()->isDependentType() ||
  3094. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3095. // If the old type was dependent, we can't merge with it, so the new type
  3096. // becomes dependent for now. We'll reproduce the original type when we
  3097. // instantiate the TypeSourceInfo for the variable.
  3098. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3099. New->setType(Context.DependentTy);
  3100. return;
  3101. }
  3102. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3103. }
  3104. // Don't actually update the type on the new declaration if the old
  3105. // declaration was an extern declaration in a different scope.
  3106. if (MergeTypeWithOld)
  3107. New->setType(MergedT);
  3108. }
  3109. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3110. LookupResult &Previous) {
  3111. // C11 6.2.7p4:
  3112. // For an identifier with internal or external linkage declared
  3113. // in a scope in which a prior declaration of that identifier is
  3114. // visible, if the prior declaration specifies internal or
  3115. // external linkage, the type of the identifier at the later
  3116. // declaration becomes the composite type.
  3117. //
  3118. // If the variable isn't visible, we do not merge with its type.
  3119. if (Previous.isShadowed())
  3120. return false;
  3121. if (S.getLangOpts().CPlusPlus) {
  3122. // C++11 [dcl.array]p3:
  3123. // If there is a preceding declaration of the entity in the same
  3124. // scope in which the bound was specified, an omitted array bound
  3125. // is taken to be the same as in that earlier declaration.
  3126. return NewVD->isPreviousDeclInSameBlockScope() ||
  3127. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3128. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3129. } else {
  3130. // If the old declaration was function-local, don't merge with its
  3131. // type unless we're in the same function.
  3132. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3133. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3134. }
  3135. }
  3136. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3137. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3138. /// situation, merging decls or emitting diagnostics as appropriate.
  3139. ///
  3140. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3141. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3142. /// definitions here, since the initializer hasn't been attached.
  3143. ///
  3144. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3145. // If the new decl is already invalid, don't do any other checking.
  3146. if (New->isInvalidDecl())
  3147. return;
  3148. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3149. return;
  3150. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3151. // Verify the old decl was also a variable or variable template.
  3152. VarDecl *Old = nullptr;
  3153. VarTemplateDecl *OldTemplate = nullptr;
  3154. if (Previous.isSingleResult()) {
  3155. if (NewTemplate) {
  3156. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3157. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3158. if (auto *Shadow =
  3159. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3160. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3161. return New->setInvalidDecl();
  3162. } else {
  3163. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3164. if (auto *Shadow =
  3165. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3166. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3167. return New->setInvalidDecl();
  3168. }
  3169. }
  3170. if (!Old) {
  3171. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3172. << New->getDeclName();
  3173. Diag(Previous.getRepresentativeDecl()->getLocation(),
  3174. diag::note_previous_definition);
  3175. return New->setInvalidDecl();
  3176. }
  3177. // Ensure the template parameters are compatible.
  3178. if (NewTemplate &&
  3179. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3180. OldTemplate->getTemplateParameters(),
  3181. /*Complain=*/true, TPL_TemplateMatch))
  3182. return New->setInvalidDecl();
  3183. // C++ [class.mem]p1:
  3184. // A member shall not be declared twice in the member-specification [...]
  3185. //
  3186. // Here, we need only consider static data members.
  3187. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3188. Diag(New->getLocation(), diag::err_duplicate_member)
  3189. << New->getIdentifier();
  3190. Diag(Old->getLocation(), diag::note_previous_declaration);
  3191. New->setInvalidDecl();
  3192. }
  3193. mergeDeclAttributes(New, Old);
  3194. // Warn if an already-declared variable is made a weak_import in a subsequent
  3195. // declaration
  3196. if (New->hasAttr<WeakImportAttr>() &&
  3197. Old->getStorageClass() == SC_None &&
  3198. !Old->hasAttr<WeakImportAttr>()) {
  3199. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3200. Diag(Old->getLocation(), diag::note_previous_definition);
  3201. // Remove weak_import attribute on new declaration.
  3202. New->dropAttr<WeakImportAttr>();
  3203. }
  3204. if (New->hasAttr<InternalLinkageAttr>() &&
  3205. !Old->hasAttr<InternalLinkageAttr>()) {
  3206. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  3207. << New->getDeclName();
  3208. Diag(Old->getLocation(), diag::note_previous_definition);
  3209. New->dropAttr<InternalLinkageAttr>();
  3210. }
  3211. // Merge the types.
  3212. VarDecl *MostRecent = Old->getMostRecentDecl();
  3213. if (MostRecent != Old) {
  3214. MergeVarDeclTypes(New, MostRecent,
  3215. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3216. if (New->isInvalidDecl())
  3217. return;
  3218. }
  3219. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3220. if (New->isInvalidDecl())
  3221. return;
  3222. diag::kind PrevDiag;
  3223. SourceLocation OldLocation;
  3224. std::tie(PrevDiag, OldLocation) =
  3225. getNoteDiagForInvalidRedeclaration(Old, New);
  3226. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3227. if (New->getStorageClass() == SC_Static &&
  3228. !New->isStaticDataMember() &&
  3229. Old->hasExternalFormalLinkage()) {
  3230. if (getLangOpts().MicrosoftExt) {
  3231. Diag(New->getLocation(), diag::ext_static_non_static)
  3232. << New->getDeclName();
  3233. Diag(OldLocation, PrevDiag);
  3234. } else {
  3235. Diag(New->getLocation(), diag::err_static_non_static)
  3236. << New->getDeclName();
  3237. Diag(OldLocation, PrevDiag);
  3238. return New->setInvalidDecl();
  3239. }
  3240. }
  3241. // C99 6.2.2p4:
  3242. // For an identifier declared with the storage-class specifier
  3243. // extern in a scope in which a prior declaration of that
  3244. // identifier is visible,23) if the prior declaration specifies
  3245. // internal or external linkage, the linkage of the identifier at
  3246. // the later declaration is the same as the linkage specified at
  3247. // the prior declaration. If no prior declaration is visible, or
  3248. // if the prior declaration specifies no linkage, then the
  3249. // identifier has external linkage.
  3250. if (New->hasExternalStorage() && Old->hasLinkage())
  3251. /* Okay */;
  3252. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3253. !New->isStaticDataMember() &&
  3254. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3255. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3256. Diag(OldLocation, PrevDiag);
  3257. return New->setInvalidDecl();
  3258. }
  3259. // Check if extern is followed by non-extern and vice-versa.
  3260. if (New->hasExternalStorage() &&
  3261. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3262. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3263. Diag(OldLocation, PrevDiag);
  3264. return New->setInvalidDecl();
  3265. }
  3266. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3267. !New->hasExternalStorage()) {
  3268. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3269. Diag(OldLocation, PrevDiag);
  3270. return New->setInvalidDecl();
  3271. }
  3272. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3273. // FIXME: The test for external storage here seems wrong? We still
  3274. // need to check for mismatches.
  3275. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3276. // Don't complain about out-of-line definitions of static members.
  3277. !(Old->getLexicalDeclContext()->isRecord() &&
  3278. !New->getLexicalDeclContext()->isRecord())) {
  3279. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3280. Diag(OldLocation, PrevDiag);
  3281. return New->setInvalidDecl();
  3282. }
  3283. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3284. if (VarDecl *Def = Old->getDefinition()) {
  3285. // C++1z [dcl.fcn.spec]p4:
  3286. // If the definition of a variable appears in a translation unit before
  3287. // its first declaration as inline, the program is ill-formed.
  3288. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3289. Diag(Def->getLocation(), diag::note_previous_definition);
  3290. }
  3291. }
  3292. // If this redeclaration makes the function inline, we may need to add it to
  3293. // UndefinedButUsed.
  3294. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3295. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3296. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3297. SourceLocation()));
  3298. if (New->getTLSKind() != Old->getTLSKind()) {
  3299. if (!Old->getTLSKind()) {
  3300. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3301. Diag(OldLocation, PrevDiag);
  3302. } else if (!New->getTLSKind()) {
  3303. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3304. Diag(OldLocation, PrevDiag);
  3305. } else {
  3306. // Do not allow redeclaration to change the variable between requiring
  3307. // static and dynamic initialization.
  3308. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3309. // declaration to determine the kind. Do we need to be compatible here?
  3310. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3311. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3312. Diag(OldLocation, PrevDiag);
  3313. }
  3314. }
  3315. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3316. if (getLangOpts().CPlusPlus &&
  3317. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3318. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3319. Old->getCanonicalDecl()->isConstexpr()) {
  3320. // This definition won't be a definition any more once it's been merged.
  3321. Diag(New->getLocation(),
  3322. diag::warn_deprecated_redundant_constexpr_static_def);
  3323. } else if (VarDecl *Def = Old->getDefinition()) {
  3324. if (checkVarDeclRedefinition(Def, New))
  3325. return;
  3326. }
  3327. }
  3328. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3329. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3330. Diag(OldLocation, PrevDiag);
  3331. New->setInvalidDecl();
  3332. return;
  3333. }
  3334. // Merge "used" flag.
  3335. if (Old->getMostRecentDecl()->isUsed(false))
  3336. New->setIsUsed();
  3337. // Keep a chain of previous declarations.
  3338. New->setPreviousDecl(Old);
  3339. if (NewTemplate)
  3340. NewTemplate->setPreviousDecl(OldTemplate);
  3341. // Inherit access appropriately.
  3342. New->setAccess(Old->getAccess());
  3343. if (NewTemplate)
  3344. NewTemplate->setAccess(New->getAccess());
  3345. if (Old->isInline())
  3346. New->setImplicitlyInline();
  3347. }
  3348. /// We've just determined that \p Old and \p New both appear to be definitions
  3349. /// of the same variable. Either diagnose or fix the problem.
  3350. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3351. if (!hasVisibleDefinition(Old) &&
  3352. (New->getFormalLinkage() == InternalLinkage ||
  3353. New->isInline() ||
  3354. New->getDescribedVarTemplate() ||
  3355. New->getNumTemplateParameterLists() ||
  3356. New->getDeclContext()->isDependentContext())) {
  3357. // The previous definition is hidden, and multiple definitions are
  3358. // permitted (in separate TUs). Demote this to a declaration.
  3359. New->demoteThisDefinitionToDeclaration();
  3360. // Make the canonical definition visible.
  3361. if (auto *OldTD = Old->getDescribedVarTemplate())
  3362. makeMergedDefinitionVisible(OldTD, New->getLocation());
  3363. makeMergedDefinitionVisible(Old, New->getLocation());
  3364. return false;
  3365. } else {
  3366. Diag(New->getLocation(), diag::err_redefinition) << New;
  3367. Diag(Old->getLocation(), diag::note_previous_definition);
  3368. New->setInvalidDecl();
  3369. return true;
  3370. }
  3371. }
  3372. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3373. /// no declarator (e.g. "struct foo;") is parsed.
  3374. Decl *
  3375. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3376. RecordDecl *&AnonRecord) {
  3377. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3378. AnonRecord);
  3379. }
  3380. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3381. // disambiguate entities defined in different scopes.
  3382. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3383. // compatibility.
  3384. // We will pick our mangling number depending on which version of MSVC is being
  3385. // targeted.
  3386. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3387. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3388. ? S->getMSCurManglingNumber()
  3389. : S->getMSLastManglingNumber();
  3390. }
  3391. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3392. if (!Context.getLangOpts().CPlusPlus)
  3393. return;
  3394. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3395. // If this tag is the direct child of a class, number it if
  3396. // it is anonymous.
  3397. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3398. return;
  3399. MangleNumberingContext &MCtx =
  3400. Context.getManglingNumberContext(Tag->getParent());
  3401. Context.setManglingNumber(
  3402. Tag, MCtx.getManglingNumber(
  3403. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3404. return;
  3405. }
  3406. // If this tag isn't a direct child of a class, number it if it is local.
  3407. Decl *ManglingContextDecl;
  3408. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3409. Tag->getDeclContext(), ManglingContextDecl)) {
  3410. Context.setManglingNumber(
  3411. Tag, MCtx->getManglingNumber(
  3412. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3413. }
  3414. }
  3415. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3416. TypedefNameDecl *NewTD) {
  3417. if (TagFromDeclSpec->isInvalidDecl())
  3418. return;
  3419. // Do nothing if the tag already has a name for linkage purposes.
  3420. if (TagFromDeclSpec->hasNameForLinkage())
  3421. return;
  3422. // A well-formed anonymous tag must always be a TUK_Definition.
  3423. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3424. // The type must match the tag exactly; no qualifiers allowed.
  3425. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3426. Context.getTagDeclType(TagFromDeclSpec))) {
  3427. if (getLangOpts().CPlusPlus)
  3428. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3429. return;
  3430. }
  3431. // If we've already computed linkage for the anonymous tag, then
  3432. // adding a typedef name for the anonymous decl can change that
  3433. // linkage, which might be a serious problem. Diagnose this as
  3434. // unsupported and ignore the typedef name. TODO: we should
  3435. // pursue this as a language defect and establish a formal rule
  3436. // for how to handle it.
  3437. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3438. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3439. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3440. tagLoc = getLocForEndOfToken(tagLoc);
  3441. llvm::SmallString<40> textToInsert;
  3442. textToInsert += ' ';
  3443. textToInsert += NewTD->getIdentifier()->getName();
  3444. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3445. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3446. return;
  3447. }
  3448. // Otherwise, set this is the anon-decl typedef for the tag.
  3449. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3450. }
  3451. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3452. switch (T) {
  3453. case DeclSpec::TST_class:
  3454. return 0;
  3455. case DeclSpec::TST_struct:
  3456. return 1;
  3457. case DeclSpec::TST_interface:
  3458. return 2;
  3459. case DeclSpec::TST_union:
  3460. return 3;
  3461. case DeclSpec::TST_enum:
  3462. return 4;
  3463. default:
  3464. llvm_unreachable("unexpected type specifier");
  3465. }
  3466. }
  3467. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3468. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3469. /// parameters to cope with template friend declarations.
  3470. Decl *
  3471. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3472. MultiTemplateParamsArg TemplateParams,
  3473. bool IsExplicitInstantiation,
  3474. RecordDecl *&AnonRecord) {
  3475. Decl *TagD = nullptr;
  3476. TagDecl *Tag = nullptr;
  3477. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3478. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3479. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3480. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3481. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3482. TagD = DS.getRepAsDecl();
  3483. if (!TagD) // We probably had an error
  3484. return nullptr;
  3485. // Note that the above type specs guarantee that the
  3486. // type rep is a Decl, whereas in many of the others
  3487. // it's a Type.
  3488. if (isa<TagDecl>(TagD))
  3489. Tag = cast<TagDecl>(TagD);
  3490. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3491. Tag = CTD->getTemplatedDecl();
  3492. }
  3493. if (Tag) {
  3494. handleTagNumbering(Tag, S);
  3495. Tag->setFreeStanding();
  3496. if (Tag->isInvalidDecl())
  3497. return Tag;
  3498. }
  3499. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3500. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3501. // or incomplete types shall not be restrict-qualified."
  3502. if (TypeQuals & DeclSpec::TQ_restrict)
  3503. Diag(DS.getRestrictSpecLoc(),
  3504. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3505. << DS.getSourceRange();
  3506. }
  3507. if (DS.isInlineSpecified())
  3508. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  3509. << getLangOpts().CPlusPlus1z;
  3510. if (DS.isConstexprSpecified()) {
  3511. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3512. // and definitions of functions and variables.
  3513. if (Tag)
  3514. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3515. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
  3516. else
  3517. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  3518. // Don't emit warnings after this error.
  3519. return TagD;
  3520. }
  3521. if (DS.isConceptSpecified()) {
  3522. // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
  3523. // either a function concept and its definition or a variable concept and
  3524. // its initializer.
  3525. Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
  3526. return TagD;
  3527. }
  3528. DiagnoseFunctionSpecifiers(DS);
  3529. if (DS.isFriendSpecified()) {
  3530. // If we're dealing with a decl but not a TagDecl, assume that
  3531. // whatever routines created it handled the friendship aspect.
  3532. if (TagD && !Tag)
  3533. return nullptr;
  3534. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3535. }
  3536. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3537. bool IsExplicitSpecialization =
  3538. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3539. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3540. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  3541. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  3542. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3543. // nested-name-specifier unless it is an explicit instantiation
  3544. // or an explicit specialization.
  3545. //
  3546. // FIXME: We allow class template partial specializations here too, per the
  3547. // obvious intent of DR1819.
  3548. //
  3549. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3550. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3551. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3552. return nullptr;
  3553. }
  3554. // Track whether this decl-specifier declares anything.
  3555. bool DeclaresAnything = true;
  3556. // Handle anonymous struct definitions.
  3557. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3558. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3559. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3560. if (getLangOpts().CPlusPlus ||
  3561. Record->getDeclContext()->isRecord()) {
  3562. // If CurContext is a DeclContext that can contain statements,
  3563. // RecursiveASTVisitor won't visit the decls that
  3564. // BuildAnonymousStructOrUnion() will put into CurContext.
  3565. // Also store them here so that they can be part of the
  3566. // DeclStmt that gets created in this case.
  3567. // FIXME: Also return the IndirectFieldDecls created by
  3568. // BuildAnonymousStructOr union, for the same reason?
  3569. if (CurContext->isFunctionOrMethod())
  3570. AnonRecord = Record;
  3571. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3572. Context.getPrintingPolicy());
  3573. }
  3574. DeclaresAnything = false;
  3575. }
  3576. }
  3577. // C11 6.7.2.1p2:
  3578. // A struct-declaration that does not declare an anonymous structure or
  3579. // anonymous union shall contain a struct-declarator-list.
  3580. //
  3581. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3582. // did not permit a struct-declaration without a struct-declarator-list.
  3583. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3584. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3585. // Check for Microsoft C extension: anonymous struct/union member.
  3586. // Handle 2 kinds of anonymous struct/union:
  3587. // struct STRUCT;
  3588. // union UNION;
  3589. // and
  3590. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3591. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3592. if ((Tag && Tag->getDeclName()) ||
  3593. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3594. RecordDecl *Record = nullptr;
  3595. if (Tag)
  3596. Record = dyn_cast<RecordDecl>(Tag);
  3597. else if (const RecordType *RT =
  3598. DS.getRepAsType().get()->getAsStructureType())
  3599. Record = RT->getDecl();
  3600. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3601. Record = UT->getDecl();
  3602. if (Record && getLangOpts().MicrosoftExt) {
  3603. Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
  3604. << Record->isUnion() << DS.getSourceRange();
  3605. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3606. }
  3607. DeclaresAnything = false;
  3608. }
  3609. }
  3610. // Skip all the checks below if we have a type error.
  3611. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3612. (TagD && TagD->isInvalidDecl()))
  3613. return TagD;
  3614. if (getLangOpts().CPlusPlus &&
  3615. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3616. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  3617. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  3618. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  3619. DeclaresAnything = false;
  3620. if (!DS.isMissingDeclaratorOk()) {
  3621. // Customize diagnostic for a typedef missing a name.
  3622. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  3623. Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
  3624. << DS.getSourceRange();
  3625. else
  3626. DeclaresAnything = false;
  3627. }
  3628. if (DS.isModulePrivateSpecified() &&
  3629. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  3630. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  3631. << Tag->getTagKind()
  3632. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  3633. ActOnDocumentableDecl(TagD);
  3634. // C 6.7/2:
  3635. // A declaration [...] shall declare at least a declarator [...], a tag,
  3636. // or the members of an enumeration.
  3637. // C++ [dcl.dcl]p3:
  3638. // [If there are no declarators], and except for the declaration of an
  3639. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  3640. // names into the program, or shall redeclare a name introduced by a
  3641. // previous declaration.
  3642. if (!DeclaresAnything) {
  3643. // In C, we allow this as a (popular) extension / bug. Don't bother
  3644. // producing further diagnostics for redundant qualifiers after this.
  3645. Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
  3646. return TagD;
  3647. }
  3648. // C++ [dcl.stc]p1:
  3649. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  3650. // init-declarator-list of the declaration shall not be empty.
  3651. // C++ [dcl.fct.spec]p1:
  3652. // If a cv-qualifier appears in a decl-specifier-seq, the
  3653. // init-declarator-list of the declaration shall not be empty.
  3654. //
  3655. // Spurious qualifiers here appear to be valid in C.
  3656. unsigned DiagID = diag::warn_standalone_specifier;
  3657. if (getLangOpts().CPlusPlus)
  3658. DiagID = diag::ext_standalone_specifier;
  3659. // Note that a linkage-specification sets a storage class, but
  3660. // 'extern "C" struct foo;' is actually valid and not theoretically
  3661. // useless.
  3662. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3663. if (SCS == DeclSpec::SCS_mutable)
  3664. // Since mutable is not a viable storage class specifier in C, there is
  3665. // no reason to treat it as an extension. Instead, diagnose as an error.
  3666. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  3667. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  3668. Diag(DS.getStorageClassSpecLoc(), DiagID)
  3669. << DeclSpec::getSpecifierName(SCS);
  3670. }
  3671. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  3672. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  3673. << DeclSpec::getSpecifierName(TSCS);
  3674. if (DS.getTypeQualifiers()) {
  3675. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3676. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  3677. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3678. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  3679. // Restrict is covered above.
  3680. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3681. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  3682. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  3683. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  3684. }
  3685. // Warn about ignored type attributes, for example:
  3686. // __attribute__((aligned)) struct A;
  3687. // Attributes should be placed after tag to apply to type declaration.
  3688. if (!DS.getAttributes().empty()) {
  3689. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  3690. if (TypeSpecType == DeclSpec::TST_class ||
  3691. TypeSpecType == DeclSpec::TST_struct ||
  3692. TypeSpecType == DeclSpec::TST_interface ||
  3693. TypeSpecType == DeclSpec::TST_union ||
  3694. TypeSpecType == DeclSpec::TST_enum) {
  3695. for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
  3696. attrs = attrs->getNext())
  3697. Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
  3698. << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  3699. }
  3700. }
  3701. return TagD;
  3702. }
  3703. /// We are trying to inject an anonymous member into the given scope;
  3704. /// check if there's an existing declaration that can't be overloaded.
  3705. ///
  3706. /// \return true if this is a forbidden redeclaration
  3707. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  3708. Scope *S,
  3709. DeclContext *Owner,
  3710. DeclarationName Name,
  3711. SourceLocation NameLoc,
  3712. bool IsUnion) {
  3713. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  3714. Sema::ForRedeclaration);
  3715. if (!SemaRef.LookupName(R, S)) return false;
  3716. // Pick a representative declaration.
  3717. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  3718. assert(PrevDecl && "Expected a non-null Decl");
  3719. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  3720. return false;
  3721. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  3722. << IsUnion << Name;
  3723. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  3724. return true;
  3725. }
  3726. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  3727. /// anonymous struct or union AnonRecord into the owning context Owner
  3728. /// and scope S. This routine will be invoked just after we realize
  3729. /// that an unnamed union or struct is actually an anonymous union or
  3730. /// struct, e.g.,
  3731. ///
  3732. /// @code
  3733. /// union {
  3734. /// int i;
  3735. /// float f;
  3736. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  3737. /// // f into the surrounding scope.x
  3738. /// @endcode
  3739. ///
  3740. /// This routine is recursive, injecting the names of nested anonymous
  3741. /// structs/unions into the owning context and scope as well.
  3742. static bool
  3743. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  3744. RecordDecl *AnonRecord, AccessSpecifier AS,
  3745. SmallVectorImpl<NamedDecl *> &Chaining) {
  3746. bool Invalid = false;
  3747. // Look every FieldDecl and IndirectFieldDecl with a name.
  3748. for (auto *D : AnonRecord->decls()) {
  3749. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  3750. cast<NamedDecl>(D)->getDeclName()) {
  3751. ValueDecl *VD = cast<ValueDecl>(D);
  3752. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  3753. VD->getLocation(),
  3754. AnonRecord->isUnion())) {
  3755. // C++ [class.union]p2:
  3756. // The names of the members of an anonymous union shall be
  3757. // distinct from the names of any other entity in the
  3758. // scope in which the anonymous union is declared.
  3759. Invalid = true;
  3760. } else {
  3761. // C++ [class.union]p2:
  3762. // For the purpose of name lookup, after the anonymous union
  3763. // definition, the members of the anonymous union are
  3764. // considered to have been defined in the scope in which the
  3765. // anonymous union is declared.
  3766. unsigned OldChainingSize = Chaining.size();
  3767. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  3768. Chaining.append(IF->chain_begin(), IF->chain_end());
  3769. else
  3770. Chaining.push_back(VD);
  3771. assert(Chaining.size() >= 2);
  3772. NamedDecl **NamedChain =
  3773. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  3774. for (unsigned i = 0; i < Chaining.size(); i++)
  3775. NamedChain[i] = Chaining[i];
  3776. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  3777. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  3778. VD->getType(), {NamedChain, Chaining.size()});
  3779. for (const auto *Attr : VD->attrs())
  3780. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  3781. IndirectField->setAccess(AS);
  3782. IndirectField->setImplicit();
  3783. SemaRef.PushOnScopeChains(IndirectField, S);
  3784. // That includes picking up the appropriate access specifier.
  3785. if (AS != AS_none) IndirectField->setAccess(AS);
  3786. Chaining.resize(OldChainingSize);
  3787. }
  3788. }
  3789. }
  3790. return Invalid;
  3791. }
  3792. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  3793. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  3794. /// illegal input values are mapped to SC_None.
  3795. static StorageClass
  3796. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  3797. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  3798. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  3799. "Parser allowed 'typedef' as storage class VarDecl.");
  3800. switch (StorageClassSpec) {
  3801. case DeclSpec::SCS_unspecified: return SC_None;
  3802. case DeclSpec::SCS_extern:
  3803. if (DS.isExternInLinkageSpec())
  3804. return SC_None;
  3805. return SC_Extern;
  3806. case DeclSpec::SCS_static: return SC_Static;
  3807. case DeclSpec::SCS_auto: return SC_Auto;
  3808. case DeclSpec::SCS_register: return SC_Register;
  3809. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  3810. // Illegal SCSs map to None: error reporting is up to the caller.
  3811. case DeclSpec::SCS_mutable: // Fall through.
  3812. case DeclSpec::SCS_typedef: return SC_None;
  3813. }
  3814. llvm_unreachable("unknown storage class specifier");
  3815. }
  3816. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  3817. assert(Record->hasInClassInitializer());
  3818. for (const auto *I : Record->decls()) {
  3819. const auto *FD = dyn_cast<FieldDecl>(I);
  3820. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  3821. FD = IFD->getAnonField();
  3822. if (FD && FD->hasInClassInitializer())
  3823. return FD->getLocation();
  3824. }
  3825. llvm_unreachable("couldn't find in-class initializer");
  3826. }
  3827. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3828. SourceLocation DefaultInitLoc) {
  3829. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3830. return;
  3831. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  3832. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  3833. }
  3834. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3835. CXXRecordDecl *AnonUnion) {
  3836. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3837. return;
  3838. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  3839. }
  3840. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  3841. /// anonymous structure or union. Anonymous unions are a C++ feature
  3842. /// (C++ [class.union]) and a C11 feature; anonymous structures
  3843. /// are a C11 feature and GNU C++ extension.
  3844. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  3845. AccessSpecifier AS,
  3846. RecordDecl *Record,
  3847. const PrintingPolicy &Policy) {
  3848. DeclContext *Owner = Record->getDeclContext();
  3849. // Diagnose whether this anonymous struct/union is an extension.
  3850. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  3851. Diag(Record->getLocation(), diag::ext_anonymous_union);
  3852. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  3853. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  3854. else if (!Record->isUnion() && !getLangOpts().C11)
  3855. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  3856. // C and C++ require different kinds of checks for anonymous
  3857. // structs/unions.
  3858. bool Invalid = false;
  3859. if (getLangOpts().CPlusPlus) {
  3860. const char *PrevSpec = nullptr;
  3861. unsigned DiagID;
  3862. if (Record->isUnion()) {
  3863. // C++ [class.union]p6:
  3864. // Anonymous unions declared in a named namespace or in the
  3865. // global namespace shall be declared static.
  3866. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  3867. (isa<TranslationUnitDecl>(Owner) ||
  3868. (isa<NamespaceDecl>(Owner) &&
  3869. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  3870. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  3871. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  3872. // Recover by adding 'static'.
  3873. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  3874. PrevSpec, DiagID, Policy);
  3875. }
  3876. // C++ [class.union]p6:
  3877. // A storage class is not allowed in a declaration of an
  3878. // anonymous union in a class scope.
  3879. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  3880. isa<RecordDecl>(Owner)) {
  3881. Diag(DS.getStorageClassSpecLoc(),
  3882. diag::err_anonymous_union_with_storage_spec)
  3883. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  3884. // Recover by removing the storage specifier.
  3885. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  3886. SourceLocation(),
  3887. PrevSpec, DiagID, Context.getPrintingPolicy());
  3888. }
  3889. }
  3890. // Ignore const/volatile/restrict qualifiers.
  3891. if (DS.getTypeQualifiers()) {
  3892. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3893. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  3894. << Record->isUnion() << "const"
  3895. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  3896. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3897. Diag(DS.getVolatileSpecLoc(),
  3898. diag::ext_anonymous_struct_union_qualified)
  3899. << Record->isUnion() << "volatile"
  3900. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  3901. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  3902. Diag(DS.getRestrictSpecLoc(),
  3903. diag::ext_anonymous_struct_union_qualified)
  3904. << Record->isUnion() << "restrict"
  3905. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  3906. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3907. Diag(DS.getAtomicSpecLoc(),
  3908. diag::ext_anonymous_struct_union_qualified)
  3909. << Record->isUnion() << "_Atomic"
  3910. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  3911. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  3912. Diag(DS.getUnalignedSpecLoc(),
  3913. diag::ext_anonymous_struct_union_qualified)
  3914. << Record->isUnion() << "__unaligned"
  3915. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  3916. DS.ClearTypeQualifiers();
  3917. }
  3918. // C++ [class.union]p2:
  3919. // The member-specification of an anonymous union shall only
  3920. // define non-static data members. [Note: nested types and
  3921. // functions cannot be declared within an anonymous union. ]
  3922. for (auto *Mem : Record->decls()) {
  3923. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  3924. // C++ [class.union]p3:
  3925. // An anonymous union shall not have private or protected
  3926. // members (clause 11).
  3927. assert(FD->getAccess() != AS_none);
  3928. if (FD->getAccess() != AS_public) {
  3929. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  3930. << Record->isUnion() << (FD->getAccess() == AS_protected);
  3931. Invalid = true;
  3932. }
  3933. // C++ [class.union]p1
  3934. // An object of a class with a non-trivial constructor, a non-trivial
  3935. // copy constructor, a non-trivial destructor, or a non-trivial copy
  3936. // assignment operator cannot be a member of a union, nor can an
  3937. // array of such objects.
  3938. if (CheckNontrivialField(FD))
  3939. Invalid = true;
  3940. } else if (Mem->isImplicit()) {
  3941. // Any implicit members are fine.
  3942. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  3943. // This is a type that showed up in an
  3944. // elaborated-type-specifier inside the anonymous struct or
  3945. // union, but which actually declares a type outside of the
  3946. // anonymous struct or union. It's okay.
  3947. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  3948. if (!MemRecord->isAnonymousStructOrUnion() &&
  3949. MemRecord->getDeclName()) {
  3950. // Visual C++ allows type definition in anonymous struct or union.
  3951. if (getLangOpts().MicrosoftExt)
  3952. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  3953. << Record->isUnion();
  3954. else {
  3955. // This is a nested type declaration.
  3956. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  3957. << Record->isUnion();
  3958. Invalid = true;
  3959. }
  3960. } else {
  3961. // This is an anonymous type definition within another anonymous type.
  3962. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  3963. // not part of standard C++.
  3964. Diag(MemRecord->getLocation(),
  3965. diag::ext_anonymous_record_with_anonymous_type)
  3966. << Record->isUnion();
  3967. }
  3968. } else if (isa<AccessSpecDecl>(Mem)) {
  3969. // Any access specifier is fine.
  3970. } else if (isa<StaticAssertDecl>(Mem)) {
  3971. // In C++1z, static_assert declarations are also fine.
  3972. } else {
  3973. // We have something that isn't a non-static data
  3974. // member. Complain about it.
  3975. unsigned DK = diag::err_anonymous_record_bad_member;
  3976. if (isa<TypeDecl>(Mem))
  3977. DK = diag::err_anonymous_record_with_type;
  3978. else if (isa<FunctionDecl>(Mem))
  3979. DK = diag::err_anonymous_record_with_function;
  3980. else if (isa<VarDecl>(Mem))
  3981. DK = diag::err_anonymous_record_with_static;
  3982. // Visual C++ allows type definition in anonymous struct or union.
  3983. if (getLangOpts().MicrosoftExt &&
  3984. DK == diag::err_anonymous_record_with_type)
  3985. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  3986. << Record->isUnion();
  3987. else {
  3988. Diag(Mem->getLocation(), DK) << Record->isUnion();
  3989. Invalid = true;
  3990. }
  3991. }
  3992. }
  3993. // C++11 [class.union]p8 (DR1460):
  3994. // At most one variant member of a union may have a
  3995. // brace-or-equal-initializer.
  3996. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  3997. Owner->isRecord())
  3998. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  3999. cast<CXXRecordDecl>(Record));
  4000. }
  4001. if (!Record->isUnion() && !Owner->isRecord()) {
  4002. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  4003. << getLangOpts().CPlusPlus;
  4004. Invalid = true;
  4005. }
  4006. // Mock up a declarator.
  4007. Declarator Dc(DS, Declarator::MemberContext);
  4008. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4009. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  4010. // Create a declaration for this anonymous struct/union.
  4011. NamedDecl *Anon = nullptr;
  4012. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  4013. Anon = FieldDecl::Create(Context, OwningClass,
  4014. DS.getLocStart(),
  4015. Record->getLocation(),
  4016. /*IdentifierInfo=*/nullptr,
  4017. Context.getTypeDeclType(Record),
  4018. TInfo,
  4019. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4020. /*InitStyle=*/ICIS_NoInit);
  4021. Anon->setAccess(AS);
  4022. if (getLangOpts().CPlusPlus)
  4023. FieldCollector->Add(cast<FieldDecl>(Anon));
  4024. } else {
  4025. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  4026. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  4027. if (SCSpec == DeclSpec::SCS_mutable) {
  4028. // mutable can only appear on non-static class members, so it's always
  4029. // an error here
  4030. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  4031. Invalid = true;
  4032. SC = SC_None;
  4033. }
  4034. Anon = VarDecl::Create(Context, Owner,
  4035. DS.getLocStart(),
  4036. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  4037. Context.getTypeDeclType(Record),
  4038. TInfo, SC);
  4039. // Default-initialize the implicit variable. This initialization will be
  4040. // trivial in almost all cases, except if a union member has an in-class
  4041. // initializer:
  4042. // union { int n = 0; };
  4043. ActOnUninitializedDecl(Anon);
  4044. }
  4045. Anon->setImplicit();
  4046. // Mark this as an anonymous struct/union type.
  4047. Record->setAnonymousStructOrUnion(true);
  4048. // Add the anonymous struct/union object to the current
  4049. // context. We'll be referencing this object when we refer to one of
  4050. // its members.
  4051. Owner->addDecl(Anon);
  4052. // Inject the members of the anonymous struct/union into the owning
  4053. // context and into the identifier resolver chain for name lookup
  4054. // purposes.
  4055. SmallVector<NamedDecl*, 2> Chain;
  4056. Chain.push_back(Anon);
  4057. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4058. Invalid = true;
  4059. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4060. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4061. Decl *ManglingContextDecl;
  4062. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  4063. NewVD->getDeclContext(), ManglingContextDecl)) {
  4064. Context.setManglingNumber(
  4065. NewVD, MCtx->getManglingNumber(
  4066. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4067. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4068. }
  4069. }
  4070. }
  4071. if (Invalid)
  4072. Anon->setInvalidDecl();
  4073. return Anon;
  4074. }
  4075. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4076. /// Microsoft C anonymous structure.
  4077. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4078. /// Example:
  4079. ///
  4080. /// struct A { int a; };
  4081. /// struct B { struct A; int b; };
  4082. ///
  4083. /// void foo() {
  4084. /// B var;
  4085. /// var.a = 3;
  4086. /// }
  4087. ///
  4088. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4089. RecordDecl *Record) {
  4090. assert(Record && "expected a record!");
  4091. // Mock up a declarator.
  4092. Declarator Dc(DS, Declarator::TypeNameContext);
  4093. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4094. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4095. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4096. QualType RecTy = Context.getTypeDeclType(Record);
  4097. // Create a declaration for this anonymous struct.
  4098. NamedDecl *Anon = FieldDecl::Create(Context,
  4099. ParentDecl,
  4100. DS.getLocStart(),
  4101. DS.getLocStart(),
  4102. /*IdentifierInfo=*/nullptr,
  4103. RecTy,
  4104. TInfo,
  4105. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4106. /*InitStyle=*/ICIS_NoInit);
  4107. Anon->setImplicit();
  4108. // Add the anonymous struct object to the current context.
  4109. CurContext->addDecl(Anon);
  4110. // Inject the members of the anonymous struct into the current
  4111. // context and into the identifier resolver chain for name lookup
  4112. // purposes.
  4113. SmallVector<NamedDecl*, 2> Chain;
  4114. Chain.push_back(Anon);
  4115. RecordDecl *RecordDef = Record->getDefinition();
  4116. if (RequireCompleteType(Anon->getLocation(), RecTy,
  4117. diag::err_field_incomplete) ||
  4118. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4119. AS_none, Chain)) {
  4120. Anon->setInvalidDecl();
  4121. ParentDecl->setInvalidDecl();
  4122. }
  4123. return Anon;
  4124. }
  4125. /// GetNameForDeclarator - Determine the full declaration name for the
  4126. /// given Declarator.
  4127. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4128. return GetNameFromUnqualifiedId(D.getName());
  4129. }
  4130. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  4131. DeclarationNameInfo
  4132. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4133. DeclarationNameInfo NameInfo;
  4134. NameInfo.setLoc(Name.StartLocation);
  4135. switch (Name.getKind()) {
  4136. case UnqualifiedId::IK_ImplicitSelfParam:
  4137. case UnqualifiedId::IK_Identifier:
  4138. NameInfo.setName(Name.Identifier);
  4139. NameInfo.setLoc(Name.StartLocation);
  4140. return NameInfo;
  4141. case UnqualifiedId::IK_DeductionGuideName: {
  4142. // C++ [temp.deduct.guide]p3:
  4143. // The simple-template-id shall name a class template specialization.
  4144. // The template-name shall be the same identifier as the template-name
  4145. // of the simple-template-id.
  4146. // These together intend to imply that the template-name shall name a
  4147. // class template.
  4148. // FIXME: template<typename T> struct X {};
  4149. // template<typename T> using Y = X<T>;
  4150. // Y(int) -> Y<int>;
  4151. // satisfies these rules but does not name a class template.
  4152. TemplateName TN = Name.TemplateName.get().get();
  4153. auto *Template = TN.getAsTemplateDecl();
  4154. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  4155. Diag(Name.StartLocation,
  4156. diag::err_deduction_guide_name_not_class_template)
  4157. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  4158. if (Template)
  4159. Diag(Template->getLocation(), diag::note_template_decl_here);
  4160. return DeclarationNameInfo();
  4161. }
  4162. NameInfo.setName(
  4163. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  4164. NameInfo.setLoc(Name.StartLocation);
  4165. return NameInfo;
  4166. }
  4167. case UnqualifiedId::IK_OperatorFunctionId:
  4168. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4169. Name.OperatorFunctionId.Operator));
  4170. NameInfo.setLoc(Name.StartLocation);
  4171. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  4172. = Name.OperatorFunctionId.SymbolLocations[0];
  4173. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  4174. = Name.EndLocation.getRawEncoding();
  4175. return NameInfo;
  4176. case UnqualifiedId::IK_LiteralOperatorId:
  4177. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4178. Name.Identifier));
  4179. NameInfo.setLoc(Name.StartLocation);
  4180. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4181. return NameInfo;
  4182. case UnqualifiedId::IK_ConversionFunctionId: {
  4183. TypeSourceInfo *TInfo;
  4184. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4185. if (Ty.isNull())
  4186. return DeclarationNameInfo();
  4187. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4188. Context.getCanonicalType(Ty)));
  4189. NameInfo.setLoc(Name.StartLocation);
  4190. NameInfo.setNamedTypeInfo(TInfo);
  4191. return NameInfo;
  4192. }
  4193. case UnqualifiedId::IK_ConstructorName: {
  4194. TypeSourceInfo *TInfo;
  4195. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4196. if (Ty.isNull())
  4197. return DeclarationNameInfo();
  4198. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4199. Context.getCanonicalType(Ty)));
  4200. NameInfo.setLoc(Name.StartLocation);
  4201. NameInfo.setNamedTypeInfo(TInfo);
  4202. return NameInfo;
  4203. }
  4204. case UnqualifiedId::IK_ConstructorTemplateId: {
  4205. // In well-formed code, we can only have a constructor
  4206. // template-id that refers to the current context, so go there
  4207. // to find the actual type being constructed.
  4208. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4209. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4210. return DeclarationNameInfo();
  4211. // Determine the type of the class being constructed.
  4212. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4213. // FIXME: Check two things: that the template-id names the same type as
  4214. // CurClassType, and that the template-id does not occur when the name
  4215. // was qualified.
  4216. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4217. Context.getCanonicalType(CurClassType)));
  4218. NameInfo.setLoc(Name.StartLocation);
  4219. // FIXME: should we retrieve TypeSourceInfo?
  4220. NameInfo.setNamedTypeInfo(nullptr);
  4221. return NameInfo;
  4222. }
  4223. case UnqualifiedId::IK_DestructorName: {
  4224. TypeSourceInfo *TInfo;
  4225. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4226. if (Ty.isNull())
  4227. return DeclarationNameInfo();
  4228. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4229. Context.getCanonicalType(Ty)));
  4230. NameInfo.setLoc(Name.StartLocation);
  4231. NameInfo.setNamedTypeInfo(TInfo);
  4232. return NameInfo;
  4233. }
  4234. case UnqualifiedId::IK_TemplateId: {
  4235. TemplateName TName = Name.TemplateId->Template.get();
  4236. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4237. return Context.getNameForTemplate(TName, TNameLoc);
  4238. }
  4239. } // switch (Name.getKind())
  4240. llvm_unreachable("Unknown name kind");
  4241. }
  4242. static QualType getCoreType(QualType Ty) {
  4243. do {
  4244. if (Ty->isPointerType() || Ty->isReferenceType())
  4245. Ty = Ty->getPointeeType();
  4246. else if (Ty->isArrayType())
  4247. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4248. else
  4249. return Ty.withoutLocalFastQualifiers();
  4250. } while (true);
  4251. }
  4252. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4253. /// and Definition have "nearly" matching parameters. This heuristic is
  4254. /// used to improve diagnostics in the case where an out-of-line function
  4255. /// definition doesn't match any declaration within the class or namespace.
  4256. /// Also sets Params to the list of indices to the parameters that differ
  4257. /// between the declaration and the definition. If hasSimilarParameters
  4258. /// returns true and Params is empty, then all of the parameters match.
  4259. static bool hasSimilarParameters(ASTContext &Context,
  4260. FunctionDecl *Declaration,
  4261. FunctionDecl *Definition,
  4262. SmallVectorImpl<unsigned> &Params) {
  4263. Params.clear();
  4264. if (Declaration->param_size() != Definition->param_size())
  4265. return false;
  4266. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4267. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4268. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4269. // The parameter types are identical
  4270. if (Context.hasSameType(DefParamTy, DeclParamTy))
  4271. continue;
  4272. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4273. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4274. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4275. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4276. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4277. (DeclTyName && DeclTyName == DefTyName))
  4278. Params.push_back(Idx);
  4279. else // The two parameters aren't even close
  4280. return false;
  4281. }
  4282. return true;
  4283. }
  4284. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4285. /// declarator needs to be rebuilt in the current instantiation.
  4286. /// Any bits of declarator which appear before the name are valid for
  4287. /// consideration here. That's specifically the type in the decl spec
  4288. /// and the base type in any member-pointer chunks.
  4289. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4290. DeclarationName Name) {
  4291. // The types we specifically need to rebuild are:
  4292. // - typenames, typeofs, and decltypes
  4293. // - types which will become injected class names
  4294. // Of course, we also need to rebuild any type referencing such a
  4295. // type. It's safest to just say "dependent", but we call out a
  4296. // few cases here.
  4297. DeclSpec &DS = D.getMutableDeclSpec();
  4298. switch (DS.getTypeSpecType()) {
  4299. case DeclSpec::TST_typename:
  4300. case DeclSpec::TST_typeofType:
  4301. case DeclSpec::TST_underlyingType:
  4302. case DeclSpec::TST_atomic: {
  4303. // Grab the type from the parser.
  4304. TypeSourceInfo *TSI = nullptr;
  4305. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4306. if (T.isNull() || !T->isDependentType()) break;
  4307. // Make sure there's a type source info. This isn't really much
  4308. // of a waste; most dependent types should have type source info
  4309. // attached already.
  4310. if (!TSI)
  4311. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4312. // Rebuild the type in the current instantiation.
  4313. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4314. if (!TSI) return true;
  4315. // Store the new type back in the decl spec.
  4316. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4317. DS.UpdateTypeRep(LocType);
  4318. break;
  4319. }
  4320. case DeclSpec::TST_decltype:
  4321. case DeclSpec::TST_typeofExpr: {
  4322. Expr *E = DS.getRepAsExpr();
  4323. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4324. if (Result.isInvalid()) return true;
  4325. DS.UpdateExprRep(Result.get());
  4326. break;
  4327. }
  4328. default:
  4329. // Nothing to do for these decl specs.
  4330. break;
  4331. }
  4332. // It doesn't matter what order we do this in.
  4333. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4334. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4335. // The only type information in the declarator which can come
  4336. // before the declaration name is the base type of a member
  4337. // pointer.
  4338. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4339. continue;
  4340. // Rebuild the scope specifier in-place.
  4341. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4342. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4343. return true;
  4344. }
  4345. return false;
  4346. }
  4347. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4348. D.setFunctionDefinitionKind(FDK_Declaration);
  4349. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4350. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4351. Dcl && Dcl->getDeclContext()->isFileContext())
  4352. Dcl->setTopLevelDeclInObjCContainer();
  4353. if (getLangOpts().OpenCL)
  4354. setCurrentOpenCLExtensionForDecl(Dcl);
  4355. return Dcl;
  4356. }
  4357. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4358. /// If T is the name of a class, then each of the following shall have a
  4359. /// name different from T:
  4360. /// - every static data member of class T;
  4361. /// - every member function of class T
  4362. /// - every member of class T that is itself a type;
  4363. /// \returns true if the declaration name violates these rules.
  4364. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4365. DeclarationNameInfo NameInfo) {
  4366. DeclarationName Name = NameInfo.getName();
  4367. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  4368. while (Record && Record->isAnonymousStructOrUnion())
  4369. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  4370. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  4371. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4372. return true;
  4373. }
  4374. return false;
  4375. }
  4376. /// \brief Diagnose a declaration whose declarator-id has the given
  4377. /// nested-name-specifier.
  4378. ///
  4379. /// \param SS The nested-name-specifier of the declarator-id.
  4380. ///
  4381. /// \param DC The declaration context to which the nested-name-specifier
  4382. /// resolves.
  4383. ///
  4384. /// \param Name The name of the entity being declared.
  4385. ///
  4386. /// \param Loc The location of the name of the entity being declared.
  4387. ///
  4388. /// \returns true if we cannot safely recover from this error, false otherwise.
  4389. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4390. DeclarationName Name,
  4391. SourceLocation Loc) {
  4392. DeclContext *Cur = CurContext;
  4393. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4394. Cur = Cur->getParent();
  4395. // If the user provided a superfluous scope specifier that refers back to the
  4396. // class in which the entity is already declared, diagnose and ignore it.
  4397. //
  4398. // class X {
  4399. // void X::f();
  4400. // };
  4401. //
  4402. // Note, it was once ill-formed to give redundant qualification in all
  4403. // contexts, but that rule was removed by DR482.
  4404. if (Cur->Equals(DC)) {
  4405. if (Cur->isRecord()) {
  4406. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4407. : diag::err_member_extra_qualification)
  4408. << Name << FixItHint::CreateRemoval(SS.getRange());
  4409. SS.clear();
  4410. } else {
  4411. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4412. }
  4413. return false;
  4414. }
  4415. // Check whether the qualifying scope encloses the scope of the original
  4416. // declaration.
  4417. if (!Cur->Encloses(DC)) {
  4418. if (Cur->isRecord())
  4419. Diag(Loc, diag::err_member_qualification)
  4420. << Name << SS.getRange();
  4421. else if (isa<TranslationUnitDecl>(DC))
  4422. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4423. << Name << SS.getRange();
  4424. else if (isa<FunctionDecl>(Cur))
  4425. Diag(Loc, diag::err_invalid_declarator_in_function)
  4426. << Name << SS.getRange();
  4427. else if (isa<BlockDecl>(Cur))
  4428. Diag(Loc, diag::err_invalid_declarator_in_block)
  4429. << Name << SS.getRange();
  4430. else
  4431. Diag(Loc, diag::err_invalid_declarator_scope)
  4432. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4433. return true;
  4434. }
  4435. if (Cur->isRecord()) {
  4436. // Cannot qualify members within a class.
  4437. Diag(Loc, diag::err_member_qualification)
  4438. << Name << SS.getRange();
  4439. SS.clear();
  4440. // C++ constructors and destructors with incorrect scopes can break
  4441. // our AST invariants by having the wrong underlying types. If
  4442. // that's the case, then drop this declaration entirely.
  4443. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4444. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4445. !Context.hasSameType(Name.getCXXNameType(),
  4446. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4447. return true;
  4448. return false;
  4449. }
  4450. // C++11 [dcl.meaning]p1:
  4451. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4452. // not begin with a decltype-specifer"
  4453. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4454. while (SpecLoc.getPrefix())
  4455. SpecLoc = SpecLoc.getPrefix();
  4456. if (dyn_cast_or_null<DecltypeType>(
  4457. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4458. Diag(Loc, diag::err_decltype_in_declarator)
  4459. << SpecLoc.getTypeLoc().getSourceRange();
  4460. return false;
  4461. }
  4462. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4463. MultiTemplateParamsArg TemplateParamLists) {
  4464. // TODO: consider using NameInfo for diagnostic.
  4465. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4466. DeclarationName Name = NameInfo.getName();
  4467. // All of these full declarators require an identifier. If it doesn't have
  4468. // one, the ParsedFreeStandingDeclSpec action should be used.
  4469. if (D.isDecompositionDeclarator()) {
  4470. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  4471. } else if (!Name) {
  4472. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4473. Diag(D.getDeclSpec().getLocStart(),
  4474. diag::err_declarator_need_ident)
  4475. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4476. return nullptr;
  4477. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4478. return nullptr;
  4479. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4480. // we find one that is.
  4481. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4482. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4483. S = S->getParent();
  4484. DeclContext *DC = CurContext;
  4485. if (D.getCXXScopeSpec().isInvalid())
  4486. D.setInvalidType();
  4487. else if (D.getCXXScopeSpec().isSet()) {
  4488. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4489. UPPC_DeclarationQualifier))
  4490. return nullptr;
  4491. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4492. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4493. if (!DC || isa<EnumDecl>(DC)) {
  4494. // If we could not compute the declaration context, it's because the
  4495. // declaration context is dependent but does not refer to a class,
  4496. // class template, or class template partial specialization. Complain
  4497. // and return early, to avoid the coming semantic disaster.
  4498. Diag(D.getIdentifierLoc(),
  4499. diag::err_template_qualified_declarator_no_match)
  4500. << D.getCXXScopeSpec().getScopeRep()
  4501. << D.getCXXScopeSpec().getRange();
  4502. return nullptr;
  4503. }
  4504. bool IsDependentContext = DC->isDependentContext();
  4505. if (!IsDependentContext &&
  4506. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4507. return nullptr;
  4508. // If a class is incomplete, do not parse entities inside it.
  4509. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4510. Diag(D.getIdentifierLoc(),
  4511. diag::err_member_def_undefined_record)
  4512. << Name << DC << D.getCXXScopeSpec().getRange();
  4513. return nullptr;
  4514. }
  4515. if (!D.getDeclSpec().isFriendSpecified()) {
  4516. if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
  4517. Name, D.getIdentifierLoc())) {
  4518. if (DC->isRecord())
  4519. return nullptr;
  4520. D.setInvalidType();
  4521. }
  4522. }
  4523. // Check whether we need to rebuild the type of the given
  4524. // declaration in the current instantiation.
  4525. if (EnteringContext && IsDependentContext &&
  4526. TemplateParamLists.size() != 0) {
  4527. ContextRAII SavedContext(*this, DC);
  4528. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4529. D.setInvalidType();
  4530. }
  4531. }
  4532. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4533. QualType R = TInfo->getType();
  4534. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4535. // If this is a typedef, we'll end up spewing multiple diagnostics.
  4536. // Just return early; it's safer. If this is a function, let the
  4537. // "constructor cannot have a return type" diagnostic handle it.
  4538. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4539. return nullptr;
  4540. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4541. UPPC_DeclarationType))
  4542. D.setInvalidType();
  4543. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4544. ForRedeclaration);
  4545. // See if this is a redefinition of a variable in the same scope.
  4546. if (!D.getCXXScopeSpec().isSet()) {
  4547. bool IsLinkageLookup = false;
  4548. bool CreateBuiltins = false;
  4549. // If the declaration we're planning to build will be a function
  4550. // or object with linkage, then look for another declaration with
  4551. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4552. //
  4553. // If the declaration we're planning to build will be declared with
  4554. // external linkage in the translation unit, create any builtin with
  4555. // the same name.
  4556. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4557. /* Do nothing*/;
  4558. else if (CurContext->isFunctionOrMethod() &&
  4559. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4560. R->isFunctionType())) {
  4561. IsLinkageLookup = true;
  4562. CreateBuiltins =
  4563. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4564. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4565. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4566. CreateBuiltins = true;
  4567. if (IsLinkageLookup)
  4568. Previous.clear(LookupRedeclarationWithLinkage);
  4569. LookupName(Previous, S, CreateBuiltins);
  4570. } else { // Something like "int foo::x;"
  4571. LookupQualifiedName(Previous, DC);
  4572. // C++ [dcl.meaning]p1:
  4573. // When the declarator-id is qualified, the declaration shall refer to a
  4574. // previously declared member of the class or namespace to which the
  4575. // qualifier refers (or, in the case of a namespace, of an element of the
  4576. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4577. // thereof; [...]
  4578. //
  4579. // Note that we already checked the context above, and that we do not have
  4580. // enough information to make sure that Previous contains the declaration
  4581. // we want to match. For example, given:
  4582. //
  4583. // class X {
  4584. // void f();
  4585. // void f(float);
  4586. // };
  4587. //
  4588. // void X::f(int) { } // ill-formed
  4589. //
  4590. // In this case, Previous will point to the overload set
  4591. // containing the two f's declared in X, but neither of them
  4592. // matches.
  4593. // C++ [dcl.meaning]p1:
  4594. // [...] the member shall not merely have been introduced by a
  4595. // using-declaration in the scope of the class or namespace nominated by
  4596. // the nested-name-specifier of the declarator-id.
  4597. RemoveUsingDecls(Previous);
  4598. }
  4599. if (Previous.isSingleResult() &&
  4600. Previous.getFoundDecl()->isTemplateParameter()) {
  4601. // Maybe we will complain about the shadowed template parameter.
  4602. if (!D.isInvalidType())
  4603. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4604. Previous.getFoundDecl());
  4605. // Just pretend that we didn't see the previous declaration.
  4606. Previous.clear();
  4607. }
  4608. // In C++, the previous declaration we find might be a tag type
  4609. // (class or enum). In this case, the new declaration will hide the
  4610. // tag type. Note that this does does not apply if we're declaring a
  4611. // typedef (C++ [dcl.typedef]p4).
  4612. if (Previous.isSingleTagDecl() &&
  4613. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
  4614. Previous.clear();
  4615. // Check that there are no default arguments other than in the parameters
  4616. // of a function declaration (C++ only).
  4617. if (getLangOpts().CPlusPlus)
  4618. CheckExtraCXXDefaultArguments(D);
  4619. if (D.getDeclSpec().isConceptSpecified()) {
  4620. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  4621. // applied only to the definition of a function template or variable
  4622. // template, declared in namespace scope
  4623. if (!TemplateParamLists.size()) {
  4624. Diag(D.getDeclSpec().getConceptSpecLoc(),
  4625. diag:: err_concept_wrong_decl_kind);
  4626. return nullptr;
  4627. }
  4628. if (!DC->getRedeclContext()->isFileContext()) {
  4629. Diag(D.getIdentifierLoc(),
  4630. diag::err_concept_decls_may_only_appear_in_namespace_scope);
  4631. return nullptr;
  4632. }
  4633. }
  4634. NamedDecl *New;
  4635. bool AddToScope = true;
  4636. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  4637. if (TemplateParamLists.size()) {
  4638. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  4639. return nullptr;
  4640. }
  4641. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  4642. } else if (R->isFunctionType()) {
  4643. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  4644. TemplateParamLists,
  4645. AddToScope);
  4646. } else {
  4647. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  4648. AddToScope);
  4649. }
  4650. if (!New)
  4651. return nullptr;
  4652. // If this has an identifier and is not a function template specialization,
  4653. // add it to the scope stack.
  4654. if (New->getDeclName() && AddToScope) {
  4655. // Only make a locally-scoped extern declaration visible if it is the first
  4656. // declaration of this entity. Qualified lookup for such an entity should
  4657. // only find this declaration if there is no visible declaration of it.
  4658. bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
  4659. PushOnScopeChains(New, S, AddToContext);
  4660. if (!AddToContext)
  4661. CurContext->addHiddenDecl(New);
  4662. }
  4663. if (isInOpenMPDeclareTargetContext())
  4664. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  4665. return New;
  4666. }
  4667. /// Helper method to turn variable array types into constant array
  4668. /// types in certain situations which would otherwise be errors (for
  4669. /// GCC compatibility).
  4670. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  4671. ASTContext &Context,
  4672. bool &SizeIsNegative,
  4673. llvm::APSInt &Oversized) {
  4674. // This method tries to turn a variable array into a constant
  4675. // array even when the size isn't an ICE. This is necessary
  4676. // for compatibility with code that depends on gcc's buggy
  4677. // constant expression folding, like struct {char x[(int)(char*)2];}
  4678. SizeIsNegative = false;
  4679. Oversized = 0;
  4680. if (T->isDependentType())
  4681. return QualType();
  4682. QualifierCollector Qs;
  4683. const Type *Ty = Qs.strip(T);
  4684. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  4685. QualType Pointee = PTy->getPointeeType();
  4686. QualType FixedType =
  4687. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  4688. Oversized);
  4689. if (FixedType.isNull()) return FixedType;
  4690. FixedType = Context.getPointerType(FixedType);
  4691. return Qs.apply(Context, FixedType);
  4692. }
  4693. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  4694. QualType Inner = PTy->getInnerType();
  4695. QualType FixedType =
  4696. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  4697. Oversized);
  4698. if (FixedType.isNull()) return FixedType;
  4699. FixedType = Context.getParenType(FixedType);
  4700. return Qs.apply(Context, FixedType);
  4701. }
  4702. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  4703. if (!VLATy)
  4704. return QualType();
  4705. // FIXME: We should probably handle this case
  4706. if (VLATy->getElementType()->isVariablyModifiedType())
  4707. return QualType();
  4708. llvm::APSInt Res;
  4709. if (!VLATy->getSizeExpr() ||
  4710. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  4711. return QualType();
  4712. // Check whether the array size is negative.
  4713. if (Res.isSigned() && Res.isNegative()) {
  4714. SizeIsNegative = true;
  4715. return QualType();
  4716. }
  4717. // Check whether the array is too large to be addressed.
  4718. unsigned ActiveSizeBits
  4719. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  4720. Res);
  4721. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  4722. Oversized = Res;
  4723. return QualType();
  4724. }
  4725. return Context.getConstantArrayType(VLATy->getElementType(),
  4726. Res, ArrayType::Normal, 0);
  4727. }
  4728. static void
  4729. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  4730. SrcTL = SrcTL.getUnqualifiedLoc();
  4731. DstTL = DstTL.getUnqualifiedLoc();
  4732. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  4733. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  4734. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  4735. DstPTL.getPointeeLoc());
  4736. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  4737. return;
  4738. }
  4739. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  4740. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  4741. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  4742. DstPTL.getInnerLoc());
  4743. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  4744. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  4745. return;
  4746. }
  4747. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  4748. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  4749. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  4750. TypeLoc DstElemTL = DstATL.getElementLoc();
  4751. DstElemTL.initializeFullCopy(SrcElemTL);
  4752. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  4753. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  4754. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  4755. }
  4756. /// Helper method to turn variable array types into constant array
  4757. /// types in certain situations which would otherwise be errors (for
  4758. /// GCC compatibility).
  4759. static TypeSourceInfo*
  4760. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  4761. ASTContext &Context,
  4762. bool &SizeIsNegative,
  4763. llvm::APSInt &Oversized) {
  4764. QualType FixedTy
  4765. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  4766. SizeIsNegative, Oversized);
  4767. if (FixedTy.isNull())
  4768. return nullptr;
  4769. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  4770. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  4771. FixedTInfo->getTypeLoc());
  4772. return FixedTInfo;
  4773. }
  4774. /// \brief Register the given locally-scoped extern "C" declaration so
  4775. /// that it can be found later for redeclarations. We include any extern "C"
  4776. /// declaration that is not visible in the translation unit here, not just
  4777. /// function-scope declarations.
  4778. void
  4779. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  4780. if (!getLangOpts().CPlusPlus &&
  4781. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  4782. // Don't need to track declarations in the TU in C.
  4783. return;
  4784. // Note that we have a locally-scoped external with this name.
  4785. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  4786. }
  4787. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  4788. // FIXME: We can have multiple results via __attribute__((overloadable)).
  4789. auto Result = Context.getExternCContextDecl()->lookup(Name);
  4790. return Result.empty() ? nullptr : *Result.begin();
  4791. }
  4792. /// \brief Diagnose function specifiers on a declaration of an identifier that
  4793. /// does not identify a function.
  4794. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  4795. // FIXME: We should probably indicate the identifier in question to avoid
  4796. // confusion for constructs like "virtual int a(), b;"
  4797. if (DS.isVirtualSpecified())
  4798. Diag(DS.getVirtualSpecLoc(),
  4799. diag::err_virtual_non_function);
  4800. if (DS.isExplicitSpecified())
  4801. Diag(DS.getExplicitSpecLoc(),
  4802. diag::err_explicit_non_function);
  4803. if (DS.isNoreturnSpecified())
  4804. Diag(DS.getNoreturnSpecLoc(),
  4805. diag::err_noreturn_non_function);
  4806. }
  4807. NamedDecl*
  4808. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  4809. TypeSourceInfo *TInfo, LookupResult &Previous) {
  4810. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  4811. if (D.getCXXScopeSpec().isSet()) {
  4812. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  4813. << D.getCXXScopeSpec().getRange();
  4814. D.setInvalidType();
  4815. // Pretend we didn't see the scope specifier.
  4816. DC = CurContext;
  4817. Previous.clear();
  4818. }
  4819. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  4820. if (D.getDeclSpec().isInlineSpecified())
  4821. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  4822. << getLangOpts().CPlusPlus1z;
  4823. if (D.getDeclSpec().isConstexprSpecified())
  4824. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  4825. << 1;
  4826. if (D.getDeclSpec().isConceptSpecified())
  4827. Diag(D.getDeclSpec().getConceptSpecLoc(),
  4828. diag::err_concept_wrong_decl_kind);
  4829. if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
  4830. if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
  4831. Diag(D.getName().StartLocation,
  4832. diag::err_deduction_guide_invalid_specifier)
  4833. << "typedef";
  4834. else
  4835. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  4836. << D.getName().getSourceRange();
  4837. return nullptr;
  4838. }
  4839. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  4840. if (!NewTD) return nullptr;
  4841. // Handle attributes prior to checking for duplicates in MergeVarDecl
  4842. ProcessDeclAttributes(S, NewTD, D);
  4843. CheckTypedefForVariablyModifiedType(S, NewTD);
  4844. bool Redeclaration = D.isRedeclaration();
  4845. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  4846. D.setRedeclaration(Redeclaration);
  4847. return ND;
  4848. }
  4849. void
  4850. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  4851. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  4852. // then it shall have block scope.
  4853. // Note that variably modified types must be fixed before merging the decl so
  4854. // that redeclarations will match.
  4855. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  4856. QualType T = TInfo->getType();
  4857. if (T->isVariablyModifiedType()) {
  4858. getCurFunction()->setHasBranchProtectedScope();
  4859. if (S->getFnParent() == nullptr) {
  4860. bool SizeIsNegative;
  4861. llvm::APSInt Oversized;
  4862. TypeSourceInfo *FixedTInfo =
  4863. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  4864. SizeIsNegative,
  4865. Oversized);
  4866. if (FixedTInfo) {
  4867. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  4868. NewTD->setTypeSourceInfo(FixedTInfo);
  4869. } else {
  4870. if (SizeIsNegative)
  4871. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  4872. else if (T->isVariableArrayType())
  4873. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  4874. else if (Oversized.getBoolValue())
  4875. Diag(NewTD->getLocation(), diag::err_array_too_large)
  4876. << Oversized.toString(10);
  4877. else
  4878. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  4879. NewTD->setInvalidDecl();
  4880. }
  4881. }
  4882. }
  4883. }
  4884. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  4885. /// declares a typedef-name, either using the 'typedef' type specifier or via
  4886. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  4887. NamedDecl*
  4888. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  4889. LookupResult &Previous, bool &Redeclaration) {
  4890. // Merge the decl with the existing one if appropriate. If the decl is
  4891. // in an outer scope, it isn't the same thing.
  4892. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  4893. /*AllowInlineNamespace*/false);
  4894. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  4895. if (!Previous.empty()) {
  4896. Redeclaration = true;
  4897. MergeTypedefNameDecl(S, NewTD, Previous);
  4898. }
  4899. // If this is the C FILE type, notify the AST context.
  4900. if (IdentifierInfo *II = NewTD->getIdentifier())
  4901. if (!NewTD->isInvalidDecl() &&
  4902. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  4903. if (II->isStr("FILE"))
  4904. Context.setFILEDecl(NewTD);
  4905. else if (II->isStr("jmp_buf"))
  4906. Context.setjmp_bufDecl(NewTD);
  4907. else if (II->isStr("sigjmp_buf"))
  4908. Context.setsigjmp_bufDecl(NewTD);
  4909. else if (II->isStr("ucontext_t"))
  4910. Context.setucontext_tDecl(NewTD);
  4911. }
  4912. return NewTD;
  4913. }
  4914. /// \brief Determines whether the given declaration is an out-of-scope
  4915. /// previous declaration.
  4916. ///
  4917. /// This routine should be invoked when name lookup has found a
  4918. /// previous declaration (PrevDecl) that is not in the scope where a
  4919. /// new declaration by the same name is being introduced. If the new
  4920. /// declaration occurs in a local scope, previous declarations with
  4921. /// linkage may still be considered previous declarations (C99
  4922. /// 6.2.2p4-5, C++ [basic.link]p6).
  4923. ///
  4924. /// \param PrevDecl the previous declaration found by name
  4925. /// lookup
  4926. ///
  4927. /// \param DC the context in which the new declaration is being
  4928. /// declared.
  4929. ///
  4930. /// \returns true if PrevDecl is an out-of-scope previous declaration
  4931. /// for a new delcaration with the same name.
  4932. static bool
  4933. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  4934. ASTContext &Context) {
  4935. if (!PrevDecl)
  4936. return false;
  4937. if (!PrevDecl->hasLinkage())
  4938. return false;
  4939. if (Context.getLangOpts().CPlusPlus) {
  4940. // C++ [basic.link]p6:
  4941. // If there is a visible declaration of an entity with linkage
  4942. // having the same name and type, ignoring entities declared
  4943. // outside the innermost enclosing namespace scope, the block
  4944. // scope declaration declares that same entity and receives the
  4945. // linkage of the previous declaration.
  4946. DeclContext *OuterContext = DC->getRedeclContext();
  4947. if (!OuterContext->isFunctionOrMethod())
  4948. // This rule only applies to block-scope declarations.
  4949. return false;
  4950. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  4951. if (PrevOuterContext->isRecord())
  4952. // We found a member function: ignore it.
  4953. return false;
  4954. // Find the innermost enclosing namespace for the new and
  4955. // previous declarations.
  4956. OuterContext = OuterContext->getEnclosingNamespaceContext();
  4957. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  4958. // The previous declaration is in a different namespace, so it
  4959. // isn't the same function.
  4960. if (!OuterContext->Equals(PrevOuterContext))
  4961. return false;
  4962. }
  4963. return true;
  4964. }
  4965. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  4966. CXXScopeSpec &SS = D.getCXXScopeSpec();
  4967. if (!SS.isSet()) return;
  4968. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  4969. }
  4970. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  4971. QualType type = decl->getType();
  4972. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  4973. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  4974. // Various kinds of declaration aren't allowed to be __autoreleasing.
  4975. unsigned kind = -1U;
  4976. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  4977. if (var->hasAttr<BlocksAttr>())
  4978. kind = 0; // __block
  4979. else if (!var->hasLocalStorage())
  4980. kind = 1; // global
  4981. } else if (isa<ObjCIvarDecl>(decl)) {
  4982. kind = 3; // ivar
  4983. } else if (isa<FieldDecl>(decl)) {
  4984. kind = 2; // field
  4985. }
  4986. if (kind != -1U) {
  4987. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  4988. << kind;
  4989. }
  4990. } else if (lifetime == Qualifiers::OCL_None) {
  4991. // Try to infer lifetime.
  4992. if (!type->isObjCLifetimeType())
  4993. return false;
  4994. lifetime = type->getObjCARCImplicitLifetime();
  4995. type = Context.getLifetimeQualifiedType(type, lifetime);
  4996. decl->setType(type);
  4997. }
  4998. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  4999. // Thread-local variables cannot have lifetime.
  5000. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  5001. var->getTLSKind()) {
  5002. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  5003. << var->getType();
  5004. return true;
  5005. }
  5006. }
  5007. return false;
  5008. }
  5009. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  5010. // Ensure that an auto decl is deduced otherwise the checks below might cache
  5011. // the wrong linkage.
  5012. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  5013. // 'weak' only applies to declarations with external linkage.
  5014. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  5015. if (!ND.isExternallyVisible()) {
  5016. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  5017. ND.dropAttr<WeakAttr>();
  5018. }
  5019. }
  5020. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  5021. if (ND.isExternallyVisible()) {
  5022. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  5023. ND.dropAttr<WeakRefAttr>();
  5024. ND.dropAttr<AliasAttr>();
  5025. }
  5026. }
  5027. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  5028. if (VD->hasInit()) {
  5029. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  5030. assert(VD->isThisDeclarationADefinition() &&
  5031. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  5032. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  5033. VD->dropAttr<AliasAttr>();
  5034. }
  5035. }
  5036. }
  5037. // 'selectany' only applies to externally visible variable declarations.
  5038. // It does not apply to functions.
  5039. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  5040. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  5041. S.Diag(Attr->getLocation(),
  5042. diag::err_attribute_selectany_non_extern_data);
  5043. ND.dropAttr<SelectAnyAttr>();
  5044. }
  5045. }
  5046. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  5047. // dll attributes require external linkage. Static locals may have external
  5048. // linkage but still cannot be explicitly imported or exported.
  5049. auto *VD = dyn_cast<VarDecl>(&ND);
  5050. if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
  5051. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  5052. << &ND << Attr;
  5053. ND.setInvalidDecl();
  5054. }
  5055. }
  5056. // Virtual functions cannot be marked as 'notail'.
  5057. if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
  5058. if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
  5059. if (MD->isVirtual()) {
  5060. S.Diag(ND.getLocation(),
  5061. diag::err_invalid_attribute_on_virtual_function)
  5062. << Attr;
  5063. ND.dropAttr<NotTailCalledAttr>();
  5064. }
  5065. }
  5066. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  5067. NamedDecl *NewDecl,
  5068. bool IsSpecialization,
  5069. bool IsDefinition) {
  5070. if (OldDecl->isInvalidDecl())
  5071. return;
  5072. bool IsTemplate = false;
  5073. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  5074. OldDecl = OldTD->getTemplatedDecl();
  5075. IsTemplate = true;
  5076. if (!IsSpecialization)
  5077. IsDefinition = false;
  5078. }
  5079. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  5080. NewDecl = NewTD->getTemplatedDecl();
  5081. IsTemplate = true;
  5082. }
  5083. if (!OldDecl || !NewDecl)
  5084. return;
  5085. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  5086. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5087. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5088. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5089. // dllimport and dllexport are inheritable attributes so we have to exclude
  5090. // inherited attribute instances.
  5091. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5092. (NewExportAttr && !NewExportAttr->isInherited());
  5093. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5094. // the only exception being explicit specializations.
  5095. // Implicitly generated declarations are also excluded for now because there
  5096. // is no other way to switch these to use dllimport or dllexport.
  5097. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5098. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5099. // Allow with a warning for free functions and global variables.
  5100. bool JustWarn = false;
  5101. if (!OldDecl->isCXXClassMember()) {
  5102. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5103. if (VD && !VD->getDescribedVarTemplate())
  5104. JustWarn = true;
  5105. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5106. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5107. JustWarn = true;
  5108. }
  5109. // We cannot change a declaration that's been used because IR has already
  5110. // been emitted. Dllimported functions will still work though (modulo
  5111. // address equality) as they can use the thunk.
  5112. if (OldDecl->isUsed())
  5113. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5114. JustWarn = false;
  5115. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5116. : diag::err_attribute_dll_redeclaration;
  5117. S.Diag(NewDecl->getLocation(), DiagID)
  5118. << NewDecl
  5119. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5120. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5121. if (!JustWarn) {
  5122. NewDecl->setInvalidDecl();
  5123. return;
  5124. }
  5125. }
  5126. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5127. // exceptions being inline function definitions (except for function
  5128. // templates), local extern declarations, qualified friend declarations or
  5129. // special MSVC extension: in the last case, the declaration is treated as if
  5130. // it were marked dllexport.
  5131. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5132. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5133. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5134. // Ignore static data because out-of-line definitions are diagnosed
  5135. // separately.
  5136. IsStaticDataMember = VD->isStaticDataMember();
  5137. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5138. VarDecl::DeclarationOnly;
  5139. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5140. IsInline = FD->isInlined();
  5141. IsQualifiedFriend = FD->getQualifier() &&
  5142. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5143. }
  5144. if (OldImportAttr && !HasNewAttr &&
  5145. (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
  5146. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5147. if (IsMicrosoft && IsDefinition) {
  5148. S.Diag(NewDecl->getLocation(),
  5149. diag::warn_redeclaration_without_import_attribute)
  5150. << NewDecl;
  5151. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5152. NewDecl->dropAttr<DLLImportAttr>();
  5153. NewDecl->addAttr(::new (S.Context) DLLExportAttr(
  5154. NewImportAttr->getRange(), S.Context,
  5155. NewImportAttr->getSpellingListIndex()));
  5156. } else {
  5157. S.Diag(NewDecl->getLocation(),
  5158. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5159. << NewDecl << OldImportAttr;
  5160. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5161. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5162. OldDecl->dropAttr<DLLImportAttr>();
  5163. NewDecl->dropAttr<DLLImportAttr>();
  5164. }
  5165. } else if (IsInline && OldImportAttr && !IsMicrosoft) {
  5166. // In MinGW, seeing a function declared inline drops the dllimport attribute.
  5167. OldDecl->dropAttr<DLLImportAttr>();
  5168. NewDecl->dropAttr<DLLImportAttr>();
  5169. S.Diag(NewDecl->getLocation(),
  5170. diag::warn_dllimport_dropped_from_inline_function)
  5171. << NewDecl << OldImportAttr;
  5172. }
  5173. }
  5174. /// Given that we are within the definition of the given function,
  5175. /// will that definition behave like C99's 'inline', where the
  5176. /// definition is discarded except for optimization purposes?
  5177. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  5178. // Try to avoid calling GetGVALinkageForFunction.
  5179. // All cases of this require the 'inline' keyword.
  5180. if (!FD->isInlined()) return false;
  5181. // This is only possible in C++ with the gnu_inline attribute.
  5182. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  5183. return false;
  5184. // Okay, go ahead and call the relatively-more-expensive function.
  5185. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  5186. }
  5187. /// Determine whether a variable is extern "C" prior to attaching
  5188. /// an initializer. We can't just call isExternC() here, because that
  5189. /// will also compute and cache whether the declaration is externally
  5190. /// visible, which might change when we attach the initializer.
  5191. ///
  5192. /// This can only be used if the declaration is known to not be a
  5193. /// redeclaration of an internal linkage declaration.
  5194. ///
  5195. /// For instance:
  5196. ///
  5197. /// auto x = []{};
  5198. ///
  5199. /// Attaching the initializer here makes this declaration not externally
  5200. /// visible, because its type has internal linkage.
  5201. ///
  5202. /// FIXME: This is a hack.
  5203. template<typename T>
  5204. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  5205. if (S.getLangOpts().CPlusPlus) {
  5206. // In C++, the overloadable attribute negates the effects of extern "C".
  5207. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  5208. return false;
  5209. // So do CUDA's host/device attributes.
  5210. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  5211. D->template hasAttr<CUDAHostAttr>()))
  5212. return false;
  5213. }
  5214. return D->isExternC();
  5215. }
  5216. static bool shouldConsiderLinkage(const VarDecl *VD) {
  5217. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  5218. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
  5219. return VD->hasExternalStorage();
  5220. if (DC->isFileContext())
  5221. return true;
  5222. if (DC->isRecord())
  5223. return false;
  5224. llvm_unreachable("Unexpected context");
  5225. }
  5226. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  5227. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  5228. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  5229. isa<OMPDeclareReductionDecl>(DC))
  5230. return true;
  5231. if (DC->isRecord())
  5232. return false;
  5233. llvm_unreachable("Unexpected context");
  5234. }
  5235. static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
  5236. AttributeList::Kind Kind) {
  5237. for (const AttributeList *L = AttrList; L; L = L->getNext())
  5238. if (L->getKind() == Kind)
  5239. return true;
  5240. return false;
  5241. }
  5242. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  5243. AttributeList::Kind Kind) {
  5244. // Check decl attributes on the DeclSpec.
  5245. if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
  5246. return true;
  5247. // Walk the declarator structure, checking decl attributes that were in a type
  5248. // position to the decl itself.
  5249. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  5250. if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
  5251. return true;
  5252. }
  5253. // Finally, check attributes on the decl itself.
  5254. return hasParsedAttr(S, PD.getAttributes(), Kind);
  5255. }
  5256. /// Adjust the \c DeclContext for a function or variable that might be a
  5257. /// function-local external declaration.
  5258. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  5259. if (!DC->isFunctionOrMethod())
  5260. return false;
  5261. // If this is a local extern function or variable declared within a function
  5262. // template, don't add it into the enclosing namespace scope until it is
  5263. // instantiated; it might have a dependent type right now.
  5264. if (DC->isDependentContext())
  5265. return true;
  5266. // C++11 [basic.link]p7:
  5267. // When a block scope declaration of an entity with linkage is not found to
  5268. // refer to some other declaration, then that entity is a member of the
  5269. // innermost enclosing namespace.
  5270. //
  5271. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  5272. // semantically-enclosing namespace, not a lexically-enclosing one.
  5273. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  5274. DC = DC->getParent();
  5275. return true;
  5276. }
  5277. /// \brief Returns true if given declaration has external C language linkage.
  5278. static bool isDeclExternC(const Decl *D) {
  5279. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  5280. return FD->isExternC();
  5281. if (const auto *VD = dyn_cast<VarDecl>(D))
  5282. return VD->isExternC();
  5283. llvm_unreachable("Unknown type of decl!");
  5284. }
  5285. NamedDecl *Sema::ActOnVariableDeclarator(
  5286. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  5287. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  5288. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  5289. QualType R = TInfo->getType();
  5290. DeclarationName Name = GetNameForDeclarator(D).getName();
  5291. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5292. if (D.isDecompositionDeclarator()) {
  5293. AddToScope = false;
  5294. // Take the name of the first declarator as our name for diagnostic
  5295. // purposes.
  5296. auto &Decomp = D.getDecompositionDeclarator();
  5297. if (!Decomp.bindings().empty()) {
  5298. II = Decomp.bindings()[0].Name;
  5299. Name = II;
  5300. }
  5301. } else if (!II) {
  5302. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
  5303. return nullptr;
  5304. }
  5305. if (getLangOpts().OpenCL) {
  5306. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  5307. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  5308. // argument.
  5309. if (R->isImageType() || R->isPipeType()) {
  5310. Diag(D.getIdentifierLoc(),
  5311. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  5312. << R;
  5313. D.setInvalidType();
  5314. return nullptr;
  5315. }
  5316. // OpenCL v1.2 s6.9.r:
  5317. // The event type cannot be used to declare a program scope variable.
  5318. // OpenCL v2.0 s6.9.q:
  5319. // The clk_event_t and reserve_id_t types cannot be declared in program scope.
  5320. if (NULL == S->getParent()) {
  5321. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  5322. Diag(D.getIdentifierLoc(),
  5323. diag::err_invalid_type_for_program_scope_var) << R;
  5324. D.setInvalidType();
  5325. return nullptr;
  5326. }
  5327. }
  5328. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  5329. QualType NR = R;
  5330. while (NR->isPointerType()) {
  5331. if (NR->isFunctionPointerType()) {
  5332. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
  5333. D.setInvalidType();
  5334. break;
  5335. }
  5336. NR = NR->getPointeeType();
  5337. }
  5338. if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  5339. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5340. // half array type (unless the cl_khr_fp16 extension is enabled).
  5341. if (Context.getBaseElementType(R)->isHalfType()) {
  5342. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5343. D.setInvalidType();
  5344. }
  5345. }
  5346. // OpenCL v1.2 s6.9.b p4:
  5347. // The sampler type cannot be used with the __local and __global address
  5348. // space qualifiers.
  5349. if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
  5350. R.getAddressSpace() == LangAS::opencl_global)) {
  5351. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5352. }
  5353. // OpenCL v1.2 s6.9.r:
  5354. // The event type cannot be used with the __local, __constant and __global
  5355. // address space qualifiers.
  5356. if (R->isEventT()) {
  5357. if (R.getAddressSpace()) {
  5358. Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
  5359. D.setInvalidType();
  5360. }
  5361. }
  5362. }
  5363. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  5364. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  5365. // dllimport globals without explicit storage class are treated as extern. We
  5366. // have to change the storage class this early to get the right DeclContext.
  5367. if (SC == SC_None && !DC->isRecord() &&
  5368. hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
  5369. !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
  5370. SC = SC_Extern;
  5371. DeclContext *OriginalDC = DC;
  5372. bool IsLocalExternDecl = SC == SC_Extern &&
  5373. adjustContextForLocalExternDecl(DC);
  5374. if (SCSpec == DeclSpec::SCS_mutable) {
  5375. // mutable can only appear on non-static class members, so it's always
  5376. // an error here
  5377. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5378. D.setInvalidType();
  5379. SC = SC_None;
  5380. }
  5381. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5382. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5383. D.getDeclSpec().getStorageClassSpecLoc())) {
  5384. // In C++11, the 'register' storage class specifier is deprecated.
  5385. // Suppress the warning in system macros, it's used in macros in some
  5386. // popular C system headers, such as in glibc's htonl() macro.
  5387. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5388. getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
  5389. : diag::warn_deprecated_register)
  5390. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5391. }
  5392. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5393. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5394. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5395. // appear in the declaration specifiers in an external declaration.
  5396. // Global Register+Asm is a GNU extension we support.
  5397. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5398. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5399. D.setInvalidType();
  5400. }
  5401. }
  5402. bool IsMemberSpecialization = false;
  5403. bool IsVariableTemplateSpecialization = false;
  5404. bool IsPartialSpecialization = false;
  5405. bool IsVariableTemplate = false;
  5406. VarDecl *NewVD = nullptr;
  5407. VarTemplateDecl *NewTemplate = nullptr;
  5408. TemplateParameterList *TemplateParams = nullptr;
  5409. if (!getLangOpts().CPlusPlus) {
  5410. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5411. D.getIdentifierLoc(), II,
  5412. R, TInfo, SC);
  5413. if (R->getContainedDeducedType())
  5414. ParsingInitForAutoVars.insert(NewVD);
  5415. if (D.isInvalidType())
  5416. NewVD->setInvalidDecl();
  5417. } else {
  5418. bool Invalid = false;
  5419. if (DC->isRecord() && !CurContext->isRecord()) {
  5420. // This is an out-of-line definition of a static data member.
  5421. switch (SC) {
  5422. case SC_None:
  5423. break;
  5424. case SC_Static:
  5425. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5426. diag::err_static_out_of_line)
  5427. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5428. break;
  5429. case SC_Auto:
  5430. case SC_Register:
  5431. case SC_Extern:
  5432. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5433. // to names of variables declared in a block or to function parameters.
  5434. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5435. // of class members
  5436. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5437. diag::err_storage_class_for_static_member)
  5438. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5439. break;
  5440. case SC_PrivateExtern:
  5441. llvm_unreachable("C storage class in c++!");
  5442. }
  5443. }
  5444. if (SC == SC_Static && CurContext->isRecord()) {
  5445. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5446. if (RD->isLocalClass())
  5447. Diag(D.getIdentifierLoc(),
  5448. diag::err_static_data_member_not_allowed_in_local_class)
  5449. << Name << RD->getDeclName();
  5450. // C++98 [class.union]p1: If a union contains a static data member,
  5451. // the program is ill-formed. C++11 drops this restriction.
  5452. if (RD->isUnion())
  5453. Diag(D.getIdentifierLoc(),
  5454. getLangOpts().CPlusPlus11
  5455. ? diag::warn_cxx98_compat_static_data_member_in_union
  5456. : diag::ext_static_data_member_in_union) << Name;
  5457. // We conservatively disallow static data members in anonymous structs.
  5458. else if (!RD->getDeclName())
  5459. Diag(D.getIdentifierLoc(),
  5460. diag::err_static_data_member_not_allowed_in_anon_struct)
  5461. << Name << RD->isUnion();
  5462. }
  5463. }
  5464. // Match up the template parameter lists with the scope specifier, then
  5465. // determine whether we have a template or a template specialization.
  5466. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5467. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  5468. D.getCXXScopeSpec(),
  5469. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  5470. ? D.getName().TemplateId
  5471. : nullptr,
  5472. TemplateParamLists,
  5473. /*never a friend*/ false, IsMemberSpecialization, Invalid);
  5474. if (TemplateParams) {
  5475. if (!TemplateParams->size() &&
  5476. D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  5477. // There is an extraneous 'template<>' for this variable. Complain
  5478. // about it, but allow the declaration of the variable.
  5479. Diag(TemplateParams->getTemplateLoc(),
  5480. diag::err_template_variable_noparams)
  5481. << II
  5482. << SourceRange(TemplateParams->getTemplateLoc(),
  5483. TemplateParams->getRAngleLoc());
  5484. TemplateParams = nullptr;
  5485. } else {
  5486. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  5487. // This is an explicit specialization or a partial specialization.
  5488. // FIXME: Check that we can declare a specialization here.
  5489. IsVariableTemplateSpecialization = true;
  5490. IsPartialSpecialization = TemplateParams->size() > 0;
  5491. } else { // if (TemplateParams->size() > 0)
  5492. // This is a template declaration.
  5493. IsVariableTemplate = true;
  5494. // Check that we can declare a template here.
  5495. if (CheckTemplateDeclScope(S, TemplateParams))
  5496. return nullptr;
  5497. // Only C++1y supports variable templates (N3651).
  5498. Diag(D.getIdentifierLoc(),
  5499. getLangOpts().CPlusPlus14
  5500. ? diag::warn_cxx11_compat_variable_template
  5501. : diag::ext_variable_template);
  5502. }
  5503. }
  5504. } else {
  5505. assert(
  5506. (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
  5507. "should have a 'template<>' for this decl");
  5508. }
  5509. if (IsVariableTemplateSpecialization) {
  5510. SourceLocation TemplateKWLoc =
  5511. TemplateParamLists.size() > 0
  5512. ? TemplateParamLists[0]->getTemplateLoc()
  5513. : SourceLocation();
  5514. DeclResult Res = ActOnVarTemplateSpecialization(
  5515. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5516. IsPartialSpecialization);
  5517. if (Res.isInvalid())
  5518. return nullptr;
  5519. NewVD = cast<VarDecl>(Res.get());
  5520. AddToScope = false;
  5521. } else if (D.isDecompositionDeclarator()) {
  5522. NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
  5523. D.getIdentifierLoc(), R, TInfo, SC,
  5524. Bindings);
  5525. } else
  5526. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5527. D.getIdentifierLoc(), II, R, TInfo, SC);
  5528. // If this is supposed to be a variable template, create it as such.
  5529. if (IsVariableTemplate) {
  5530. NewTemplate =
  5531. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5532. TemplateParams, NewVD);
  5533. NewVD->setDescribedVarTemplate(NewTemplate);
  5534. }
  5535. // If this decl has an auto type in need of deduction, make a note of the
  5536. // Decl so we can diagnose uses of it in its own initializer.
  5537. if (R->getContainedDeducedType())
  5538. ParsingInitForAutoVars.insert(NewVD);
  5539. if (D.isInvalidType() || Invalid) {
  5540. NewVD->setInvalidDecl();
  5541. if (NewTemplate)
  5542. NewTemplate->setInvalidDecl();
  5543. }
  5544. SetNestedNameSpecifier(NewVD, D);
  5545. // If we have any template parameter lists that don't directly belong to
  5546. // the variable (matching the scope specifier), store them.
  5547. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5548. if (TemplateParamLists.size() > VDTemplateParamLists)
  5549. NewVD->setTemplateParameterListsInfo(
  5550. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  5551. if (D.getDeclSpec().isConstexprSpecified()) {
  5552. NewVD->setConstexpr(true);
  5553. // C++1z [dcl.spec.constexpr]p1:
  5554. // A static data member declared with the constexpr specifier is
  5555. // implicitly an inline variable.
  5556. if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
  5557. NewVD->setImplicitlyInline();
  5558. }
  5559. if (D.getDeclSpec().isConceptSpecified()) {
  5560. if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
  5561. VTD->setConcept();
  5562. // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
  5563. // be declared with the thread_local, inline, friend, or constexpr
  5564. // specifiers, [...]
  5565. if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
  5566. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5567. diag::err_concept_decl_invalid_specifiers)
  5568. << 0 << 0;
  5569. NewVD->setInvalidDecl(true);
  5570. }
  5571. if (D.getDeclSpec().isConstexprSpecified()) {
  5572. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  5573. diag::err_concept_decl_invalid_specifiers)
  5574. << 0 << 3;
  5575. NewVD->setInvalidDecl(true);
  5576. }
  5577. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  5578. // applied only to the definition of a function template or variable
  5579. // template, declared in namespace scope.
  5580. if (IsVariableTemplateSpecialization) {
  5581. Diag(D.getDeclSpec().getConceptSpecLoc(),
  5582. diag::err_concept_specified_specialization)
  5583. << (IsPartialSpecialization ? 2 : 1);
  5584. }
  5585. // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
  5586. // following restrictions:
  5587. // - The declared type shall have the type bool.
  5588. if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
  5589. !NewVD->isInvalidDecl()) {
  5590. Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
  5591. NewVD->setInvalidDecl(true);
  5592. }
  5593. }
  5594. }
  5595. if (D.getDeclSpec().isInlineSpecified()) {
  5596. if (!getLangOpts().CPlusPlus) {
  5597. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5598. << 0;
  5599. } else if (CurContext->isFunctionOrMethod()) {
  5600. // 'inline' is not allowed on block scope variable declaration.
  5601. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5602. diag::err_inline_declaration_block_scope) << Name
  5603. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  5604. } else {
  5605. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5606. getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
  5607. : diag::ext_inline_variable);
  5608. NewVD->setInlineSpecified();
  5609. }
  5610. }
  5611. // Set the lexical context. If the declarator has a C++ scope specifier, the
  5612. // lexical context will be different from the semantic context.
  5613. NewVD->setLexicalDeclContext(CurContext);
  5614. if (NewTemplate)
  5615. NewTemplate->setLexicalDeclContext(CurContext);
  5616. if (IsLocalExternDecl) {
  5617. if (D.isDecompositionDeclarator())
  5618. for (auto *B : Bindings)
  5619. B->setLocalExternDecl();
  5620. else
  5621. NewVD->setLocalExternDecl();
  5622. }
  5623. bool EmitTLSUnsupportedError = false;
  5624. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  5625. // C++11 [dcl.stc]p4:
  5626. // When thread_local is applied to a variable of block scope the
  5627. // storage-class-specifier static is implied if it does not appear
  5628. // explicitly.
  5629. // Core issue: 'static' is not implied if the variable is declared
  5630. // 'extern'.
  5631. if (NewVD->hasLocalStorage() &&
  5632. (SCSpec != DeclSpec::SCS_unspecified ||
  5633. TSCS != DeclSpec::TSCS_thread_local ||
  5634. !DC->isFunctionOrMethod()))
  5635. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5636. diag::err_thread_non_global)
  5637. << DeclSpec::getSpecifierName(TSCS);
  5638. else if (!Context.getTargetInfo().isTLSSupported()) {
  5639. if (getLangOpts().CUDA) {
  5640. // Postpone error emission until we've collected attributes required to
  5641. // figure out whether it's a host or device variable and whether the
  5642. // error should be ignored.
  5643. EmitTLSUnsupportedError = true;
  5644. // We still need to mark the variable as TLS so it shows up in AST with
  5645. // proper storage class for other tools to use even if we're not going
  5646. // to emit any code for it.
  5647. NewVD->setTSCSpec(TSCS);
  5648. } else
  5649. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5650. diag::err_thread_unsupported);
  5651. } else
  5652. NewVD->setTSCSpec(TSCS);
  5653. }
  5654. // C99 6.7.4p3
  5655. // An inline definition of a function with external linkage shall
  5656. // not contain a definition of a modifiable object with static or
  5657. // thread storage duration...
  5658. // We only apply this when the function is required to be defined
  5659. // elsewhere, i.e. when the function is not 'extern inline'. Note
  5660. // that a local variable with thread storage duration still has to
  5661. // be marked 'static'. Also note that it's possible to get these
  5662. // semantics in C++ using __attribute__((gnu_inline)).
  5663. if (SC == SC_Static && S->getFnParent() != nullptr &&
  5664. !NewVD->getType().isConstQualified()) {
  5665. FunctionDecl *CurFD = getCurFunctionDecl();
  5666. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  5667. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5668. diag::warn_static_local_in_extern_inline);
  5669. MaybeSuggestAddingStaticToDecl(CurFD);
  5670. }
  5671. }
  5672. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5673. if (IsVariableTemplateSpecialization)
  5674. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5675. << (IsPartialSpecialization ? 1 : 0)
  5676. << FixItHint::CreateRemoval(
  5677. D.getDeclSpec().getModulePrivateSpecLoc());
  5678. else if (IsMemberSpecialization)
  5679. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5680. << 2
  5681. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5682. else if (NewVD->hasLocalStorage())
  5683. Diag(NewVD->getLocation(), diag::err_module_private_local)
  5684. << 0 << NewVD->getDeclName()
  5685. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5686. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5687. else {
  5688. NewVD->setModulePrivate();
  5689. if (NewTemplate)
  5690. NewTemplate->setModulePrivate();
  5691. for (auto *B : Bindings)
  5692. B->setModulePrivate();
  5693. }
  5694. }
  5695. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5696. ProcessDeclAttributes(S, NewVD, D);
  5697. if (getLangOpts().CUDA) {
  5698. if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
  5699. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5700. diag::err_thread_unsupported);
  5701. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  5702. // storage [duration]."
  5703. if (SC == SC_None && S->getFnParent() != nullptr &&
  5704. (NewVD->hasAttr<CUDASharedAttr>() ||
  5705. NewVD->hasAttr<CUDAConstantAttr>())) {
  5706. NewVD->setStorageClass(SC_Static);
  5707. }
  5708. }
  5709. // Ensure that dllimport globals without explicit storage class are treated as
  5710. // extern. The storage class is set above using parsed attributes. Now we can
  5711. // check the VarDecl itself.
  5712. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  5713. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  5714. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  5715. // In auto-retain/release, infer strong retension for variables of
  5716. // retainable type.
  5717. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  5718. NewVD->setInvalidDecl();
  5719. // Handle GNU asm-label extension (encoded as an attribute).
  5720. if (Expr *E = (Expr*)D.getAsmLabel()) {
  5721. // The parser guarantees this is a string.
  5722. StringLiteral *SE = cast<StringLiteral>(E);
  5723. StringRef Label = SE->getString();
  5724. if (S->getFnParent() != nullptr) {
  5725. switch (SC) {
  5726. case SC_None:
  5727. case SC_Auto:
  5728. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  5729. break;
  5730. case SC_Register:
  5731. // Local Named register
  5732. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  5733. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  5734. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5735. break;
  5736. case SC_Static:
  5737. case SC_Extern:
  5738. case SC_PrivateExtern:
  5739. break;
  5740. }
  5741. } else if (SC == SC_Register) {
  5742. // Global Named register
  5743. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  5744. const auto &TI = Context.getTargetInfo();
  5745. bool HasSizeMismatch;
  5746. if (!TI.isValidGCCRegisterName(Label))
  5747. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5748. else if (!TI.validateGlobalRegisterVariable(Label,
  5749. Context.getTypeSize(R),
  5750. HasSizeMismatch))
  5751. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  5752. else if (HasSizeMismatch)
  5753. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  5754. }
  5755. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  5756. Diag(D.getLocStart(), diag::err_asm_bad_register_type);
  5757. NewVD->setInvalidDecl(true);
  5758. }
  5759. }
  5760. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  5761. Context, Label, 0));
  5762. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  5763. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  5764. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  5765. if (I != ExtnameUndeclaredIdentifiers.end()) {
  5766. if (isDeclExternC(NewVD)) {
  5767. NewVD->addAttr(I->second);
  5768. ExtnameUndeclaredIdentifiers.erase(I);
  5769. } else
  5770. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  5771. << /*Variable*/1 << NewVD;
  5772. }
  5773. }
  5774. // Find the shadowed declaration before filtering for scope.
  5775. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  5776. ? getShadowedDeclaration(NewVD, Previous)
  5777. : nullptr;
  5778. // Don't consider existing declarations that are in a different
  5779. // scope and are out-of-semantic-context declarations (if the new
  5780. // declaration has linkage).
  5781. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  5782. D.getCXXScopeSpec().isNotEmpty() ||
  5783. IsMemberSpecialization ||
  5784. IsVariableTemplateSpecialization);
  5785. // Check whether the previous declaration is in the same block scope. This
  5786. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  5787. if (getLangOpts().CPlusPlus &&
  5788. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  5789. NewVD->setPreviousDeclInSameBlockScope(
  5790. Previous.isSingleResult() && !Previous.isShadowed() &&
  5791. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  5792. if (!getLangOpts().CPlusPlus) {
  5793. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  5794. } else {
  5795. // If this is an explicit specialization of a static data member, check it.
  5796. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  5797. CheckMemberSpecialization(NewVD, Previous))
  5798. NewVD->setInvalidDecl();
  5799. // Merge the decl with the existing one if appropriate.
  5800. if (!Previous.empty()) {
  5801. if (Previous.isSingleResult() &&
  5802. isa<FieldDecl>(Previous.getFoundDecl()) &&
  5803. D.getCXXScopeSpec().isSet()) {
  5804. // The user tried to define a non-static data member
  5805. // out-of-line (C++ [dcl.meaning]p1).
  5806. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  5807. << D.getCXXScopeSpec().getRange();
  5808. Previous.clear();
  5809. NewVD->setInvalidDecl();
  5810. }
  5811. } else if (D.getCXXScopeSpec().isSet()) {
  5812. // No previous declaration in the qualifying scope.
  5813. Diag(D.getIdentifierLoc(), diag::err_no_member)
  5814. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  5815. << D.getCXXScopeSpec().getRange();
  5816. NewVD->setInvalidDecl();
  5817. }
  5818. if (!IsVariableTemplateSpecialization)
  5819. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  5820. // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
  5821. // an explicit specialization (14.8.3) or a partial specialization of a
  5822. // concept definition.
  5823. if (IsVariableTemplateSpecialization &&
  5824. !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
  5825. Previous.isSingleResult()) {
  5826. NamedDecl *PreviousDecl = Previous.getFoundDecl();
  5827. if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
  5828. if (VarTmpl->isConcept()) {
  5829. Diag(NewVD->getLocation(), diag::err_concept_specialized)
  5830. << 1 /*variable*/
  5831. << (IsPartialSpecialization ? 2 /*partially specialized*/
  5832. : 1 /*explicitly specialized*/);
  5833. Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
  5834. NewVD->setInvalidDecl();
  5835. }
  5836. }
  5837. }
  5838. if (NewTemplate) {
  5839. VarTemplateDecl *PrevVarTemplate =
  5840. NewVD->getPreviousDecl()
  5841. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  5842. : nullptr;
  5843. // Check the template parameter list of this declaration, possibly
  5844. // merging in the template parameter list from the previous variable
  5845. // template declaration.
  5846. if (CheckTemplateParameterList(
  5847. TemplateParams,
  5848. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  5849. : nullptr,
  5850. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  5851. DC->isDependentContext())
  5852. ? TPC_ClassTemplateMember
  5853. : TPC_VarTemplate))
  5854. NewVD->setInvalidDecl();
  5855. // If we are providing an explicit specialization of a static variable
  5856. // template, make a note of that.
  5857. if (PrevVarTemplate &&
  5858. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  5859. PrevVarTemplate->setMemberSpecialization();
  5860. }
  5861. }
  5862. // Diagnose shadowed variables iff this isn't a redeclaration.
  5863. if (ShadowedDecl && !D.isRedeclaration())
  5864. CheckShadow(NewVD, ShadowedDecl, Previous);
  5865. ProcessPragmaWeak(S, NewVD);
  5866. // If this is the first declaration of an extern C variable, update
  5867. // the map of such variables.
  5868. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  5869. isIncompleteDeclExternC(*this, NewVD))
  5870. RegisterLocallyScopedExternCDecl(NewVD, S);
  5871. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  5872. Decl *ManglingContextDecl;
  5873. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  5874. NewVD->getDeclContext(), ManglingContextDecl)) {
  5875. Context.setManglingNumber(
  5876. NewVD, MCtx->getManglingNumber(
  5877. NewVD, getMSManglingNumber(getLangOpts(), S)));
  5878. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  5879. }
  5880. }
  5881. // Special handling of variable named 'main'.
  5882. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  5883. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  5884. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  5885. // C++ [basic.start.main]p3
  5886. // A program that declares a variable main at global scope is ill-formed.
  5887. if (getLangOpts().CPlusPlus)
  5888. Diag(D.getLocStart(), diag::err_main_global_variable);
  5889. // In C, and external-linkage variable named main results in undefined
  5890. // behavior.
  5891. else if (NewVD->hasExternalFormalLinkage())
  5892. Diag(D.getLocStart(), diag::warn_main_redefined);
  5893. }
  5894. if (D.isRedeclaration() && !Previous.empty()) {
  5895. checkDLLAttributeRedeclaration(
  5896. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
  5897. IsMemberSpecialization, D.isFunctionDefinition());
  5898. }
  5899. if (NewTemplate) {
  5900. if (NewVD->isInvalidDecl())
  5901. NewTemplate->setInvalidDecl();
  5902. ActOnDocumentableDecl(NewTemplate);
  5903. return NewTemplate;
  5904. }
  5905. return NewVD;
  5906. }
  5907. /// Enum describing the %select options in diag::warn_decl_shadow.
  5908. enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
  5909. /// Determine what kind of declaration we're shadowing.
  5910. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  5911. const DeclContext *OldDC) {
  5912. if (isa<RecordDecl>(OldDC))
  5913. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  5914. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  5915. }
  5916. /// Return the location of the capture if the given lambda captures the given
  5917. /// variable \p VD, or an invalid source location otherwise.
  5918. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  5919. const VarDecl *VD) {
  5920. for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
  5921. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  5922. return Capture.getLocation();
  5923. }
  5924. return SourceLocation();
  5925. }
  5926. /// \brief Return the declaration shadowed by the given variable \p D, or null
  5927. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  5928. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  5929. const LookupResult &R) {
  5930. // Return if warning is ignored.
  5931. if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
  5932. return nullptr;
  5933. // Don't diagnose declarations at file scope.
  5934. if (D->hasGlobalStorage())
  5935. return nullptr;
  5936. // Only diagnose if we're shadowing an unambiguous field or variable.
  5937. if (R.getResultKind() != LookupResult::Found)
  5938. return nullptr;
  5939. NamedDecl *ShadowedDecl = R.getFoundDecl();
  5940. return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
  5941. ? ShadowedDecl
  5942. : nullptr;
  5943. }
  5944. /// \brief Diagnose variable or built-in function shadowing. Implements
  5945. /// -Wshadow.
  5946. ///
  5947. /// This method is called whenever a VarDecl is added to a "useful"
  5948. /// scope.
  5949. ///
  5950. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  5951. /// \param R the lookup of the name
  5952. ///
  5953. void Sema::CheckShadow(VarDecl *D, NamedDecl *ShadowedDecl,
  5954. const LookupResult &R) {
  5955. DeclContext *NewDC = D->getDeclContext();
  5956. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  5957. // Fields are not shadowed by variables in C++ static methods.
  5958. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  5959. if (MD->isStatic())
  5960. return;
  5961. // Fields shadowed by constructor parameters are a special case. Usually
  5962. // the constructor initializes the field with the parameter.
  5963. if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
  5964. // Remember that this was shadowed so we can either warn about its
  5965. // modification or its existence depending on warning settings.
  5966. D = D->getCanonicalDecl();
  5967. ShadowingDecls.insert({D, FD});
  5968. return;
  5969. }
  5970. }
  5971. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  5972. if (shadowedVar->isExternC()) {
  5973. // For shadowing external vars, make sure that we point to the global
  5974. // declaration, not a locally scoped extern declaration.
  5975. for (auto I : shadowedVar->redecls())
  5976. if (I->isFileVarDecl()) {
  5977. ShadowedDecl = I;
  5978. break;
  5979. }
  5980. }
  5981. DeclContext *OldDC = ShadowedDecl->getDeclContext();
  5982. unsigned WarningDiag = diag::warn_decl_shadow;
  5983. SourceLocation CaptureLoc;
  5984. if (isa<VarDecl>(ShadowedDecl) && NewDC && isa<CXXMethodDecl>(NewDC)) {
  5985. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  5986. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  5987. if (RD->getLambdaCaptureDefault() == LCD_None) {
  5988. // Try to avoid warnings for lambdas with an explicit capture list.
  5989. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  5990. // Warn only when the lambda captures the shadowed decl explicitly.
  5991. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  5992. if (CaptureLoc.isInvalid())
  5993. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  5994. } else {
  5995. // Remember that this was shadowed so we can avoid the warning if the
  5996. // shadowed decl isn't captured and the warning settings allow it.
  5997. cast<LambdaScopeInfo>(getCurFunction())
  5998. ->ShadowingDecls.push_back({D, cast<VarDecl>(ShadowedDecl)});
  5999. return;
  6000. }
  6001. }
  6002. }
  6003. }
  6004. // Only warn about certain kinds of shadowing for class members.
  6005. if (NewDC && NewDC->isRecord()) {
  6006. // In particular, don't warn about shadowing non-class members.
  6007. if (!OldDC->isRecord())
  6008. return;
  6009. // TODO: should we warn about static data members shadowing
  6010. // static data members from base classes?
  6011. // TODO: don't diagnose for inaccessible shadowed members.
  6012. // This is hard to do perfectly because we might friend the
  6013. // shadowing context, but that's just a false negative.
  6014. }
  6015. DeclarationName Name = R.getLookupName();
  6016. // Emit warning and note.
  6017. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  6018. return;
  6019. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  6020. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  6021. if (!CaptureLoc.isInvalid())
  6022. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6023. << Name << /*explicitly*/ 1;
  6024. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6025. }
  6026. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  6027. /// when these variables are captured by the lambda.
  6028. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  6029. for (const auto &Shadow : LSI->ShadowingDecls) {
  6030. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  6031. // Try to avoid the warning when the shadowed decl isn't captured.
  6032. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  6033. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6034. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  6035. ? diag::warn_decl_shadow_uncaptured_local
  6036. : diag::warn_decl_shadow)
  6037. << Shadow.VD->getDeclName()
  6038. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  6039. if (!CaptureLoc.isInvalid())
  6040. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6041. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  6042. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6043. }
  6044. }
  6045. /// \brief Check -Wshadow without the advantage of a previous lookup.
  6046. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  6047. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  6048. return;
  6049. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  6050. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  6051. LookupName(R, S);
  6052. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  6053. CheckShadow(D, ShadowedDecl, R);
  6054. }
  6055. /// Check if 'E', which is an expression that is about to be modified, refers
  6056. /// to a constructor parameter that shadows a field.
  6057. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  6058. // Quickly ignore expressions that can't be shadowing ctor parameters.
  6059. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  6060. return;
  6061. E = E->IgnoreParenImpCasts();
  6062. auto *DRE = dyn_cast<DeclRefExpr>(E);
  6063. if (!DRE)
  6064. return;
  6065. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  6066. auto I = ShadowingDecls.find(D);
  6067. if (I == ShadowingDecls.end())
  6068. return;
  6069. const NamedDecl *ShadowedDecl = I->second;
  6070. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6071. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  6072. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  6073. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6074. // Avoid issuing multiple warnings about the same decl.
  6075. ShadowingDecls.erase(I);
  6076. }
  6077. /// Check for conflict between this global or extern "C" declaration and
  6078. /// previous global or extern "C" declarations. This is only used in C++.
  6079. template<typename T>
  6080. static bool checkGlobalOrExternCConflict(
  6081. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  6082. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  6083. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  6084. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  6085. // The common case: this global doesn't conflict with any extern "C"
  6086. // declaration.
  6087. return false;
  6088. }
  6089. if (Prev) {
  6090. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  6091. // Both the old and new declarations have C language linkage. This is a
  6092. // redeclaration.
  6093. Previous.clear();
  6094. Previous.addDecl(Prev);
  6095. return true;
  6096. }
  6097. // This is a global, non-extern "C" declaration, and there is a previous
  6098. // non-global extern "C" declaration. Diagnose if this is a variable
  6099. // declaration.
  6100. if (!isa<VarDecl>(ND))
  6101. return false;
  6102. } else {
  6103. // The declaration is extern "C". Check for any declaration in the
  6104. // translation unit which might conflict.
  6105. if (IsGlobal) {
  6106. // We have already performed the lookup into the translation unit.
  6107. IsGlobal = false;
  6108. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6109. I != E; ++I) {
  6110. if (isa<VarDecl>(*I)) {
  6111. Prev = *I;
  6112. break;
  6113. }
  6114. }
  6115. } else {
  6116. DeclContext::lookup_result R =
  6117. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  6118. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  6119. I != E; ++I) {
  6120. if (isa<VarDecl>(*I)) {
  6121. Prev = *I;
  6122. break;
  6123. }
  6124. // FIXME: If we have any other entity with this name in global scope,
  6125. // the declaration is ill-formed, but that is a defect: it breaks the
  6126. // 'stat' hack, for instance. Only variables can have mangled name
  6127. // clashes with extern "C" declarations, so only they deserve a
  6128. // diagnostic.
  6129. }
  6130. }
  6131. if (!Prev)
  6132. return false;
  6133. }
  6134. // Use the first declaration's location to ensure we point at something which
  6135. // is lexically inside an extern "C" linkage-spec.
  6136. assert(Prev && "should have found a previous declaration to diagnose");
  6137. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  6138. Prev = FD->getFirstDecl();
  6139. else
  6140. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  6141. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  6142. << IsGlobal << ND;
  6143. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  6144. << IsGlobal;
  6145. return false;
  6146. }
  6147. /// Apply special rules for handling extern "C" declarations. Returns \c true
  6148. /// if we have found that this is a redeclaration of some prior entity.
  6149. ///
  6150. /// Per C++ [dcl.link]p6:
  6151. /// Two declarations [for a function or variable] with C language linkage
  6152. /// with the same name that appear in different scopes refer to the same
  6153. /// [entity]. An entity with C language linkage shall not be declared with
  6154. /// the same name as an entity in global scope.
  6155. template<typename T>
  6156. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  6157. LookupResult &Previous) {
  6158. if (!S.getLangOpts().CPlusPlus) {
  6159. // In C, when declaring a global variable, look for a corresponding 'extern'
  6160. // variable declared in function scope. We don't need this in C++, because
  6161. // we find local extern decls in the surrounding file-scope DeclContext.
  6162. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6163. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  6164. Previous.clear();
  6165. Previous.addDecl(Prev);
  6166. return true;
  6167. }
  6168. }
  6169. return false;
  6170. }
  6171. // A declaration in the translation unit can conflict with an extern "C"
  6172. // declaration.
  6173. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  6174. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  6175. // An extern "C" declaration can conflict with a declaration in the
  6176. // translation unit or can be a redeclaration of an extern "C" declaration
  6177. // in another scope.
  6178. if (isIncompleteDeclExternC(S,ND))
  6179. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  6180. // Neither global nor extern "C": nothing to do.
  6181. return false;
  6182. }
  6183. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  6184. // If the decl is already known invalid, don't check it.
  6185. if (NewVD->isInvalidDecl())
  6186. return;
  6187. TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
  6188. QualType T = TInfo->getType();
  6189. // Defer checking an 'auto' type until its initializer is attached.
  6190. if (T->isUndeducedType())
  6191. return;
  6192. if (NewVD->hasAttrs())
  6193. CheckAlignasUnderalignment(NewVD);
  6194. if (T->isObjCObjectType()) {
  6195. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  6196. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  6197. T = Context.getObjCObjectPointerType(T);
  6198. NewVD->setType(T);
  6199. }
  6200. // Emit an error if an address space was applied to decl with local storage.
  6201. // This includes arrays of objects with address space qualifiers, but not
  6202. // automatic variables that point to other address spaces.
  6203. // ISO/IEC TR 18037 S5.1.2
  6204. if (!getLangOpts().OpenCL
  6205. && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
  6206. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
  6207. NewVD->setInvalidDecl();
  6208. return;
  6209. }
  6210. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  6211. // scope.
  6212. if (getLangOpts().OpenCLVersion == 120 &&
  6213. !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
  6214. NewVD->isStaticLocal()) {
  6215. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  6216. NewVD->setInvalidDecl();
  6217. return;
  6218. }
  6219. if (getLangOpts().OpenCL) {
  6220. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  6221. if (NewVD->hasAttr<BlocksAttr>()) {
  6222. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  6223. return;
  6224. }
  6225. if (T->isBlockPointerType()) {
  6226. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  6227. // can't use 'extern' storage class.
  6228. if (!T.isConstQualified()) {
  6229. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  6230. << 0 /*const*/;
  6231. NewVD->setInvalidDecl();
  6232. return;
  6233. }
  6234. if (NewVD->hasExternalStorage()) {
  6235. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  6236. NewVD->setInvalidDecl();
  6237. return;
  6238. }
  6239. }
  6240. // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
  6241. // __constant address space.
  6242. // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
  6243. // variables inside a function can also be declared in the global
  6244. // address space.
  6245. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  6246. NewVD->hasExternalStorage()) {
  6247. if (!T->isSamplerT() &&
  6248. !(T.getAddressSpace() == LangAS::opencl_constant ||
  6249. (T.getAddressSpace() == LangAS::opencl_global &&
  6250. getLangOpts().OpenCLVersion == 200))) {
  6251. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  6252. if (getLangOpts().OpenCLVersion == 200)
  6253. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6254. << Scope << "global or constant";
  6255. else
  6256. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6257. << Scope << "constant";
  6258. NewVD->setInvalidDecl();
  6259. return;
  6260. }
  6261. } else {
  6262. if (T.getAddressSpace() == LangAS::opencl_global) {
  6263. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6264. << 1 /*is any function*/ << "global";
  6265. NewVD->setInvalidDecl();
  6266. return;
  6267. }
  6268. // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
  6269. // in functions.
  6270. if (T.getAddressSpace() == LangAS::opencl_constant ||
  6271. T.getAddressSpace() == LangAS::opencl_local) {
  6272. FunctionDecl *FD = getCurFunctionDecl();
  6273. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  6274. if (T.getAddressSpace() == LangAS::opencl_constant)
  6275. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6276. << 0 /*non-kernel only*/ << "constant";
  6277. else
  6278. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6279. << 0 /*non-kernel only*/ << "local";
  6280. NewVD->setInvalidDecl();
  6281. return;
  6282. }
  6283. }
  6284. }
  6285. }
  6286. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  6287. && !NewVD->hasAttr<BlocksAttr>()) {
  6288. if (getLangOpts().getGC() != LangOptions::NonGC)
  6289. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  6290. else {
  6291. assert(!getLangOpts().ObjCAutoRefCount);
  6292. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  6293. }
  6294. }
  6295. bool isVM = T->isVariablyModifiedType();
  6296. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  6297. NewVD->hasAttr<BlocksAttr>())
  6298. getCurFunction()->setHasBranchProtectedScope();
  6299. if ((isVM && NewVD->hasLinkage()) ||
  6300. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  6301. bool SizeIsNegative;
  6302. llvm::APSInt Oversized;
  6303. TypeSourceInfo *FixedTInfo =
  6304. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  6305. SizeIsNegative, Oversized);
  6306. if (!FixedTInfo && T->isVariableArrayType()) {
  6307. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  6308. // FIXME: This won't give the correct result for
  6309. // int a[10][n];
  6310. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  6311. if (NewVD->isFileVarDecl())
  6312. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  6313. << SizeRange;
  6314. else if (NewVD->isStaticLocal())
  6315. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  6316. << SizeRange;
  6317. else
  6318. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  6319. << SizeRange;
  6320. NewVD->setInvalidDecl();
  6321. return;
  6322. }
  6323. if (!FixedTInfo) {
  6324. if (NewVD->isFileVarDecl())
  6325. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  6326. else
  6327. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  6328. NewVD->setInvalidDecl();
  6329. return;
  6330. }
  6331. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  6332. NewVD->setType(FixedTInfo->getType());
  6333. NewVD->setTypeSourceInfo(FixedTInfo);
  6334. }
  6335. if (T->isVoidType()) {
  6336. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  6337. // of objects and functions.
  6338. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  6339. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  6340. << T;
  6341. NewVD->setInvalidDecl();
  6342. return;
  6343. }
  6344. }
  6345. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  6346. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  6347. NewVD->setInvalidDecl();
  6348. return;
  6349. }
  6350. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  6351. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  6352. NewVD->setInvalidDecl();
  6353. return;
  6354. }
  6355. if (NewVD->isConstexpr() && !T->isDependentType() &&
  6356. RequireLiteralType(NewVD->getLocation(), T,
  6357. diag::err_constexpr_var_non_literal)) {
  6358. NewVD->setInvalidDecl();
  6359. return;
  6360. }
  6361. }
  6362. /// \brief Perform semantic checking on a newly-created variable
  6363. /// declaration.
  6364. ///
  6365. /// This routine performs all of the type-checking required for a
  6366. /// variable declaration once it has been built. It is used both to
  6367. /// check variables after they have been parsed and their declarators
  6368. /// have been translated into a declaration, and to check variables
  6369. /// that have been instantiated from a template.
  6370. ///
  6371. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  6372. ///
  6373. /// Returns true if the variable declaration is a redeclaration.
  6374. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  6375. CheckVariableDeclarationType(NewVD);
  6376. // If the decl is already known invalid, don't check it.
  6377. if (NewVD->isInvalidDecl())
  6378. return false;
  6379. // If we did not find anything by this name, look for a non-visible
  6380. // extern "C" declaration with the same name.
  6381. if (Previous.empty() &&
  6382. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  6383. Previous.setShadowed();
  6384. if (!Previous.empty()) {
  6385. MergeVarDecl(NewVD, Previous);
  6386. return true;
  6387. }
  6388. return false;
  6389. }
  6390. namespace {
  6391. struct FindOverriddenMethod {
  6392. Sema *S;
  6393. CXXMethodDecl *Method;
  6394. /// Member lookup function that determines whether a given C++
  6395. /// method overrides a method in a base class, to be used with
  6396. /// CXXRecordDecl::lookupInBases().
  6397. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6398. RecordDecl *BaseRecord =
  6399. Specifier->getType()->getAs<RecordType>()->getDecl();
  6400. DeclarationName Name = Method->getDeclName();
  6401. // FIXME: Do we care about other names here too?
  6402. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6403. // We really want to find the base class destructor here.
  6404. QualType T = S->Context.getTypeDeclType(BaseRecord);
  6405. CanQualType CT = S->Context.getCanonicalType(T);
  6406. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  6407. }
  6408. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6409. Path.Decls = Path.Decls.slice(1)) {
  6410. NamedDecl *D = Path.Decls.front();
  6411. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6412. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  6413. return true;
  6414. }
  6415. }
  6416. return false;
  6417. }
  6418. };
  6419. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  6420. } // end anonymous namespace
  6421. /// \brief Report an error regarding overriding, along with any relevant
  6422. /// overriden methods.
  6423. ///
  6424. /// \param DiagID the primary error to report.
  6425. /// \param MD the overriding method.
  6426. /// \param OEK which overrides to include as notes.
  6427. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  6428. OverrideErrorKind OEK = OEK_All) {
  6429. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  6430. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  6431. E = MD->end_overridden_methods();
  6432. I != E; ++I) {
  6433. // This check (& the OEK parameter) could be replaced by a predicate, but
  6434. // without lambdas that would be overkill. This is still nicer than writing
  6435. // out the diag loop 3 times.
  6436. if ((OEK == OEK_All) ||
  6437. (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
  6438. (OEK == OEK_Deleted && (*I)->isDeleted()))
  6439. S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
  6440. }
  6441. }
  6442. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  6443. /// and if so, check that it's a valid override and remember it.
  6444. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  6445. // Look for methods in base classes that this method might override.
  6446. CXXBasePaths Paths;
  6447. FindOverriddenMethod FOM;
  6448. FOM.Method = MD;
  6449. FOM.S = this;
  6450. bool hasDeletedOverridenMethods = false;
  6451. bool hasNonDeletedOverridenMethods = false;
  6452. bool AddedAny = false;
  6453. if (DC->lookupInBases(FOM, Paths)) {
  6454. for (auto *I : Paths.found_decls()) {
  6455. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  6456. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  6457. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  6458. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  6459. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  6460. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  6461. hasDeletedOverridenMethods |= OldMD->isDeleted();
  6462. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  6463. AddedAny = true;
  6464. }
  6465. }
  6466. }
  6467. }
  6468. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  6469. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  6470. }
  6471. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  6472. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  6473. }
  6474. return AddedAny;
  6475. }
  6476. namespace {
  6477. // Struct for holding all of the extra arguments needed by
  6478. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  6479. struct ActOnFDArgs {
  6480. Scope *S;
  6481. Declarator &D;
  6482. MultiTemplateParamsArg TemplateParamLists;
  6483. bool AddToScope;
  6484. };
  6485. } // end anonymous namespace
  6486. namespace {
  6487. // Callback to only accept typo corrections that have a non-zero edit distance.
  6488. // Also only accept corrections that have the same parent decl.
  6489. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  6490. public:
  6491. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  6492. CXXRecordDecl *Parent)
  6493. : Context(Context), OriginalFD(TypoFD),
  6494. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  6495. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6496. if (candidate.getEditDistance() == 0)
  6497. return false;
  6498. SmallVector<unsigned, 1> MismatchedParams;
  6499. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  6500. CDeclEnd = candidate.end();
  6501. CDecl != CDeclEnd; ++CDecl) {
  6502. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6503. if (FD && !FD->hasBody() &&
  6504. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  6505. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  6506. CXXRecordDecl *Parent = MD->getParent();
  6507. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  6508. return true;
  6509. } else if (!ExpectedParent) {
  6510. return true;
  6511. }
  6512. }
  6513. }
  6514. return false;
  6515. }
  6516. private:
  6517. ASTContext &Context;
  6518. FunctionDecl *OriginalFD;
  6519. CXXRecordDecl *ExpectedParent;
  6520. };
  6521. } // end anonymous namespace
  6522. /// \brief Generate diagnostics for an invalid function redeclaration.
  6523. ///
  6524. /// This routine handles generating the diagnostic messages for an invalid
  6525. /// function redeclaration, including finding possible similar declarations
  6526. /// or performing typo correction if there are no previous declarations with
  6527. /// the same name.
  6528. ///
  6529. /// Returns a NamedDecl iff typo correction was performed and substituting in
  6530. /// the new declaration name does not cause new errors.
  6531. static NamedDecl *DiagnoseInvalidRedeclaration(
  6532. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  6533. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  6534. DeclarationName Name = NewFD->getDeclName();
  6535. DeclContext *NewDC = NewFD->getDeclContext();
  6536. SmallVector<unsigned, 1> MismatchedParams;
  6537. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  6538. TypoCorrection Correction;
  6539. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  6540. unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
  6541. : diag::err_member_decl_does_not_match;
  6542. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  6543. IsLocalFriend ? Sema::LookupLocalFriendName
  6544. : Sema::LookupOrdinaryName,
  6545. Sema::ForRedeclaration);
  6546. NewFD->setInvalidDecl();
  6547. if (IsLocalFriend)
  6548. SemaRef.LookupName(Prev, S);
  6549. else
  6550. SemaRef.LookupQualifiedName(Prev, NewDC);
  6551. assert(!Prev.isAmbiguous() &&
  6552. "Cannot have an ambiguity in previous-declaration lookup");
  6553. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  6554. if (!Prev.empty()) {
  6555. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  6556. Func != FuncEnd; ++Func) {
  6557. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  6558. if (FD &&
  6559. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6560. // Add 1 to the index so that 0 can mean the mismatch didn't
  6561. // involve a parameter
  6562. unsigned ParamNum =
  6563. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  6564. NearMatches.push_back(std::make_pair(FD, ParamNum));
  6565. }
  6566. }
  6567. // If the qualified name lookup yielded nothing, try typo correction
  6568. } else if ((Correction = SemaRef.CorrectTypo(
  6569. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  6570. &ExtraArgs.D.getCXXScopeSpec(),
  6571. llvm::make_unique<DifferentNameValidatorCCC>(
  6572. SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
  6573. Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
  6574. // Set up everything for the call to ActOnFunctionDeclarator
  6575. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  6576. ExtraArgs.D.getIdentifierLoc());
  6577. Previous.clear();
  6578. Previous.setLookupName(Correction.getCorrection());
  6579. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  6580. CDeclEnd = Correction.end();
  6581. CDecl != CDeclEnd; ++CDecl) {
  6582. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6583. if (FD && !FD->hasBody() &&
  6584. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6585. Previous.addDecl(FD);
  6586. }
  6587. }
  6588. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  6589. NamedDecl *Result;
  6590. // Retry building the function declaration with the new previous
  6591. // declarations, and with errors suppressed.
  6592. {
  6593. // Trap errors.
  6594. Sema::SFINAETrap Trap(SemaRef);
  6595. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  6596. // pieces need to verify the typo-corrected C++ declaration and hopefully
  6597. // eliminate the need for the parameter pack ExtraArgs.
  6598. Result = SemaRef.ActOnFunctionDeclarator(
  6599. ExtraArgs.S, ExtraArgs.D,
  6600. Correction.getCorrectionDecl()->getDeclContext(),
  6601. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  6602. ExtraArgs.AddToScope);
  6603. if (Trap.hasErrorOccurred())
  6604. Result = nullptr;
  6605. }
  6606. if (Result) {
  6607. // Determine which correction we picked.
  6608. Decl *Canonical = Result->getCanonicalDecl();
  6609. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6610. I != E; ++I)
  6611. if ((*I)->getCanonicalDecl() == Canonical)
  6612. Correction.setCorrectionDecl(*I);
  6613. SemaRef.diagnoseTypo(
  6614. Correction,
  6615. SemaRef.PDiag(IsLocalFriend
  6616. ? diag::err_no_matching_local_friend_suggest
  6617. : diag::err_member_decl_does_not_match_suggest)
  6618. << Name << NewDC << IsDefinition);
  6619. return Result;
  6620. }
  6621. // Pretend the typo correction never occurred
  6622. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  6623. ExtraArgs.D.getIdentifierLoc());
  6624. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  6625. Previous.clear();
  6626. Previous.setLookupName(Name);
  6627. }
  6628. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  6629. << Name << NewDC << IsDefinition << NewFD->getLocation();
  6630. bool NewFDisConst = false;
  6631. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  6632. NewFDisConst = NewMD->isConst();
  6633. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  6634. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  6635. NearMatch != NearMatchEnd; ++NearMatch) {
  6636. FunctionDecl *FD = NearMatch->first;
  6637. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6638. bool FDisConst = MD && MD->isConst();
  6639. bool IsMember = MD || !IsLocalFriend;
  6640. // FIXME: These notes are poorly worded for the local friend case.
  6641. if (unsigned Idx = NearMatch->second) {
  6642. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  6643. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  6644. if (Loc.isInvalid()) Loc = FD->getLocation();
  6645. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  6646. : diag::note_local_decl_close_param_match)
  6647. << Idx << FDParam->getType()
  6648. << NewFD->getParamDecl(Idx - 1)->getType();
  6649. } else if (FDisConst != NewFDisConst) {
  6650. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  6651. << NewFDisConst << FD->getSourceRange().getEnd();
  6652. } else
  6653. SemaRef.Diag(FD->getLocation(),
  6654. IsMember ? diag::note_member_def_close_match
  6655. : diag::note_local_decl_close_match);
  6656. }
  6657. return nullptr;
  6658. }
  6659. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  6660. switch (D.getDeclSpec().getStorageClassSpec()) {
  6661. default: llvm_unreachable("Unknown storage class!");
  6662. case DeclSpec::SCS_auto:
  6663. case DeclSpec::SCS_register:
  6664. case DeclSpec::SCS_mutable:
  6665. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6666. diag::err_typecheck_sclass_func);
  6667. D.getMutableDeclSpec().ClearStorageClassSpecs();
  6668. D.setInvalidType();
  6669. break;
  6670. case DeclSpec::SCS_unspecified: break;
  6671. case DeclSpec::SCS_extern:
  6672. if (D.getDeclSpec().isExternInLinkageSpec())
  6673. return SC_None;
  6674. return SC_Extern;
  6675. case DeclSpec::SCS_static: {
  6676. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  6677. // C99 6.7.1p5:
  6678. // The declaration of an identifier for a function that has
  6679. // block scope shall have no explicit storage-class specifier
  6680. // other than extern
  6681. // See also (C++ [dcl.stc]p4).
  6682. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6683. diag::err_static_block_func);
  6684. break;
  6685. } else
  6686. return SC_Static;
  6687. }
  6688. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  6689. }
  6690. // No explicit storage class has already been returned
  6691. return SC_None;
  6692. }
  6693. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  6694. DeclContext *DC, QualType &R,
  6695. TypeSourceInfo *TInfo,
  6696. StorageClass SC,
  6697. bool &IsVirtualOkay) {
  6698. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  6699. DeclarationName Name = NameInfo.getName();
  6700. FunctionDecl *NewFD = nullptr;
  6701. bool isInline = D.getDeclSpec().isInlineSpecified();
  6702. if (!SemaRef.getLangOpts().CPlusPlus) {
  6703. // Determine whether the function was written with a
  6704. // prototype. This true when:
  6705. // - there is a prototype in the declarator, or
  6706. // - the type R of the function is some kind of typedef or other non-
  6707. // attributed reference to a type name (which eventually refers to a
  6708. // function type).
  6709. bool HasPrototype =
  6710. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  6711. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  6712. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  6713. D.getLocStart(), NameInfo, R,
  6714. TInfo, SC, isInline,
  6715. HasPrototype, false);
  6716. if (D.isInvalidType())
  6717. NewFD->setInvalidDecl();
  6718. return NewFD;
  6719. }
  6720. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  6721. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  6722. // Check that the return type is not an abstract class type.
  6723. // For record types, this is done by the AbstractClassUsageDiagnoser once
  6724. // the class has been completely parsed.
  6725. if (!DC->isRecord() &&
  6726. SemaRef.RequireNonAbstractType(
  6727. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  6728. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  6729. D.setInvalidType();
  6730. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  6731. // This is a C++ constructor declaration.
  6732. assert(DC->isRecord() &&
  6733. "Constructors can only be declared in a member context");
  6734. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  6735. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  6736. D.getLocStart(), NameInfo,
  6737. R, TInfo, isExplicit, isInline,
  6738. /*isImplicitlyDeclared=*/false,
  6739. isConstexpr);
  6740. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6741. // This is a C++ destructor declaration.
  6742. if (DC->isRecord()) {
  6743. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  6744. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  6745. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  6746. SemaRef.Context, Record,
  6747. D.getLocStart(),
  6748. NameInfo, R, TInfo, isInline,
  6749. /*isImplicitlyDeclared=*/false);
  6750. // If the class is complete, then we now create the implicit exception
  6751. // specification. If the class is incomplete or dependent, we can't do
  6752. // it yet.
  6753. if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
  6754. Record->getDefinition() && !Record->isBeingDefined() &&
  6755. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  6756. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  6757. }
  6758. IsVirtualOkay = true;
  6759. return NewDD;
  6760. } else {
  6761. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  6762. D.setInvalidType();
  6763. // Create a FunctionDecl to satisfy the function definition parsing
  6764. // code path.
  6765. return FunctionDecl::Create(SemaRef.Context, DC,
  6766. D.getLocStart(),
  6767. D.getIdentifierLoc(), Name, R, TInfo,
  6768. SC, isInline,
  6769. /*hasPrototype=*/true, isConstexpr);
  6770. }
  6771. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  6772. if (!DC->isRecord()) {
  6773. SemaRef.Diag(D.getIdentifierLoc(),
  6774. diag::err_conv_function_not_member);
  6775. return nullptr;
  6776. }
  6777. SemaRef.CheckConversionDeclarator(D, R, SC);
  6778. IsVirtualOkay = true;
  6779. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  6780. D.getLocStart(), NameInfo,
  6781. R, TInfo, isInline, isExplicit,
  6782. isConstexpr, SourceLocation());
  6783. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  6784. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  6785. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
  6786. isExplicit, NameInfo, R, TInfo,
  6787. D.getLocEnd());
  6788. } else if (DC->isRecord()) {
  6789. // If the name of the function is the same as the name of the record,
  6790. // then this must be an invalid constructor that has a return type.
  6791. // (The parser checks for a return type and makes the declarator a
  6792. // constructor if it has no return type).
  6793. if (Name.getAsIdentifierInfo() &&
  6794. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  6795. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  6796. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  6797. << SourceRange(D.getIdentifierLoc());
  6798. return nullptr;
  6799. }
  6800. // This is a C++ method declaration.
  6801. CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
  6802. cast<CXXRecordDecl>(DC),
  6803. D.getLocStart(), NameInfo, R,
  6804. TInfo, SC, isInline,
  6805. isConstexpr, SourceLocation());
  6806. IsVirtualOkay = !Ret->isStatic();
  6807. return Ret;
  6808. } else {
  6809. bool isFriend =
  6810. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  6811. if (!isFriend && SemaRef.CurContext->isRecord())
  6812. return nullptr;
  6813. // Determine whether the function was written with a
  6814. // prototype. This true when:
  6815. // - we're in C++ (where every function has a prototype),
  6816. return FunctionDecl::Create(SemaRef.Context, DC,
  6817. D.getLocStart(),
  6818. NameInfo, R, TInfo, SC, isInline,
  6819. true/*HasPrototype*/, isConstexpr);
  6820. }
  6821. }
  6822. enum OpenCLParamType {
  6823. ValidKernelParam,
  6824. PtrPtrKernelParam,
  6825. PtrKernelParam,
  6826. InvalidAddrSpacePtrKernelParam,
  6827. InvalidKernelParam,
  6828. RecordKernelParam
  6829. };
  6830. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  6831. if (PT->isPointerType()) {
  6832. QualType PointeeType = PT->getPointeeType();
  6833. if (PointeeType->isPointerType())
  6834. return PtrPtrKernelParam;
  6835. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  6836. PointeeType.getAddressSpace() == 0)
  6837. return InvalidAddrSpacePtrKernelParam;
  6838. return PtrKernelParam;
  6839. }
  6840. // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
  6841. // be used as builtin types.
  6842. if (PT->isImageType())
  6843. return PtrKernelParam;
  6844. if (PT->isBooleanType())
  6845. return InvalidKernelParam;
  6846. if (PT->isEventT())
  6847. return InvalidKernelParam;
  6848. // OpenCL extension spec v1.2 s9.5:
  6849. // This extension adds support for half scalar and vector types as built-in
  6850. // types that can be used for arithmetic operations, conversions etc.
  6851. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
  6852. return InvalidKernelParam;
  6853. if (PT->isRecordType())
  6854. return RecordKernelParam;
  6855. return ValidKernelParam;
  6856. }
  6857. static void checkIsValidOpenCLKernelParameter(
  6858. Sema &S,
  6859. Declarator &D,
  6860. ParmVarDecl *Param,
  6861. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  6862. QualType PT = Param->getType();
  6863. // Cache the valid types we encounter to avoid rechecking structs that are
  6864. // used again
  6865. if (ValidTypes.count(PT.getTypePtr()))
  6866. return;
  6867. switch (getOpenCLKernelParameterType(S, PT)) {
  6868. case PtrPtrKernelParam:
  6869. // OpenCL v1.2 s6.9.a:
  6870. // A kernel function argument cannot be declared as a
  6871. // pointer to a pointer type.
  6872. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  6873. D.setInvalidType();
  6874. return;
  6875. case InvalidAddrSpacePtrKernelParam:
  6876. // OpenCL v1.0 s6.5:
  6877. // __kernel function arguments declared to be a pointer of a type can point
  6878. // to one of the following address spaces only : __global, __local or
  6879. // __constant.
  6880. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  6881. D.setInvalidType();
  6882. return;
  6883. // OpenCL v1.2 s6.9.k:
  6884. // Arguments to kernel functions in a program cannot be declared with the
  6885. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  6886. // uintptr_t or a struct and/or union that contain fields declared to be
  6887. // one of these built-in scalar types.
  6888. case InvalidKernelParam:
  6889. // OpenCL v1.2 s6.8 n:
  6890. // A kernel function argument cannot be declared
  6891. // of event_t type.
  6892. // Do not diagnose half type since it is diagnosed as invalid argument
  6893. // type for any function elsewhere.
  6894. if (!PT->isHalfType())
  6895. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  6896. D.setInvalidType();
  6897. return;
  6898. case PtrKernelParam:
  6899. case ValidKernelParam:
  6900. ValidTypes.insert(PT.getTypePtr());
  6901. return;
  6902. case RecordKernelParam:
  6903. break;
  6904. }
  6905. // Track nested structs we will inspect
  6906. SmallVector<const Decl *, 4> VisitStack;
  6907. // Track where we are in the nested structs. Items will migrate from
  6908. // VisitStack to HistoryStack as we do the DFS for bad field.
  6909. SmallVector<const FieldDecl *, 4> HistoryStack;
  6910. HistoryStack.push_back(nullptr);
  6911. const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
  6912. VisitStack.push_back(PD);
  6913. assert(VisitStack.back() && "First decl null?");
  6914. do {
  6915. const Decl *Next = VisitStack.pop_back_val();
  6916. if (!Next) {
  6917. assert(!HistoryStack.empty());
  6918. // Found a marker, we have gone up a level
  6919. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  6920. ValidTypes.insert(Hist->getType().getTypePtr());
  6921. continue;
  6922. }
  6923. // Adds everything except the original parameter declaration (which is not a
  6924. // field itself) to the history stack.
  6925. const RecordDecl *RD;
  6926. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  6927. HistoryStack.push_back(Field);
  6928. RD = Field->getType()->castAs<RecordType>()->getDecl();
  6929. } else {
  6930. RD = cast<RecordDecl>(Next);
  6931. }
  6932. // Add a null marker so we know when we've gone back up a level
  6933. VisitStack.push_back(nullptr);
  6934. for (const auto *FD : RD->fields()) {
  6935. QualType QT = FD->getType();
  6936. if (ValidTypes.count(QT.getTypePtr()))
  6937. continue;
  6938. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  6939. if (ParamType == ValidKernelParam)
  6940. continue;
  6941. if (ParamType == RecordKernelParam) {
  6942. VisitStack.push_back(FD);
  6943. continue;
  6944. }
  6945. // OpenCL v1.2 s6.9.p:
  6946. // Arguments to kernel functions that are declared to be a struct or union
  6947. // do not allow OpenCL objects to be passed as elements of the struct or
  6948. // union.
  6949. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  6950. ParamType == InvalidAddrSpacePtrKernelParam) {
  6951. S.Diag(Param->getLocation(),
  6952. diag::err_record_with_pointers_kernel_param)
  6953. << PT->isUnionType()
  6954. << PT;
  6955. } else {
  6956. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  6957. }
  6958. S.Diag(PD->getLocation(), diag::note_within_field_of_type)
  6959. << PD->getDeclName();
  6960. // We have an error, now let's go back up through history and show where
  6961. // the offending field came from
  6962. for (ArrayRef<const FieldDecl *>::const_iterator
  6963. I = HistoryStack.begin() + 1,
  6964. E = HistoryStack.end();
  6965. I != E; ++I) {
  6966. const FieldDecl *OuterField = *I;
  6967. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  6968. << OuterField->getType();
  6969. }
  6970. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  6971. << QT->isPointerType()
  6972. << QT;
  6973. D.setInvalidType();
  6974. return;
  6975. }
  6976. } while (!VisitStack.empty());
  6977. }
  6978. /// Find the DeclContext in which a tag is implicitly declared if we see an
  6979. /// elaborated type specifier in the specified context, and lookup finds
  6980. /// nothing.
  6981. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  6982. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  6983. DC = DC->getParent();
  6984. return DC;
  6985. }
  6986. /// Find the Scope in which a tag is implicitly declared if we see an
  6987. /// elaborated type specifier in the specified context, and lookup finds
  6988. /// nothing.
  6989. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  6990. while (S->isClassScope() ||
  6991. (LangOpts.CPlusPlus &&
  6992. S->isFunctionPrototypeScope()) ||
  6993. ((S->getFlags() & Scope::DeclScope) == 0) ||
  6994. (S->getEntity() && S->getEntity()->isTransparentContext()))
  6995. S = S->getParent();
  6996. return S;
  6997. }
  6998. NamedDecl*
  6999. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  7000. TypeSourceInfo *TInfo, LookupResult &Previous,
  7001. MultiTemplateParamsArg TemplateParamLists,
  7002. bool &AddToScope) {
  7003. QualType R = TInfo->getType();
  7004. assert(R.getTypePtr()->isFunctionType());
  7005. // TODO: consider using NameInfo for diagnostic.
  7006. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  7007. DeclarationName Name = NameInfo.getName();
  7008. StorageClass SC = getFunctionStorageClass(*this, D);
  7009. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  7010. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  7011. diag::err_invalid_thread)
  7012. << DeclSpec::getSpecifierName(TSCS);
  7013. if (D.isFirstDeclarationOfMember())
  7014. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  7015. D.getIdentifierLoc());
  7016. bool isFriend = false;
  7017. FunctionTemplateDecl *FunctionTemplate = nullptr;
  7018. bool isMemberSpecialization = false;
  7019. bool isFunctionTemplateSpecialization = false;
  7020. bool isDependentClassScopeExplicitSpecialization = false;
  7021. bool HasExplicitTemplateArgs = false;
  7022. TemplateArgumentListInfo TemplateArgs;
  7023. bool isVirtualOkay = false;
  7024. DeclContext *OriginalDC = DC;
  7025. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  7026. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  7027. isVirtualOkay);
  7028. if (!NewFD) return nullptr;
  7029. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  7030. NewFD->setTopLevelDeclInObjCContainer();
  7031. // Set the lexical context. If this is a function-scope declaration, or has a
  7032. // C++ scope specifier, or is the object of a friend declaration, the lexical
  7033. // context will be different from the semantic context.
  7034. NewFD->setLexicalDeclContext(CurContext);
  7035. if (IsLocalExternDecl)
  7036. NewFD->setLocalExternDecl();
  7037. if (getLangOpts().CPlusPlus) {
  7038. bool isInline = D.getDeclSpec().isInlineSpecified();
  7039. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7040. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  7041. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  7042. bool isConcept = D.getDeclSpec().isConceptSpecified();
  7043. isFriend = D.getDeclSpec().isFriendSpecified();
  7044. if (isFriend && !isInline && D.isFunctionDefinition()) {
  7045. // C++ [class.friend]p5
  7046. // A function can be defined in a friend declaration of a
  7047. // class . . . . Such a function is implicitly inline.
  7048. NewFD->setImplicitlyInline();
  7049. }
  7050. // If this is a method defined in an __interface, and is not a constructor
  7051. // or an overloaded operator, then set the pure flag (isVirtual will already
  7052. // return true).
  7053. if (const CXXRecordDecl *Parent =
  7054. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  7055. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  7056. NewFD->setPure(true);
  7057. // C++ [class.union]p2
  7058. // A union can have member functions, but not virtual functions.
  7059. if (isVirtual && Parent->isUnion())
  7060. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  7061. }
  7062. SetNestedNameSpecifier(NewFD, D);
  7063. isMemberSpecialization = false;
  7064. isFunctionTemplateSpecialization = false;
  7065. if (D.isInvalidType())
  7066. NewFD->setInvalidDecl();
  7067. // Match up the template parameter lists with the scope specifier, then
  7068. // determine whether we have a template or a template specialization.
  7069. bool Invalid = false;
  7070. if (TemplateParameterList *TemplateParams =
  7071. MatchTemplateParametersToScopeSpecifier(
  7072. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  7073. D.getCXXScopeSpec(),
  7074. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  7075. ? D.getName().TemplateId
  7076. : nullptr,
  7077. TemplateParamLists, isFriend, isMemberSpecialization,
  7078. Invalid)) {
  7079. if (TemplateParams->size() > 0) {
  7080. // This is a function template
  7081. // Check that we can declare a template here.
  7082. if (CheckTemplateDeclScope(S, TemplateParams))
  7083. NewFD->setInvalidDecl();
  7084. // A destructor cannot be a template.
  7085. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7086. Diag(NewFD->getLocation(), diag::err_destructor_template);
  7087. NewFD->setInvalidDecl();
  7088. }
  7089. // If we're adding a template to a dependent context, we may need to
  7090. // rebuilding some of the types used within the template parameter list,
  7091. // now that we know what the current instantiation is.
  7092. if (DC->isDependentContext()) {
  7093. ContextRAII SavedContext(*this, DC);
  7094. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  7095. Invalid = true;
  7096. }
  7097. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  7098. NewFD->getLocation(),
  7099. Name, TemplateParams,
  7100. NewFD);
  7101. FunctionTemplate->setLexicalDeclContext(CurContext);
  7102. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  7103. // For source fidelity, store the other template param lists.
  7104. if (TemplateParamLists.size() > 1) {
  7105. NewFD->setTemplateParameterListsInfo(Context,
  7106. TemplateParamLists.drop_back(1));
  7107. }
  7108. } else {
  7109. // This is a function template specialization.
  7110. isFunctionTemplateSpecialization = true;
  7111. // For source fidelity, store all the template param lists.
  7112. if (TemplateParamLists.size() > 0)
  7113. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7114. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  7115. if (isFriend) {
  7116. // We want to remove the "template<>", found here.
  7117. SourceRange RemoveRange = TemplateParams->getSourceRange();
  7118. // If we remove the template<> and the name is not a
  7119. // template-id, we're actually silently creating a problem:
  7120. // the friend declaration will refer to an untemplated decl,
  7121. // and clearly the user wants a template specialization. So
  7122. // we need to insert '<>' after the name.
  7123. SourceLocation InsertLoc;
  7124. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  7125. InsertLoc = D.getName().getSourceRange().getEnd();
  7126. InsertLoc = getLocForEndOfToken(InsertLoc);
  7127. }
  7128. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  7129. << Name << RemoveRange
  7130. << FixItHint::CreateRemoval(RemoveRange)
  7131. << FixItHint::CreateInsertion(InsertLoc, "<>");
  7132. }
  7133. }
  7134. }
  7135. else {
  7136. // All template param lists were matched against the scope specifier:
  7137. // this is NOT (an explicit specialization of) a template.
  7138. if (TemplateParamLists.size() > 0)
  7139. // For source fidelity, store all the template param lists.
  7140. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7141. }
  7142. if (Invalid) {
  7143. NewFD->setInvalidDecl();
  7144. if (FunctionTemplate)
  7145. FunctionTemplate->setInvalidDecl();
  7146. }
  7147. // C++ [dcl.fct.spec]p5:
  7148. // The virtual specifier shall only be used in declarations of
  7149. // nonstatic class member functions that appear within a
  7150. // member-specification of a class declaration; see 10.3.
  7151. //
  7152. if (isVirtual && !NewFD->isInvalidDecl()) {
  7153. if (!isVirtualOkay) {
  7154. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7155. diag::err_virtual_non_function);
  7156. } else if (!CurContext->isRecord()) {
  7157. // 'virtual' was specified outside of the class.
  7158. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7159. diag::err_virtual_out_of_class)
  7160. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7161. } else if (NewFD->getDescribedFunctionTemplate()) {
  7162. // C++ [temp.mem]p3:
  7163. // A member function template shall not be virtual.
  7164. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7165. diag::err_virtual_member_function_template)
  7166. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7167. } else {
  7168. // Okay: Add virtual to the method.
  7169. NewFD->setVirtualAsWritten(true);
  7170. }
  7171. if (getLangOpts().CPlusPlus14 &&
  7172. NewFD->getReturnType()->isUndeducedType())
  7173. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  7174. }
  7175. if (getLangOpts().CPlusPlus14 &&
  7176. (NewFD->isDependentContext() ||
  7177. (isFriend && CurContext->isDependentContext())) &&
  7178. NewFD->getReturnType()->isUndeducedType()) {
  7179. // If the function template is referenced directly (for instance, as a
  7180. // member of the current instantiation), pretend it has a dependent type.
  7181. // This is not really justified by the standard, but is the only sane
  7182. // thing to do.
  7183. // FIXME: For a friend function, we have not marked the function as being
  7184. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  7185. const FunctionProtoType *FPT =
  7186. NewFD->getType()->castAs<FunctionProtoType>();
  7187. QualType Result =
  7188. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  7189. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  7190. FPT->getExtProtoInfo()));
  7191. }
  7192. // C++ [dcl.fct.spec]p3:
  7193. // The inline specifier shall not appear on a block scope function
  7194. // declaration.
  7195. if (isInline && !NewFD->isInvalidDecl()) {
  7196. if (CurContext->isFunctionOrMethod()) {
  7197. // 'inline' is not allowed on block scope function declaration.
  7198. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7199. diag::err_inline_declaration_block_scope) << Name
  7200. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7201. }
  7202. }
  7203. // C++ [dcl.fct.spec]p6:
  7204. // The explicit specifier shall be used only in the declaration of a
  7205. // constructor or conversion function within its class definition;
  7206. // see 12.3.1 and 12.3.2.
  7207. if (isExplicit && !NewFD->isInvalidDecl() &&
  7208. !isa<CXXDeductionGuideDecl>(NewFD)) {
  7209. if (!CurContext->isRecord()) {
  7210. // 'explicit' was specified outside of the class.
  7211. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7212. diag::err_explicit_out_of_class)
  7213. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  7214. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  7215. !isa<CXXConversionDecl>(NewFD)) {
  7216. // 'explicit' was specified on a function that wasn't a constructor
  7217. // or conversion function.
  7218. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7219. diag::err_explicit_non_ctor_or_conv_function)
  7220. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  7221. }
  7222. }
  7223. if (isConstexpr) {
  7224. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  7225. // are implicitly inline.
  7226. NewFD->setImplicitlyInline();
  7227. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  7228. // be either constructors or to return a literal type. Therefore,
  7229. // destructors cannot be declared constexpr.
  7230. if (isa<CXXDestructorDecl>(NewFD))
  7231. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  7232. }
  7233. if (isConcept) {
  7234. // This is a function concept.
  7235. if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
  7236. FTD->setConcept();
  7237. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  7238. // applied only to the definition of a function template [...]
  7239. if (!D.isFunctionDefinition()) {
  7240. Diag(D.getDeclSpec().getConceptSpecLoc(),
  7241. diag::err_function_concept_not_defined);
  7242. NewFD->setInvalidDecl();
  7243. }
  7244. // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
  7245. // have no exception-specification and is treated as if it were specified
  7246. // with noexcept(true) (15.4). [...]
  7247. if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
  7248. if (FPT->hasExceptionSpec()) {
  7249. SourceRange Range;
  7250. if (D.isFunctionDeclarator())
  7251. Range = D.getFunctionTypeInfo().getExceptionSpecRange();
  7252. Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
  7253. << FixItHint::CreateRemoval(Range);
  7254. NewFD->setInvalidDecl();
  7255. } else {
  7256. Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
  7257. }
  7258. // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
  7259. // following restrictions:
  7260. // - The declared return type shall have the type bool.
  7261. if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
  7262. Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
  7263. NewFD->setInvalidDecl();
  7264. }
  7265. // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
  7266. // following restrictions:
  7267. // - The declaration's parameter list shall be equivalent to an empty
  7268. // parameter list.
  7269. if (FPT->getNumParams() > 0 || FPT->isVariadic())
  7270. Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
  7271. }
  7272. // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
  7273. // implicity defined to be a constexpr declaration (implicitly inline)
  7274. NewFD->setImplicitlyInline();
  7275. // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
  7276. // be declared with the thread_local, inline, friend, or constexpr
  7277. // specifiers, [...]
  7278. if (isInline) {
  7279. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7280. diag::err_concept_decl_invalid_specifiers)
  7281. << 1 << 1;
  7282. NewFD->setInvalidDecl(true);
  7283. }
  7284. if (isFriend) {
  7285. Diag(D.getDeclSpec().getFriendSpecLoc(),
  7286. diag::err_concept_decl_invalid_specifiers)
  7287. << 1 << 2;
  7288. NewFD->setInvalidDecl(true);
  7289. }
  7290. if (isConstexpr) {
  7291. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  7292. diag::err_concept_decl_invalid_specifiers)
  7293. << 1 << 3;
  7294. NewFD->setInvalidDecl(true);
  7295. }
  7296. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  7297. // applied only to the definition of a function template or variable
  7298. // template, declared in namespace scope.
  7299. if (isFunctionTemplateSpecialization) {
  7300. Diag(D.getDeclSpec().getConceptSpecLoc(),
  7301. diag::err_concept_specified_specialization) << 1;
  7302. NewFD->setInvalidDecl(true);
  7303. return NewFD;
  7304. }
  7305. }
  7306. // If __module_private__ was specified, mark the function accordingly.
  7307. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7308. if (isFunctionTemplateSpecialization) {
  7309. SourceLocation ModulePrivateLoc
  7310. = D.getDeclSpec().getModulePrivateSpecLoc();
  7311. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  7312. << 0
  7313. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7314. } else {
  7315. NewFD->setModulePrivate();
  7316. if (FunctionTemplate)
  7317. FunctionTemplate->setModulePrivate();
  7318. }
  7319. }
  7320. if (isFriend) {
  7321. if (FunctionTemplate) {
  7322. FunctionTemplate->setObjectOfFriendDecl();
  7323. FunctionTemplate->setAccess(AS_public);
  7324. }
  7325. NewFD->setObjectOfFriendDecl();
  7326. NewFD->setAccess(AS_public);
  7327. }
  7328. // If a function is defined as defaulted or deleted, mark it as such now.
  7329. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  7330. // definition kind to FDK_Definition.
  7331. switch (D.getFunctionDefinitionKind()) {
  7332. case FDK_Declaration:
  7333. case FDK_Definition:
  7334. break;
  7335. case FDK_Defaulted:
  7336. NewFD->setDefaulted();
  7337. break;
  7338. case FDK_Deleted:
  7339. NewFD->setDeletedAsWritten();
  7340. break;
  7341. }
  7342. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  7343. D.isFunctionDefinition()) {
  7344. // C++ [class.mfct]p2:
  7345. // A member function may be defined (8.4) in its class definition, in
  7346. // which case it is an inline member function (7.1.2)
  7347. NewFD->setImplicitlyInline();
  7348. }
  7349. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  7350. !CurContext->isRecord()) {
  7351. // C++ [class.static]p1:
  7352. // A data or function member of a class may be declared static
  7353. // in a class definition, in which case it is a static member of
  7354. // the class.
  7355. // Complain about the 'static' specifier if it's on an out-of-line
  7356. // member function definition.
  7357. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7358. diag::err_static_out_of_line)
  7359. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7360. }
  7361. // C++11 [except.spec]p15:
  7362. // A deallocation function with no exception-specification is treated
  7363. // as if it were specified with noexcept(true).
  7364. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  7365. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  7366. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  7367. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  7368. NewFD->setType(Context.getFunctionType(
  7369. FPT->getReturnType(), FPT->getParamTypes(),
  7370. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  7371. }
  7372. // Filter out previous declarations that don't match the scope.
  7373. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  7374. D.getCXXScopeSpec().isNotEmpty() ||
  7375. isMemberSpecialization ||
  7376. isFunctionTemplateSpecialization);
  7377. // Handle GNU asm-label extension (encoded as an attribute).
  7378. if (Expr *E = (Expr*) D.getAsmLabel()) {
  7379. // The parser guarantees this is a string.
  7380. StringLiteral *SE = cast<StringLiteral>(E);
  7381. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  7382. SE->getString(), 0));
  7383. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7384. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7385. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  7386. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7387. if (isDeclExternC(NewFD)) {
  7388. NewFD->addAttr(I->second);
  7389. ExtnameUndeclaredIdentifiers.erase(I);
  7390. } else
  7391. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  7392. << /*Variable*/0 << NewFD;
  7393. }
  7394. }
  7395. // Copy the parameter declarations from the declarator D to the function
  7396. // declaration NewFD, if they are available. First scavenge them into Params.
  7397. SmallVector<ParmVarDecl*, 16> Params;
  7398. unsigned FTIIdx;
  7399. if (D.isFunctionDeclarator(FTIIdx)) {
  7400. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  7401. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  7402. // function that takes no arguments, not a function that takes a
  7403. // single void argument.
  7404. // We let through "const void" here because Sema::GetTypeForDeclarator
  7405. // already checks for that case.
  7406. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  7407. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  7408. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  7409. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  7410. Param->setDeclContext(NewFD);
  7411. Params.push_back(Param);
  7412. if (Param->isInvalidDecl())
  7413. NewFD->setInvalidDecl();
  7414. }
  7415. }
  7416. if (!getLangOpts().CPlusPlus) {
  7417. // In C, find all the tag declarations from the prototype and move them
  7418. // into the function DeclContext. Remove them from the surrounding tag
  7419. // injection context of the function, which is typically but not always
  7420. // the TU.
  7421. DeclContext *PrototypeTagContext =
  7422. getTagInjectionContext(NewFD->getLexicalDeclContext());
  7423. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  7424. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  7425. // We don't want to reparent enumerators. Look at their parent enum
  7426. // instead.
  7427. if (!TD) {
  7428. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  7429. TD = cast<EnumDecl>(ECD->getDeclContext());
  7430. }
  7431. if (!TD)
  7432. continue;
  7433. DeclContext *TagDC = TD->getLexicalDeclContext();
  7434. if (!TagDC->containsDecl(TD))
  7435. continue;
  7436. TagDC->removeDecl(TD);
  7437. TD->setDeclContext(NewFD);
  7438. NewFD->addDecl(TD);
  7439. // Preserve the lexical DeclContext if it is not the surrounding tag
  7440. // injection context of the FD. In this example, the semantic context of
  7441. // E will be f and the lexical context will be S, while both the
  7442. // semantic and lexical contexts of S will be f:
  7443. // void f(struct S { enum E { a } f; } s);
  7444. if (TagDC != PrototypeTagContext)
  7445. TD->setLexicalDeclContext(TagDC);
  7446. }
  7447. }
  7448. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  7449. // When we're declaring a function with a typedef, typeof, etc as in the
  7450. // following example, we'll need to synthesize (unnamed)
  7451. // parameters for use in the declaration.
  7452. //
  7453. // @code
  7454. // typedef void fn(int);
  7455. // fn f;
  7456. // @endcode
  7457. // Synthesize a parameter for each argument type.
  7458. for (const auto &AI : FT->param_types()) {
  7459. ParmVarDecl *Param =
  7460. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  7461. Param->setScopeInfo(0, Params.size());
  7462. Params.push_back(Param);
  7463. }
  7464. } else {
  7465. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  7466. "Should not need args for typedef of non-prototype fn");
  7467. }
  7468. // Finally, we know we have the right number of parameters, install them.
  7469. NewFD->setParams(Params);
  7470. if (D.getDeclSpec().isNoreturnSpecified())
  7471. NewFD->addAttr(
  7472. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  7473. Context, 0));
  7474. // Functions returning a variably modified type violate C99 6.7.5.2p2
  7475. // because all functions have linkage.
  7476. if (!NewFD->isInvalidDecl() &&
  7477. NewFD->getReturnType()->isVariablyModifiedType()) {
  7478. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  7479. NewFD->setInvalidDecl();
  7480. }
  7481. // Apply an implicit SectionAttr if #pragma code_seg is active.
  7482. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  7483. !NewFD->hasAttr<SectionAttr>()) {
  7484. NewFD->addAttr(
  7485. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  7486. CodeSegStack.CurrentValue->getString(),
  7487. CodeSegStack.CurrentPragmaLocation));
  7488. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  7489. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  7490. ASTContext::PSF_Read,
  7491. NewFD))
  7492. NewFD->dropAttr<SectionAttr>();
  7493. }
  7494. // Handle attributes.
  7495. ProcessDeclAttributes(S, NewFD, D);
  7496. if (getLangOpts().OpenCL) {
  7497. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  7498. // type declaration will generate a compilation error.
  7499. unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
  7500. if (AddressSpace == LangAS::opencl_local ||
  7501. AddressSpace == LangAS::opencl_global ||
  7502. AddressSpace == LangAS::opencl_constant) {
  7503. Diag(NewFD->getLocation(),
  7504. diag::err_opencl_return_value_with_address_space);
  7505. NewFD->setInvalidDecl();
  7506. }
  7507. }
  7508. if (!getLangOpts().CPlusPlus) {
  7509. // Perform semantic checking on the function declaration.
  7510. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7511. CheckMain(NewFD, D.getDeclSpec());
  7512. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7513. CheckMSVCRTEntryPoint(NewFD);
  7514. if (!NewFD->isInvalidDecl())
  7515. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7516. isMemberSpecialization));
  7517. else if (!Previous.empty())
  7518. // Recover gracefully from an invalid redeclaration.
  7519. D.setRedeclaration(true);
  7520. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7521. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7522. "previous declaration set still overloaded");
  7523. // Diagnose no-prototype function declarations with calling conventions that
  7524. // don't support variadic calls. Only do this in C and do it after merging
  7525. // possibly prototyped redeclarations.
  7526. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  7527. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  7528. CallingConv CC = FT->getExtInfo().getCC();
  7529. if (!supportsVariadicCall(CC)) {
  7530. // Windows system headers sometimes accidentally use stdcall without
  7531. // (void) parameters, so we relax this to a warning.
  7532. int DiagID =
  7533. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  7534. Diag(NewFD->getLocation(), DiagID)
  7535. << FunctionType::getNameForCallConv(CC);
  7536. }
  7537. }
  7538. } else {
  7539. // C++11 [replacement.functions]p3:
  7540. // The program's definitions shall not be specified as inline.
  7541. //
  7542. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  7543. //
  7544. // Suppress the diagnostic if the function is __attribute__((used)), since
  7545. // that forces an external definition to be emitted.
  7546. if (D.getDeclSpec().isInlineSpecified() &&
  7547. NewFD->isReplaceableGlobalAllocationFunction() &&
  7548. !NewFD->hasAttr<UsedAttr>())
  7549. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7550. diag::ext_operator_new_delete_declared_inline)
  7551. << NewFD->getDeclName();
  7552. // If the declarator is a template-id, translate the parser's template
  7553. // argument list into our AST format.
  7554. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  7555. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  7556. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  7557. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  7558. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  7559. TemplateId->NumArgs);
  7560. translateTemplateArguments(TemplateArgsPtr,
  7561. TemplateArgs);
  7562. HasExplicitTemplateArgs = true;
  7563. if (NewFD->isInvalidDecl()) {
  7564. HasExplicitTemplateArgs = false;
  7565. } else if (FunctionTemplate) {
  7566. // Function template with explicit template arguments.
  7567. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  7568. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  7569. HasExplicitTemplateArgs = false;
  7570. } else {
  7571. assert((isFunctionTemplateSpecialization ||
  7572. D.getDeclSpec().isFriendSpecified()) &&
  7573. "should have a 'template<>' for this decl");
  7574. // "friend void foo<>(int);" is an implicit specialization decl.
  7575. isFunctionTemplateSpecialization = true;
  7576. }
  7577. } else if (isFriend && isFunctionTemplateSpecialization) {
  7578. // This combination is only possible in a recovery case; the user
  7579. // wrote something like:
  7580. // template <> friend void foo(int);
  7581. // which we're recovering from as if the user had written:
  7582. // friend void foo<>(int);
  7583. // Go ahead and fake up a template id.
  7584. HasExplicitTemplateArgs = true;
  7585. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  7586. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  7587. }
  7588. // We do not add HD attributes to specializations here because
  7589. // they may have different constexpr-ness compared to their
  7590. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  7591. // may end up with different effective targets. Instead, a
  7592. // specialization inherits its target attributes from its template
  7593. // in the CheckFunctionTemplateSpecialization() call below.
  7594. if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
  7595. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  7596. // If it's a friend (and only if it's a friend), it's possible
  7597. // that either the specialized function type or the specialized
  7598. // template is dependent, and therefore matching will fail. In
  7599. // this case, don't check the specialization yet.
  7600. bool InstantiationDependent = false;
  7601. if (isFunctionTemplateSpecialization && isFriend &&
  7602. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  7603. TemplateSpecializationType::anyDependentTemplateArguments(
  7604. TemplateArgs,
  7605. InstantiationDependent))) {
  7606. assert(HasExplicitTemplateArgs &&
  7607. "friend function specialization without template args");
  7608. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  7609. Previous))
  7610. NewFD->setInvalidDecl();
  7611. } else if (isFunctionTemplateSpecialization) {
  7612. if (CurContext->isDependentContext() && CurContext->isRecord()
  7613. && !isFriend) {
  7614. isDependentClassScopeExplicitSpecialization = true;
  7615. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  7616. diag::ext_function_specialization_in_class :
  7617. diag::err_function_specialization_in_class)
  7618. << NewFD->getDeclName();
  7619. } else if (CheckFunctionTemplateSpecialization(NewFD,
  7620. (HasExplicitTemplateArgs ? &TemplateArgs
  7621. : nullptr),
  7622. Previous))
  7623. NewFD->setInvalidDecl();
  7624. // C++ [dcl.stc]p1:
  7625. // A storage-class-specifier shall not be specified in an explicit
  7626. // specialization (14.7.3)
  7627. FunctionTemplateSpecializationInfo *Info =
  7628. NewFD->getTemplateSpecializationInfo();
  7629. if (Info && SC != SC_None) {
  7630. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  7631. Diag(NewFD->getLocation(),
  7632. diag::err_explicit_specialization_inconsistent_storage_class)
  7633. << SC
  7634. << FixItHint::CreateRemoval(
  7635. D.getDeclSpec().getStorageClassSpecLoc());
  7636. else
  7637. Diag(NewFD->getLocation(),
  7638. diag::ext_explicit_specialization_storage_class)
  7639. << FixItHint::CreateRemoval(
  7640. D.getDeclSpec().getStorageClassSpecLoc());
  7641. }
  7642. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  7643. if (CheckMemberSpecialization(NewFD, Previous))
  7644. NewFD->setInvalidDecl();
  7645. }
  7646. // Perform semantic checking on the function declaration.
  7647. if (!isDependentClassScopeExplicitSpecialization) {
  7648. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7649. CheckMain(NewFD, D.getDeclSpec());
  7650. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7651. CheckMSVCRTEntryPoint(NewFD);
  7652. if (!NewFD->isInvalidDecl())
  7653. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7654. isMemberSpecialization));
  7655. else if (!Previous.empty())
  7656. // Recover gracefully from an invalid redeclaration.
  7657. D.setRedeclaration(true);
  7658. }
  7659. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7660. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7661. "previous declaration set still overloaded");
  7662. NamedDecl *PrincipalDecl = (FunctionTemplate
  7663. ? cast<NamedDecl>(FunctionTemplate)
  7664. : NewFD);
  7665. if (isFriend && NewFD->getPreviousDecl()) {
  7666. AccessSpecifier Access = AS_public;
  7667. if (!NewFD->isInvalidDecl())
  7668. Access = NewFD->getPreviousDecl()->getAccess();
  7669. NewFD->setAccess(Access);
  7670. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  7671. }
  7672. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  7673. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  7674. PrincipalDecl->setNonMemberOperator();
  7675. // If we have a function template, check the template parameter
  7676. // list. This will check and merge default template arguments.
  7677. if (FunctionTemplate) {
  7678. FunctionTemplateDecl *PrevTemplate =
  7679. FunctionTemplate->getPreviousDecl();
  7680. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  7681. PrevTemplate ? PrevTemplate->getTemplateParameters()
  7682. : nullptr,
  7683. D.getDeclSpec().isFriendSpecified()
  7684. ? (D.isFunctionDefinition()
  7685. ? TPC_FriendFunctionTemplateDefinition
  7686. : TPC_FriendFunctionTemplate)
  7687. : (D.getCXXScopeSpec().isSet() &&
  7688. DC && DC->isRecord() &&
  7689. DC->isDependentContext())
  7690. ? TPC_ClassTemplateMember
  7691. : TPC_FunctionTemplate);
  7692. }
  7693. if (NewFD->isInvalidDecl()) {
  7694. // Ignore all the rest of this.
  7695. } else if (!D.isRedeclaration()) {
  7696. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  7697. AddToScope };
  7698. // Fake up an access specifier if it's supposed to be a class member.
  7699. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  7700. NewFD->setAccess(AS_public);
  7701. // Qualified decls generally require a previous declaration.
  7702. if (D.getCXXScopeSpec().isSet()) {
  7703. // ...with the major exception of templated-scope or
  7704. // dependent-scope friend declarations.
  7705. // TODO: we currently also suppress this check in dependent
  7706. // contexts because (1) the parameter depth will be off when
  7707. // matching friend templates and (2) we might actually be
  7708. // selecting a friend based on a dependent factor. But there
  7709. // are situations where these conditions don't apply and we
  7710. // can actually do this check immediately.
  7711. if (isFriend &&
  7712. (TemplateParamLists.size() ||
  7713. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  7714. CurContext->isDependentContext())) {
  7715. // ignore these
  7716. } else {
  7717. // The user tried to provide an out-of-line definition for a
  7718. // function that is a member of a class or namespace, but there
  7719. // was no such member function declared (C++ [class.mfct]p2,
  7720. // C++ [namespace.memdef]p2). For example:
  7721. //
  7722. // class X {
  7723. // void f() const;
  7724. // };
  7725. //
  7726. // void X::f() { } // ill-formed
  7727. //
  7728. // Complain about this problem, and attempt to suggest close
  7729. // matches (e.g., those that differ only in cv-qualifiers and
  7730. // whether the parameter types are references).
  7731. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7732. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  7733. AddToScope = ExtraArgs.AddToScope;
  7734. return Result;
  7735. }
  7736. }
  7737. // Unqualified local friend declarations are required to resolve
  7738. // to something.
  7739. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  7740. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7741. *this, Previous, NewFD, ExtraArgs, true, S)) {
  7742. AddToScope = ExtraArgs.AddToScope;
  7743. return Result;
  7744. }
  7745. }
  7746. } else if (!D.isFunctionDefinition() &&
  7747. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  7748. !isFriend && !isFunctionTemplateSpecialization &&
  7749. !isMemberSpecialization) {
  7750. // An out-of-line member function declaration must also be a
  7751. // definition (C++ [class.mfct]p2).
  7752. // Note that this is not the case for explicit specializations of
  7753. // function templates or member functions of class templates, per
  7754. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  7755. // extension for compatibility with old SWIG code which likes to
  7756. // generate them.
  7757. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  7758. << D.getCXXScopeSpec().getRange();
  7759. }
  7760. }
  7761. ProcessPragmaWeak(S, NewFD);
  7762. checkAttributesAfterMerging(*this, *NewFD);
  7763. AddKnownFunctionAttributes(NewFD);
  7764. if (NewFD->hasAttr<OverloadableAttr>() &&
  7765. !NewFD->getType()->getAs<FunctionProtoType>()) {
  7766. Diag(NewFD->getLocation(),
  7767. diag::err_attribute_overloadable_no_prototype)
  7768. << NewFD;
  7769. // Turn this into a variadic function with no parameters.
  7770. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  7771. FunctionProtoType::ExtProtoInfo EPI(
  7772. Context.getDefaultCallingConvention(true, false));
  7773. EPI.Variadic = true;
  7774. EPI.ExtInfo = FT->getExtInfo();
  7775. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  7776. NewFD->setType(R);
  7777. }
  7778. // If there's a #pragma GCC visibility in scope, and this isn't a class
  7779. // member, set the visibility of this function.
  7780. if (!DC->isRecord() && NewFD->isExternallyVisible())
  7781. AddPushedVisibilityAttribute(NewFD);
  7782. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  7783. // marking the function.
  7784. AddCFAuditedAttribute(NewFD);
  7785. // If this is a function definition, check if we have to apply optnone due to
  7786. // a pragma.
  7787. if(D.isFunctionDefinition())
  7788. AddRangeBasedOptnone(NewFD);
  7789. // If this is the first declaration of an extern C variable, update
  7790. // the map of such variables.
  7791. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  7792. isIncompleteDeclExternC(*this, NewFD))
  7793. RegisterLocallyScopedExternCDecl(NewFD, S);
  7794. // Set this FunctionDecl's range up to the right paren.
  7795. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  7796. if (D.isRedeclaration() && !Previous.empty()) {
  7797. checkDLLAttributeRedeclaration(
  7798. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
  7799. isMemberSpecialization || isFunctionTemplateSpecialization,
  7800. D.isFunctionDefinition());
  7801. }
  7802. if (getLangOpts().CUDA) {
  7803. IdentifierInfo *II = NewFD->getIdentifier();
  7804. if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
  7805. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  7806. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  7807. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  7808. Context.setcudaConfigureCallDecl(NewFD);
  7809. }
  7810. // Variadic functions, other than a *declaration* of printf, are not allowed
  7811. // in device-side CUDA code, unless someone passed
  7812. // -fcuda-allow-variadic-functions.
  7813. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  7814. (NewFD->hasAttr<CUDADeviceAttr>() ||
  7815. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  7816. !(II && II->isStr("printf") && NewFD->isExternC() &&
  7817. !D.isFunctionDefinition())) {
  7818. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  7819. }
  7820. }
  7821. if (getLangOpts().CPlusPlus) {
  7822. if (FunctionTemplate) {
  7823. if (NewFD->isInvalidDecl())
  7824. FunctionTemplate->setInvalidDecl();
  7825. return FunctionTemplate;
  7826. }
  7827. }
  7828. if (NewFD->hasAttr<OpenCLKernelAttr>()) {
  7829. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  7830. if ((getLangOpts().OpenCLVersion >= 120)
  7831. && (SC == SC_Static)) {
  7832. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  7833. D.setInvalidType();
  7834. }
  7835. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  7836. if (!NewFD->getReturnType()->isVoidType()) {
  7837. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  7838. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  7839. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  7840. : FixItHint());
  7841. D.setInvalidType();
  7842. }
  7843. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  7844. for (auto Param : NewFD->parameters())
  7845. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  7846. }
  7847. for (const ParmVarDecl *Param : NewFD->parameters()) {
  7848. QualType PT = Param->getType();
  7849. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  7850. // types.
  7851. if (getLangOpts().OpenCLVersion >= 200) {
  7852. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  7853. QualType ElemTy = PipeTy->getElementType();
  7854. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  7855. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  7856. D.setInvalidType();
  7857. }
  7858. }
  7859. }
  7860. }
  7861. MarkUnusedFileScopedDecl(NewFD);
  7862. // Here we have an function template explicit specialization at class scope.
  7863. // The actually specialization will be postponed to template instatiation
  7864. // time via the ClassScopeFunctionSpecializationDecl node.
  7865. if (isDependentClassScopeExplicitSpecialization) {
  7866. ClassScopeFunctionSpecializationDecl *NewSpec =
  7867. ClassScopeFunctionSpecializationDecl::Create(
  7868. Context, CurContext, SourceLocation(),
  7869. cast<CXXMethodDecl>(NewFD),
  7870. HasExplicitTemplateArgs, TemplateArgs);
  7871. CurContext->addDecl(NewSpec);
  7872. AddToScope = false;
  7873. }
  7874. return NewFD;
  7875. }
  7876. /// \brief Checks if the new declaration declared in dependent context must be
  7877. /// put in the same redeclaration chain as the specified declaration.
  7878. ///
  7879. /// \param D Declaration that is checked.
  7880. /// \param PrevDecl Previous declaration found with proper lookup method for the
  7881. /// same declaration name.
  7882. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  7883. /// belongs to.
  7884. ///
  7885. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  7886. // Any declarations should be put into redeclaration chains except for
  7887. // friend declaration in a dependent context that names a function in
  7888. // namespace scope.
  7889. //
  7890. // This allows to compile code like:
  7891. //
  7892. // void func();
  7893. // template<typename T> class C1 { friend void func() { } };
  7894. // template<typename T> class C2 { friend void func() { } };
  7895. //
  7896. // This code snippet is a valid code unless both templates are instantiated.
  7897. return !(D->getLexicalDeclContext()->isDependentContext() &&
  7898. D->getDeclContext()->isFileContext() &&
  7899. D->getFriendObjectKind() != Decl::FOK_None);
  7900. }
  7901. /// \brief Perform semantic checking of a new function declaration.
  7902. ///
  7903. /// Performs semantic analysis of the new function declaration
  7904. /// NewFD. This routine performs all semantic checking that does not
  7905. /// require the actual declarator involved in the declaration, and is
  7906. /// used both for the declaration of functions as they are parsed
  7907. /// (called via ActOnDeclarator) and for the declaration of functions
  7908. /// that have been instantiated via C++ template instantiation (called
  7909. /// via InstantiateDecl).
  7910. ///
  7911. /// \param IsMemberSpecialization whether this new function declaration is
  7912. /// a member specialization (that replaces any definition provided by the
  7913. /// previous declaration).
  7914. ///
  7915. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  7916. ///
  7917. /// \returns true if the function declaration is a redeclaration.
  7918. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  7919. LookupResult &Previous,
  7920. bool IsMemberSpecialization) {
  7921. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  7922. "Variably modified return types are not handled here");
  7923. // Determine whether the type of this function should be merged with
  7924. // a previous visible declaration. This never happens for functions in C++,
  7925. // and always happens in C if the previous declaration was visible.
  7926. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  7927. !Previous.isShadowed();
  7928. bool Redeclaration = false;
  7929. NamedDecl *OldDecl = nullptr;
  7930. // Merge or overload the declaration with an existing declaration of
  7931. // the same name, if appropriate.
  7932. if (!Previous.empty()) {
  7933. // Determine whether NewFD is an overload of PrevDecl or
  7934. // a declaration that requires merging. If it's an overload,
  7935. // there's no more work to do here; we'll just add the new
  7936. // function to the scope.
  7937. if (!AllowOverloadingOfFunction(Previous, Context)) {
  7938. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  7939. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  7940. Redeclaration = true;
  7941. OldDecl = Candidate;
  7942. }
  7943. } else {
  7944. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  7945. /*NewIsUsingDecl*/ false)) {
  7946. case Ovl_Match:
  7947. Redeclaration = true;
  7948. break;
  7949. case Ovl_NonFunction:
  7950. Redeclaration = true;
  7951. break;
  7952. case Ovl_Overload:
  7953. Redeclaration = false;
  7954. break;
  7955. }
  7956. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  7957. // If a function name is overloadable in C, then every function
  7958. // with that name must be marked "overloadable".
  7959. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  7960. << Redeclaration << NewFD;
  7961. NamedDecl *OverloadedDecl = nullptr;
  7962. if (Redeclaration)
  7963. OverloadedDecl = OldDecl;
  7964. else if (!Previous.empty())
  7965. OverloadedDecl = Previous.getRepresentativeDecl();
  7966. if (OverloadedDecl)
  7967. Diag(OverloadedDecl->getLocation(),
  7968. diag::note_attribute_overloadable_prev_overload);
  7969. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  7970. }
  7971. }
  7972. }
  7973. // Check for a previous extern "C" declaration with this name.
  7974. if (!Redeclaration &&
  7975. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  7976. if (!Previous.empty()) {
  7977. // This is an extern "C" declaration with the same name as a previous
  7978. // declaration, and thus redeclares that entity...
  7979. Redeclaration = true;
  7980. OldDecl = Previous.getFoundDecl();
  7981. MergeTypeWithPrevious = false;
  7982. // ... except in the presence of __attribute__((overloadable)).
  7983. if (OldDecl->hasAttr<OverloadableAttr>()) {
  7984. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  7985. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  7986. << Redeclaration << NewFD;
  7987. Diag(Previous.getFoundDecl()->getLocation(),
  7988. diag::note_attribute_overloadable_prev_overload);
  7989. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  7990. }
  7991. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  7992. Redeclaration = false;
  7993. OldDecl = nullptr;
  7994. }
  7995. }
  7996. }
  7997. }
  7998. // C++11 [dcl.constexpr]p8:
  7999. // A constexpr specifier for a non-static member function that is not
  8000. // a constructor declares that member function to be const.
  8001. //
  8002. // This needs to be delayed until we know whether this is an out-of-line
  8003. // definition of a static member function.
  8004. //
  8005. // This rule is not present in C++1y, so we produce a backwards
  8006. // compatibility warning whenever it happens in C++11.
  8007. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  8008. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  8009. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  8010. (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
  8011. CXXMethodDecl *OldMD = nullptr;
  8012. if (OldDecl)
  8013. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  8014. if (!OldMD || !OldMD->isStatic()) {
  8015. const FunctionProtoType *FPT =
  8016. MD->getType()->castAs<FunctionProtoType>();
  8017. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  8018. EPI.TypeQuals |= Qualifiers::Const;
  8019. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  8020. FPT->getParamTypes(), EPI));
  8021. // Warn that we did this, if we're not performing template instantiation.
  8022. // In that case, we'll have warned already when the template was defined.
  8023. if (ActiveTemplateInstantiations.empty()) {
  8024. SourceLocation AddConstLoc;
  8025. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  8026. .IgnoreParens().getAs<FunctionTypeLoc>())
  8027. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  8028. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  8029. << FixItHint::CreateInsertion(AddConstLoc, " const");
  8030. }
  8031. }
  8032. }
  8033. if (Redeclaration) {
  8034. // NewFD and OldDecl represent declarations that need to be
  8035. // merged.
  8036. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  8037. NewFD->setInvalidDecl();
  8038. return Redeclaration;
  8039. }
  8040. Previous.clear();
  8041. Previous.addDecl(OldDecl);
  8042. if (FunctionTemplateDecl *OldTemplateDecl
  8043. = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  8044. NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
  8045. FunctionTemplateDecl *NewTemplateDecl
  8046. = NewFD->getDescribedFunctionTemplate();
  8047. assert(NewTemplateDecl && "Template/non-template mismatch");
  8048. if (CXXMethodDecl *Method
  8049. = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
  8050. Method->setAccess(OldTemplateDecl->getAccess());
  8051. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  8052. }
  8053. // If this is an explicit specialization of a member that is a function
  8054. // template, mark it as a member specialization.
  8055. if (IsMemberSpecialization &&
  8056. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  8057. NewTemplateDecl->setMemberSpecialization();
  8058. assert(OldTemplateDecl->isMemberSpecialization());
  8059. // Explicit specializations of a member template do not inherit deleted
  8060. // status from the parent member template that they are specializing.
  8061. if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
  8062. FunctionDecl *const OldTemplatedDecl =
  8063. OldTemplateDecl->getTemplatedDecl();
  8064. assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
  8065. OldTemplatedDecl->setDeletedAsWritten(false);
  8066. }
  8067. }
  8068. } else {
  8069. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  8070. // This needs to happen first so that 'inline' propagates.
  8071. NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
  8072. if (isa<CXXMethodDecl>(NewFD))
  8073. NewFD->setAccess(OldDecl->getAccess());
  8074. }
  8075. }
  8076. }
  8077. // Semantic checking for this function declaration (in isolation).
  8078. if (getLangOpts().CPlusPlus) {
  8079. // C++-specific checks.
  8080. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  8081. CheckConstructor(Constructor);
  8082. } else if (CXXDestructorDecl *Destructor =
  8083. dyn_cast<CXXDestructorDecl>(NewFD)) {
  8084. CXXRecordDecl *Record = Destructor->getParent();
  8085. QualType ClassType = Context.getTypeDeclType(Record);
  8086. // FIXME: Shouldn't we be able to perform this check even when the class
  8087. // type is dependent? Both gcc and edg can handle that.
  8088. if (!ClassType->isDependentType()) {
  8089. DeclarationName Name
  8090. = Context.DeclarationNames.getCXXDestructorName(
  8091. Context.getCanonicalType(ClassType));
  8092. if (NewFD->getDeclName() != Name) {
  8093. Diag(NewFD->getLocation(), diag::err_destructor_name);
  8094. NewFD->setInvalidDecl();
  8095. return Redeclaration;
  8096. }
  8097. }
  8098. } else if (CXXConversionDecl *Conversion
  8099. = dyn_cast<CXXConversionDecl>(NewFD)) {
  8100. ActOnConversionDeclarator(Conversion);
  8101. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  8102. if (auto *TD = Guide->getDescribedFunctionTemplate())
  8103. CheckDeductionGuideTemplate(TD);
  8104. // A deduction guide is not on the list of entities that can be
  8105. // explicitly specialized.
  8106. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  8107. Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
  8108. << /*explicit specialization*/ 1;
  8109. }
  8110. // Find any virtual functions that this function overrides.
  8111. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  8112. if (!Method->isFunctionTemplateSpecialization() &&
  8113. !Method->getDescribedFunctionTemplate() &&
  8114. Method->isCanonicalDecl()) {
  8115. if (AddOverriddenMethods(Method->getParent(), Method)) {
  8116. // If the function was marked as "static", we have a problem.
  8117. if (NewFD->getStorageClass() == SC_Static) {
  8118. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  8119. }
  8120. }
  8121. }
  8122. if (Method->isStatic())
  8123. checkThisInStaticMemberFunctionType(Method);
  8124. }
  8125. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  8126. if (NewFD->isOverloadedOperator() &&
  8127. CheckOverloadedOperatorDeclaration(NewFD)) {
  8128. NewFD->setInvalidDecl();
  8129. return Redeclaration;
  8130. }
  8131. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  8132. if (NewFD->getLiteralIdentifier() &&
  8133. CheckLiteralOperatorDeclaration(NewFD)) {
  8134. NewFD->setInvalidDecl();
  8135. return Redeclaration;
  8136. }
  8137. // In C++, check default arguments now that we have merged decls. Unless
  8138. // the lexical context is the class, because in this case this is done
  8139. // during delayed parsing anyway.
  8140. if (!CurContext->isRecord())
  8141. CheckCXXDefaultArguments(NewFD);
  8142. // If this function declares a builtin function, check the type of this
  8143. // declaration against the expected type for the builtin.
  8144. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  8145. ASTContext::GetBuiltinTypeError Error;
  8146. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  8147. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  8148. // If the type of the builtin differs only in its exception
  8149. // specification, that's OK.
  8150. // FIXME: If the types do differ in this way, it would be better to
  8151. // retain the 'noexcept' form of the type.
  8152. if (!T.isNull() &&
  8153. !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
  8154. NewFD->getType()))
  8155. // The type of this function differs from the type of the builtin,
  8156. // so forget about the builtin entirely.
  8157. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  8158. }
  8159. // If this function is declared as being extern "C", then check to see if
  8160. // the function returns a UDT (class, struct, or union type) that is not C
  8161. // compatible, and if it does, warn the user.
  8162. // But, issue any diagnostic on the first declaration only.
  8163. if (Previous.empty() && NewFD->isExternC()) {
  8164. QualType R = NewFD->getReturnType();
  8165. if (R->isIncompleteType() && !R->isVoidType())
  8166. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  8167. << NewFD << R;
  8168. else if (!R.isPODType(Context) && !R->isVoidType() &&
  8169. !R->isObjCObjectPointerType())
  8170. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  8171. }
  8172. // C++1z [dcl.fct]p6:
  8173. // [...] whether the function has a non-throwing exception-specification
  8174. // [is] part of the function type
  8175. //
  8176. // This results in an ABI break between C++14 and C++17 for functions whose
  8177. // declared type includes an exception-specification in a parameter or
  8178. // return type. (Exception specifications on the function itself are OK in
  8179. // most cases, and exception specifications are not permitted in most other
  8180. // contexts where they could make it into a mangling.)
  8181. if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
  8182. auto HasNoexcept = [&](QualType T) -> bool {
  8183. // Strip off declarator chunks that could be between us and a function
  8184. // type. We don't need to look far, exception specifications are very
  8185. // restricted prior to C++17.
  8186. if (auto *RT = T->getAs<ReferenceType>())
  8187. T = RT->getPointeeType();
  8188. else if (T->isAnyPointerType())
  8189. T = T->getPointeeType();
  8190. else if (auto *MPT = T->getAs<MemberPointerType>())
  8191. T = MPT->getPointeeType();
  8192. if (auto *FPT = T->getAs<FunctionProtoType>())
  8193. if (FPT->isNothrow(Context))
  8194. return true;
  8195. return false;
  8196. };
  8197. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  8198. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  8199. for (QualType T : FPT->param_types())
  8200. AnyNoexcept |= HasNoexcept(T);
  8201. if (AnyNoexcept)
  8202. Diag(NewFD->getLocation(),
  8203. diag::warn_cxx1z_compat_exception_spec_in_signature)
  8204. << NewFD;
  8205. }
  8206. if (!Redeclaration && LangOpts.CUDA)
  8207. checkCUDATargetOverload(NewFD, Previous);
  8208. }
  8209. return Redeclaration;
  8210. }
  8211. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  8212. // C++11 [basic.start.main]p3:
  8213. // A program that [...] declares main to be inline, static or
  8214. // constexpr is ill-formed.
  8215. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  8216. // appear in a declaration of main.
  8217. // static main is not an error under C99, but we should warn about it.
  8218. // We accept _Noreturn main as an extension.
  8219. if (FD->getStorageClass() == SC_Static)
  8220. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  8221. ? diag::err_static_main : diag::warn_static_main)
  8222. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  8223. if (FD->isInlineSpecified())
  8224. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  8225. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  8226. if (DS.isNoreturnSpecified()) {
  8227. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  8228. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  8229. Diag(NoreturnLoc, diag::ext_noreturn_main);
  8230. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  8231. << FixItHint::CreateRemoval(NoreturnRange);
  8232. }
  8233. if (FD->isConstexpr()) {
  8234. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  8235. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  8236. FD->setConstexpr(false);
  8237. }
  8238. if (getLangOpts().OpenCL) {
  8239. Diag(FD->getLocation(), diag::err_opencl_no_main)
  8240. << FD->hasAttr<OpenCLKernelAttr>();
  8241. FD->setInvalidDecl();
  8242. return;
  8243. }
  8244. QualType T = FD->getType();
  8245. assert(T->isFunctionType() && "function decl is not of function type");
  8246. const FunctionType* FT = T->castAs<FunctionType>();
  8247. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  8248. // In C with GNU extensions we allow main() to have non-integer return
  8249. // type, but we should warn about the extension, and we disable the
  8250. // implicit-return-zero rule.
  8251. // GCC in C mode accepts qualified 'int'.
  8252. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  8253. FD->setHasImplicitReturnZero(true);
  8254. else {
  8255. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  8256. SourceRange RTRange = FD->getReturnTypeSourceRange();
  8257. if (RTRange.isValid())
  8258. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  8259. << FixItHint::CreateReplacement(RTRange, "int");
  8260. }
  8261. } else {
  8262. // In C and C++, main magically returns 0 if you fall off the end;
  8263. // set the flag which tells us that.
  8264. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  8265. // All the standards say that main() should return 'int'.
  8266. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  8267. FD->setHasImplicitReturnZero(true);
  8268. else {
  8269. // Otherwise, this is just a flat-out error.
  8270. SourceRange RTRange = FD->getReturnTypeSourceRange();
  8271. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  8272. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  8273. : FixItHint());
  8274. FD->setInvalidDecl(true);
  8275. }
  8276. }
  8277. // Treat protoless main() as nullary.
  8278. if (isa<FunctionNoProtoType>(FT)) return;
  8279. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  8280. unsigned nparams = FTP->getNumParams();
  8281. assert(FD->getNumParams() == nparams);
  8282. bool HasExtraParameters = (nparams > 3);
  8283. if (FTP->isVariadic()) {
  8284. Diag(FD->getLocation(), diag::ext_variadic_main);
  8285. // FIXME: if we had information about the location of the ellipsis, we
  8286. // could add a FixIt hint to remove it as a parameter.
  8287. }
  8288. // Darwin passes an undocumented fourth argument of type char**. If
  8289. // other platforms start sprouting these, the logic below will start
  8290. // getting shifty.
  8291. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  8292. HasExtraParameters = false;
  8293. if (HasExtraParameters) {
  8294. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  8295. FD->setInvalidDecl(true);
  8296. nparams = 3;
  8297. }
  8298. // FIXME: a lot of the following diagnostics would be improved
  8299. // if we had some location information about types.
  8300. QualType CharPP =
  8301. Context.getPointerType(Context.getPointerType(Context.CharTy));
  8302. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  8303. for (unsigned i = 0; i < nparams; ++i) {
  8304. QualType AT = FTP->getParamType(i);
  8305. bool mismatch = true;
  8306. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  8307. mismatch = false;
  8308. else if (Expected[i] == CharPP) {
  8309. // As an extension, the following forms are okay:
  8310. // char const **
  8311. // char const * const *
  8312. // char * const *
  8313. QualifierCollector qs;
  8314. const PointerType* PT;
  8315. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  8316. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  8317. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  8318. Context.CharTy)) {
  8319. qs.removeConst();
  8320. mismatch = !qs.empty();
  8321. }
  8322. }
  8323. if (mismatch) {
  8324. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  8325. // TODO: suggest replacing given type with expected type
  8326. FD->setInvalidDecl(true);
  8327. }
  8328. }
  8329. if (nparams == 1 && !FD->isInvalidDecl()) {
  8330. Diag(FD->getLocation(), diag::warn_main_one_arg);
  8331. }
  8332. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  8333. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  8334. FD->setInvalidDecl();
  8335. }
  8336. }
  8337. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  8338. QualType T = FD->getType();
  8339. assert(T->isFunctionType() && "function decl is not of function type");
  8340. const FunctionType *FT = T->castAs<FunctionType>();
  8341. // Set an implicit return of 'zero' if the function can return some integral,
  8342. // enumeration, pointer or nullptr type.
  8343. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  8344. FT->getReturnType()->isAnyPointerType() ||
  8345. FT->getReturnType()->isNullPtrType())
  8346. // DllMain is exempt because a return value of zero means it failed.
  8347. if (FD->getName() != "DllMain")
  8348. FD->setHasImplicitReturnZero(true);
  8349. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  8350. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  8351. FD->setInvalidDecl();
  8352. }
  8353. }
  8354. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  8355. // FIXME: Need strict checking. In C89, we need to check for
  8356. // any assignment, increment, decrement, function-calls, or
  8357. // commas outside of a sizeof. In C99, it's the same list,
  8358. // except that the aforementioned are allowed in unevaluated
  8359. // expressions. Everything else falls under the
  8360. // "may accept other forms of constant expressions" exception.
  8361. // (We never end up here for C++, so the constant expression
  8362. // rules there don't matter.)
  8363. const Expr *Culprit;
  8364. if (Init->isConstantInitializer(Context, false, &Culprit))
  8365. return false;
  8366. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  8367. << Culprit->getSourceRange();
  8368. return true;
  8369. }
  8370. namespace {
  8371. // Visits an initialization expression to see if OrigDecl is evaluated in
  8372. // its own initialization and throws a warning if it does.
  8373. class SelfReferenceChecker
  8374. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  8375. Sema &S;
  8376. Decl *OrigDecl;
  8377. bool isRecordType;
  8378. bool isPODType;
  8379. bool isReferenceType;
  8380. bool isInitList;
  8381. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  8382. public:
  8383. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  8384. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  8385. S(S), OrigDecl(OrigDecl) {
  8386. isPODType = false;
  8387. isRecordType = false;
  8388. isReferenceType = false;
  8389. isInitList = false;
  8390. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  8391. isPODType = VD->getType().isPODType(S.Context);
  8392. isRecordType = VD->getType()->isRecordType();
  8393. isReferenceType = VD->getType()->isReferenceType();
  8394. }
  8395. }
  8396. // For most expressions, just call the visitor. For initializer lists,
  8397. // track the index of the field being initialized since fields are
  8398. // initialized in order allowing use of previously initialized fields.
  8399. void CheckExpr(Expr *E) {
  8400. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  8401. if (!InitList) {
  8402. Visit(E);
  8403. return;
  8404. }
  8405. // Track and increment the index here.
  8406. isInitList = true;
  8407. InitFieldIndex.push_back(0);
  8408. for (auto Child : InitList->children()) {
  8409. CheckExpr(cast<Expr>(Child));
  8410. ++InitFieldIndex.back();
  8411. }
  8412. InitFieldIndex.pop_back();
  8413. }
  8414. // Returns true if MemberExpr is checked and no futher checking is needed.
  8415. // Returns false if additional checking is required.
  8416. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  8417. llvm::SmallVector<FieldDecl*, 4> Fields;
  8418. Expr *Base = E;
  8419. bool ReferenceField = false;
  8420. // Get the field memebers used.
  8421. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  8422. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  8423. if (!FD)
  8424. return false;
  8425. Fields.push_back(FD);
  8426. if (FD->getType()->isReferenceType())
  8427. ReferenceField = true;
  8428. Base = ME->getBase()->IgnoreParenImpCasts();
  8429. }
  8430. // Keep checking only if the base Decl is the same.
  8431. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  8432. if (!DRE || DRE->getDecl() != OrigDecl)
  8433. return false;
  8434. // A reference field can be bound to an unininitialized field.
  8435. if (CheckReference && !ReferenceField)
  8436. return true;
  8437. // Convert FieldDecls to their index number.
  8438. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  8439. for (const FieldDecl *I : llvm::reverse(Fields))
  8440. UsedFieldIndex.push_back(I->getFieldIndex());
  8441. // See if a warning is needed by checking the first difference in index
  8442. // numbers. If field being used has index less than the field being
  8443. // initialized, then the use is safe.
  8444. for (auto UsedIter = UsedFieldIndex.begin(),
  8445. UsedEnd = UsedFieldIndex.end(),
  8446. OrigIter = InitFieldIndex.begin(),
  8447. OrigEnd = InitFieldIndex.end();
  8448. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  8449. if (*UsedIter < *OrigIter)
  8450. return true;
  8451. if (*UsedIter > *OrigIter)
  8452. break;
  8453. }
  8454. // TODO: Add a different warning which will print the field names.
  8455. HandleDeclRefExpr(DRE);
  8456. return true;
  8457. }
  8458. // For most expressions, the cast is directly above the DeclRefExpr.
  8459. // For conditional operators, the cast can be outside the conditional
  8460. // operator if both expressions are DeclRefExpr's.
  8461. void HandleValue(Expr *E) {
  8462. E = E->IgnoreParens();
  8463. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  8464. HandleDeclRefExpr(DRE);
  8465. return;
  8466. }
  8467. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  8468. Visit(CO->getCond());
  8469. HandleValue(CO->getTrueExpr());
  8470. HandleValue(CO->getFalseExpr());
  8471. return;
  8472. }
  8473. if (BinaryConditionalOperator *BCO =
  8474. dyn_cast<BinaryConditionalOperator>(E)) {
  8475. Visit(BCO->getCond());
  8476. HandleValue(BCO->getFalseExpr());
  8477. return;
  8478. }
  8479. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  8480. HandleValue(OVE->getSourceExpr());
  8481. return;
  8482. }
  8483. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  8484. if (BO->getOpcode() == BO_Comma) {
  8485. Visit(BO->getLHS());
  8486. HandleValue(BO->getRHS());
  8487. return;
  8488. }
  8489. }
  8490. if (isa<MemberExpr>(E)) {
  8491. if (isInitList) {
  8492. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  8493. false /*CheckReference*/))
  8494. return;
  8495. }
  8496. Expr *Base = E->IgnoreParenImpCasts();
  8497. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  8498. // Check for static member variables and don't warn on them.
  8499. if (!isa<FieldDecl>(ME->getMemberDecl()))
  8500. return;
  8501. Base = ME->getBase()->IgnoreParenImpCasts();
  8502. }
  8503. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  8504. HandleDeclRefExpr(DRE);
  8505. return;
  8506. }
  8507. Visit(E);
  8508. }
  8509. // Reference types not handled in HandleValue are handled here since all
  8510. // uses of references are bad, not just r-value uses.
  8511. void VisitDeclRefExpr(DeclRefExpr *E) {
  8512. if (isReferenceType)
  8513. HandleDeclRefExpr(E);
  8514. }
  8515. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  8516. if (E->getCastKind() == CK_LValueToRValue) {
  8517. HandleValue(E->getSubExpr());
  8518. return;
  8519. }
  8520. Inherited::VisitImplicitCastExpr(E);
  8521. }
  8522. void VisitMemberExpr(MemberExpr *E) {
  8523. if (isInitList) {
  8524. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  8525. return;
  8526. }
  8527. // Don't warn on arrays since they can be treated as pointers.
  8528. if (E->getType()->canDecayToPointerType()) return;
  8529. // Warn when a non-static method call is followed by non-static member
  8530. // field accesses, which is followed by a DeclRefExpr.
  8531. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  8532. bool Warn = (MD && !MD->isStatic());
  8533. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  8534. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  8535. if (!isa<FieldDecl>(ME->getMemberDecl()))
  8536. Warn = false;
  8537. Base = ME->getBase()->IgnoreParenImpCasts();
  8538. }
  8539. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  8540. if (Warn)
  8541. HandleDeclRefExpr(DRE);
  8542. return;
  8543. }
  8544. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  8545. // Visit that expression.
  8546. Visit(Base);
  8547. }
  8548. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  8549. Expr *Callee = E->getCallee();
  8550. if (isa<UnresolvedLookupExpr>(Callee))
  8551. return Inherited::VisitCXXOperatorCallExpr(E);
  8552. Visit(Callee);
  8553. for (auto Arg: E->arguments())
  8554. HandleValue(Arg->IgnoreParenImpCasts());
  8555. }
  8556. void VisitUnaryOperator(UnaryOperator *E) {
  8557. // For POD record types, addresses of its own members are well-defined.
  8558. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  8559. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  8560. if (!isPODType)
  8561. HandleValue(E->getSubExpr());
  8562. return;
  8563. }
  8564. if (E->isIncrementDecrementOp()) {
  8565. HandleValue(E->getSubExpr());
  8566. return;
  8567. }
  8568. Inherited::VisitUnaryOperator(E);
  8569. }
  8570. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  8571. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  8572. if (E->getConstructor()->isCopyConstructor()) {
  8573. Expr *ArgExpr = E->getArg(0);
  8574. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  8575. if (ILE->getNumInits() == 1)
  8576. ArgExpr = ILE->getInit(0);
  8577. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  8578. if (ICE->getCastKind() == CK_NoOp)
  8579. ArgExpr = ICE->getSubExpr();
  8580. HandleValue(ArgExpr);
  8581. return;
  8582. }
  8583. Inherited::VisitCXXConstructExpr(E);
  8584. }
  8585. void VisitCallExpr(CallExpr *E) {
  8586. // Treat std::move as a use.
  8587. if (E->getNumArgs() == 1) {
  8588. if (FunctionDecl *FD = E->getDirectCallee()) {
  8589. if (FD->isInStdNamespace() && FD->getIdentifier() &&
  8590. FD->getIdentifier()->isStr("move")) {
  8591. HandleValue(E->getArg(0));
  8592. return;
  8593. }
  8594. }
  8595. }
  8596. Inherited::VisitCallExpr(E);
  8597. }
  8598. void VisitBinaryOperator(BinaryOperator *E) {
  8599. if (E->isCompoundAssignmentOp()) {
  8600. HandleValue(E->getLHS());
  8601. Visit(E->getRHS());
  8602. return;
  8603. }
  8604. Inherited::VisitBinaryOperator(E);
  8605. }
  8606. // A custom visitor for BinaryConditionalOperator is needed because the
  8607. // regular visitor would check the condition and true expression separately
  8608. // but both point to the same place giving duplicate diagnostics.
  8609. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  8610. Visit(E->getCond());
  8611. Visit(E->getFalseExpr());
  8612. }
  8613. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  8614. Decl* ReferenceDecl = DRE->getDecl();
  8615. if (OrigDecl != ReferenceDecl) return;
  8616. unsigned diag;
  8617. if (isReferenceType) {
  8618. diag = diag::warn_uninit_self_reference_in_reference_init;
  8619. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  8620. diag = diag::warn_static_self_reference_in_init;
  8621. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  8622. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  8623. DRE->getDecl()->getType()->isRecordType()) {
  8624. diag = diag::warn_uninit_self_reference_in_init;
  8625. } else {
  8626. // Local variables will be handled by the CFG analysis.
  8627. return;
  8628. }
  8629. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  8630. S.PDiag(diag)
  8631. << DRE->getNameInfo().getName()
  8632. << OrigDecl->getLocation()
  8633. << DRE->getSourceRange());
  8634. }
  8635. };
  8636. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  8637. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  8638. bool DirectInit) {
  8639. // Parameters arguments are occassionially constructed with itself,
  8640. // for instance, in recursive functions. Skip them.
  8641. if (isa<ParmVarDecl>(OrigDecl))
  8642. return;
  8643. E = E->IgnoreParens();
  8644. // Skip checking T a = a where T is not a record or reference type.
  8645. // Doing so is a way to silence uninitialized warnings.
  8646. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  8647. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  8648. if (ICE->getCastKind() == CK_LValueToRValue)
  8649. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  8650. if (DRE->getDecl() == OrigDecl)
  8651. return;
  8652. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  8653. }
  8654. } // end anonymous namespace
  8655. namespace {
  8656. // Simple wrapper to add the name of a variable or (if no variable is
  8657. // available) a DeclarationName into a diagnostic.
  8658. struct VarDeclOrName {
  8659. VarDecl *VDecl;
  8660. DeclarationName Name;
  8661. friend const Sema::SemaDiagnosticBuilder &
  8662. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  8663. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  8664. }
  8665. };
  8666. } // end anonymous namespace
  8667. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  8668. DeclarationName Name, QualType Type,
  8669. TypeSourceInfo *TSI,
  8670. SourceRange Range, bool DirectInit,
  8671. Expr *Init) {
  8672. bool IsInitCapture = !VDecl;
  8673. assert((!VDecl || !VDecl->isInitCapture()) &&
  8674. "init captures are expected to be deduced prior to initialization");
  8675. VarDeclOrName VN{VDecl, Name};
  8676. DeducedType *Deduced = Type->getContainedDeducedType();
  8677. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  8678. // C++11 [dcl.spec.auto]p3
  8679. if (!Init) {
  8680. assert(VDecl && "no init for init capture deduction?");
  8681. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  8682. << VDecl->getDeclName() << Type;
  8683. return QualType();
  8684. }
  8685. ArrayRef<Expr*> DeduceInits = Init;
  8686. if (DirectInit) {
  8687. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  8688. DeduceInits = PL->exprs();
  8689. }
  8690. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  8691. assert(VDecl && "non-auto type for init capture deduction?");
  8692. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  8693. InitializationKind Kind = InitializationKind::CreateForInit(
  8694. VDecl->getLocation(), DirectInit, Init);
  8695. // FIXME: Initialization should not be taking a mutable list of inits.
  8696. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  8697. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  8698. InitsCopy);
  8699. }
  8700. if (DirectInit) {
  8701. if (auto *IL = dyn_cast<InitListExpr>(Init))
  8702. DeduceInits = IL->inits();
  8703. }
  8704. // Deduction only works if we have exactly one source expression.
  8705. if (DeduceInits.empty()) {
  8706. // It isn't possible to write this directly, but it is possible to
  8707. // end up in this situation with "auto x(some_pack...);"
  8708. Diag(Init->getLocStart(), IsInitCapture
  8709. ? diag::err_init_capture_no_expression
  8710. : diag::err_auto_var_init_no_expression)
  8711. << VN << Type << Range;
  8712. return QualType();
  8713. }
  8714. if (DeduceInits.size() > 1) {
  8715. Diag(DeduceInits[1]->getLocStart(),
  8716. IsInitCapture ? diag::err_init_capture_multiple_expressions
  8717. : diag::err_auto_var_init_multiple_expressions)
  8718. << VN << Type << Range;
  8719. return QualType();
  8720. }
  8721. Expr *DeduceInit = DeduceInits[0];
  8722. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  8723. Diag(Init->getLocStart(), IsInitCapture
  8724. ? diag::err_init_capture_paren_braces
  8725. : diag::err_auto_var_init_paren_braces)
  8726. << isa<InitListExpr>(Init) << VN << Type << Range;
  8727. return QualType();
  8728. }
  8729. // Expressions default to 'id' when we're in a debugger.
  8730. bool DefaultedAnyToId = false;
  8731. if (getLangOpts().DebuggerCastResultToId &&
  8732. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  8733. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  8734. if (Result.isInvalid()) {
  8735. return QualType();
  8736. }
  8737. Init = Result.get();
  8738. DefaultedAnyToId = true;
  8739. }
  8740. // C++ [dcl.decomp]p1:
  8741. // If the assignment-expression [...] has array type A and no ref-qualifier
  8742. // is present, e has type cv A
  8743. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  8744. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  8745. DeduceInit->getType()->isConstantArrayType())
  8746. return Context.getQualifiedType(DeduceInit->getType(),
  8747. Type.getQualifiers());
  8748. QualType DeducedType;
  8749. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  8750. if (!IsInitCapture)
  8751. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  8752. else if (isa<InitListExpr>(Init))
  8753. Diag(Range.getBegin(),
  8754. diag::err_init_capture_deduction_failure_from_init_list)
  8755. << VN
  8756. << (DeduceInit->getType().isNull() ? TSI->getType()
  8757. : DeduceInit->getType())
  8758. << DeduceInit->getSourceRange();
  8759. else
  8760. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  8761. << VN << TSI->getType()
  8762. << (DeduceInit->getType().isNull() ? TSI->getType()
  8763. : DeduceInit->getType())
  8764. << DeduceInit->getSourceRange();
  8765. }
  8766. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  8767. // 'id' instead of a specific object type prevents most of our usual
  8768. // checks.
  8769. // We only want to warn outside of template instantiations, though:
  8770. // inside a template, the 'id' could have come from a parameter.
  8771. if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
  8772. !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  8773. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  8774. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  8775. }
  8776. return DeducedType;
  8777. }
  8778. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  8779. Expr *Init) {
  8780. QualType DeducedType = deduceVarTypeFromInitializer(
  8781. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  8782. VDecl->getSourceRange(), DirectInit, Init);
  8783. if (DeducedType.isNull()) {
  8784. VDecl->setInvalidDecl();
  8785. return true;
  8786. }
  8787. VDecl->setType(DeducedType);
  8788. assert(VDecl->isLinkageValid());
  8789. // In ARC, infer lifetime.
  8790. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  8791. VDecl->setInvalidDecl();
  8792. // If this is a redeclaration, check that the type we just deduced matches
  8793. // the previously declared type.
  8794. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  8795. // We never need to merge the type, because we cannot form an incomplete
  8796. // array of auto, nor deduce such a type.
  8797. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  8798. }
  8799. // Check the deduced type is valid for a variable declaration.
  8800. CheckVariableDeclarationType(VDecl);
  8801. return VDecl->isInvalidDecl();
  8802. }
  8803. /// AddInitializerToDecl - Adds the initializer Init to the
  8804. /// declaration dcl. If DirectInit is true, this is C++ direct
  8805. /// initialization rather than copy initialization.
  8806. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  8807. // If there is no declaration, there was an error parsing it. Just ignore
  8808. // the initializer.
  8809. if (!RealDecl || RealDecl->isInvalidDecl()) {
  8810. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  8811. return;
  8812. }
  8813. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  8814. // Pure-specifiers are handled in ActOnPureSpecifier.
  8815. Diag(Method->getLocation(), diag::err_member_function_initialization)
  8816. << Method->getDeclName() << Init->getSourceRange();
  8817. Method->setInvalidDecl();
  8818. return;
  8819. }
  8820. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  8821. if (!VDecl) {
  8822. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  8823. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  8824. RealDecl->setInvalidDecl();
  8825. return;
  8826. }
  8827. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  8828. if (VDecl->getType()->isUndeducedType()) {
  8829. // Attempt typo correction early so that the type of the init expression can
  8830. // be deduced based on the chosen correction if the original init contains a
  8831. // TypoExpr.
  8832. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  8833. if (!Res.isUsable()) {
  8834. RealDecl->setInvalidDecl();
  8835. return;
  8836. }
  8837. Init = Res.get();
  8838. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  8839. return;
  8840. }
  8841. // dllimport cannot be used on variable definitions.
  8842. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  8843. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  8844. VDecl->setInvalidDecl();
  8845. return;
  8846. }
  8847. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  8848. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  8849. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  8850. VDecl->setInvalidDecl();
  8851. return;
  8852. }
  8853. if (!VDecl->getType()->isDependentType()) {
  8854. // A definition must end up with a complete type, which means it must be
  8855. // complete with the restriction that an array type might be completed by
  8856. // the initializer; note that later code assumes this restriction.
  8857. QualType BaseDeclType = VDecl->getType();
  8858. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  8859. BaseDeclType = Array->getElementType();
  8860. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  8861. diag::err_typecheck_decl_incomplete_type)) {
  8862. RealDecl->setInvalidDecl();
  8863. return;
  8864. }
  8865. // The variable can not have an abstract class type.
  8866. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  8867. diag::err_abstract_type_in_decl,
  8868. AbstractVariableType))
  8869. VDecl->setInvalidDecl();
  8870. }
  8871. // If adding the initializer will turn this declaration into a definition,
  8872. // and we already have a definition for this variable, diagnose or otherwise
  8873. // handle the situation.
  8874. VarDecl *Def;
  8875. if ((Def = VDecl->getDefinition()) && Def != VDecl &&
  8876. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  8877. !VDecl->isThisDeclarationADemotedDefinition() &&
  8878. checkVarDeclRedefinition(Def, VDecl))
  8879. return;
  8880. if (getLangOpts().CPlusPlus) {
  8881. // C++ [class.static.data]p4
  8882. // If a static data member is of const integral or const
  8883. // enumeration type, its declaration in the class definition can
  8884. // specify a constant-initializer which shall be an integral
  8885. // constant expression (5.19). In that case, the member can appear
  8886. // in integral constant expressions. The member shall still be
  8887. // defined in a namespace scope if it is used in the program and the
  8888. // namespace scope definition shall not contain an initializer.
  8889. //
  8890. // We already performed a redefinition check above, but for static
  8891. // data members we also need to check whether there was an in-class
  8892. // declaration with an initializer.
  8893. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  8894. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  8895. << VDecl->getDeclName();
  8896. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  8897. diag::note_previous_initializer)
  8898. << 0;
  8899. return;
  8900. }
  8901. if (VDecl->hasLocalStorage())
  8902. getCurFunction()->setHasBranchProtectedScope();
  8903. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  8904. VDecl->setInvalidDecl();
  8905. return;
  8906. }
  8907. }
  8908. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  8909. // a kernel function cannot be initialized."
  8910. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  8911. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  8912. VDecl->setInvalidDecl();
  8913. return;
  8914. }
  8915. // Get the decls type and save a reference for later, since
  8916. // CheckInitializerTypes may change it.
  8917. QualType DclT = VDecl->getType(), SavT = DclT;
  8918. // Expressions default to 'id' when we're in a debugger
  8919. // and we are assigning it to a variable of Objective-C pointer type.
  8920. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  8921. Init->getType() == Context.UnknownAnyTy) {
  8922. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  8923. if (Result.isInvalid()) {
  8924. VDecl->setInvalidDecl();
  8925. return;
  8926. }
  8927. Init = Result.get();
  8928. }
  8929. // Perform the initialization.
  8930. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  8931. if (!VDecl->isInvalidDecl()) {
  8932. // Handle errors like: int a({0})
  8933. if (CXXDirectInit && CXXDirectInit->getNumExprs() == 1 &&
  8934. !canInitializeWithParenthesizedList(VDecl->getType()))
  8935. if (auto IList = dyn_cast<InitListExpr>(CXXDirectInit->getExpr(0))) {
  8936. Diag(VDecl->getLocation(), diag::err_list_init_in_parens)
  8937. << VDecl->getType() << CXXDirectInit->getSourceRange()
  8938. << FixItHint::CreateRemoval(CXXDirectInit->getLocStart())
  8939. << FixItHint::CreateRemoval(CXXDirectInit->getLocEnd());
  8940. Init = IList;
  8941. CXXDirectInit = nullptr;
  8942. }
  8943. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  8944. InitializationKind Kind = InitializationKind::CreateForInit(
  8945. VDecl->getLocation(), DirectInit, Init);
  8946. MultiExprArg Args = Init;
  8947. if (CXXDirectInit)
  8948. Args = MultiExprArg(CXXDirectInit->getExprs(),
  8949. CXXDirectInit->getNumExprs());
  8950. // Try to correct any TypoExprs in the initialization arguments.
  8951. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  8952. ExprResult Res = CorrectDelayedTyposInExpr(
  8953. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  8954. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  8955. return Init.Failed() ? ExprError() : E;
  8956. });
  8957. if (Res.isInvalid()) {
  8958. VDecl->setInvalidDecl();
  8959. } else if (Res.get() != Args[Idx]) {
  8960. Args[Idx] = Res.get();
  8961. }
  8962. }
  8963. if (VDecl->isInvalidDecl())
  8964. return;
  8965. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  8966. /*TopLevelOfInitList=*/false,
  8967. /*TreatUnavailableAsInvalid=*/false);
  8968. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  8969. if (Result.isInvalid()) {
  8970. VDecl->setInvalidDecl();
  8971. return;
  8972. }
  8973. Init = Result.getAs<Expr>();
  8974. }
  8975. // Check for self-references within variable initializers.
  8976. // Variables declared within a function/method body (except for references)
  8977. // are handled by a dataflow analysis.
  8978. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  8979. VDecl->getType()->isReferenceType()) {
  8980. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  8981. }
  8982. // If the type changed, it means we had an incomplete type that was
  8983. // completed by the initializer. For example:
  8984. // int ary[] = { 1, 3, 5 };
  8985. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  8986. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  8987. VDecl->setType(DclT);
  8988. if (!VDecl->isInvalidDecl()) {
  8989. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  8990. if (VDecl->hasAttr<BlocksAttr>())
  8991. checkRetainCycles(VDecl, Init);
  8992. // It is safe to assign a weak reference into a strong variable.
  8993. // Although this code can still have problems:
  8994. // id x = self.weakProp;
  8995. // id y = self.weakProp;
  8996. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  8997. // paths through the function. This should be revisited if
  8998. // -Wrepeated-use-of-weak is made flow-sensitive.
  8999. if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
  9000. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  9001. Init->getLocStart()))
  9002. getCurFunction()->markSafeWeakUse(Init);
  9003. }
  9004. // The initialization is usually a full-expression.
  9005. //
  9006. // FIXME: If this is a braced initialization of an aggregate, it is not
  9007. // an expression, and each individual field initializer is a separate
  9008. // full-expression. For instance, in:
  9009. //
  9010. // struct Temp { ~Temp(); };
  9011. // struct S { S(Temp); };
  9012. // struct T { S a, b; } t = { Temp(), Temp() }
  9013. //
  9014. // we should destroy the first Temp before constructing the second.
  9015. ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
  9016. false,
  9017. VDecl->isConstexpr());
  9018. if (Result.isInvalid()) {
  9019. VDecl->setInvalidDecl();
  9020. return;
  9021. }
  9022. Init = Result.get();
  9023. // Attach the initializer to the decl.
  9024. VDecl->setInit(Init);
  9025. if (VDecl->isLocalVarDecl()) {
  9026. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  9027. // static storage duration shall be constant expressions or string literals.
  9028. // C++ does not have this restriction.
  9029. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
  9030. const Expr *Culprit;
  9031. if (VDecl->getStorageClass() == SC_Static)
  9032. CheckForConstantInitializer(Init, DclT);
  9033. // C89 is stricter than C99 for non-static aggregate types.
  9034. // C89 6.5.7p3: All the expressions [...] in an initializer list
  9035. // for an object that has aggregate or union type shall be
  9036. // constant expressions.
  9037. else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  9038. isa<InitListExpr>(Init) &&
  9039. !Init->isConstantInitializer(Context, false, &Culprit))
  9040. Diag(Culprit->getExprLoc(),
  9041. diag::ext_aggregate_init_not_constant)
  9042. << Culprit->getSourceRange();
  9043. }
  9044. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  9045. VDecl->getLexicalDeclContext()->isRecord()) {
  9046. // This is an in-class initialization for a static data member, e.g.,
  9047. //
  9048. // struct S {
  9049. // static const int value = 17;
  9050. // };
  9051. // C++ [class.mem]p4:
  9052. // A member-declarator can contain a constant-initializer only
  9053. // if it declares a static member (9.4) of const integral or
  9054. // const enumeration type, see 9.4.2.
  9055. //
  9056. // C++11 [class.static.data]p3:
  9057. // If a non-volatile non-inline const static data member is of integral
  9058. // or enumeration type, its declaration in the class definition can
  9059. // specify a brace-or-equal-initializer in which every initalizer-clause
  9060. // that is an assignment-expression is a constant expression. A static
  9061. // data member of literal type can be declared in the class definition
  9062. // with the constexpr specifier; if so, its declaration shall specify a
  9063. // brace-or-equal-initializer in which every initializer-clause that is
  9064. // an assignment-expression is a constant expression.
  9065. // Do nothing on dependent types.
  9066. if (DclT->isDependentType()) {
  9067. // Allow any 'static constexpr' members, whether or not they are of literal
  9068. // type. We separately check that every constexpr variable is of literal
  9069. // type.
  9070. } else if (VDecl->isConstexpr()) {
  9071. // Require constness.
  9072. } else if (!DclT.isConstQualified()) {
  9073. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  9074. << Init->getSourceRange();
  9075. VDecl->setInvalidDecl();
  9076. // We allow integer constant expressions in all cases.
  9077. } else if (DclT->isIntegralOrEnumerationType()) {
  9078. // Check whether the expression is a constant expression.
  9079. SourceLocation Loc;
  9080. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  9081. // In C++11, a non-constexpr const static data member with an
  9082. // in-class initializer cannot be volatile.
  9083. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  9084. else if (Init->isValueDependent())
  9085. ; // Nothing to check.
  9086. else if (Init->isIntegerConstantExpr(Context, &Loc))
  9087. ; // Ok, it's an ICE!
  9088. else if (Init->isEvaluatable(Context)) {
  9089. // If we can constant fold the initializer through heroics, accept it,
  9090. // but report this as a use of an extension for -pedantic.
  9091. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  9092. << Init->getSourceRange();
  9093. } else {
  9094. // Otherwise, this is some crazy unknown case. Report the issue at the
  9095. // location provided by the isIntegerConstantExpr failed check.
  9096. Diag(Loc, diag::err_in_class_initializer_non_constant)
  9097. << Init->getSourceRange();
  9098. VDecl->setInvalidDecl();
  9099. }
  9100. // We allow foldable floating-point constants as an extension.
  9101. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  9102. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  9103. // it anyway and provide a fixit to add the 'constexpr'.
  9104. if (getLangOpts().CPlusPlus11) {
  9105. Diag(VDecl->getLocation(),
  9106. diag::ext_in_class_initializer_float_type_cxx11)
  9107. << DclT << Init->getSourceRange();
  9108. Diag(VDecl->getLocStart(),
  9109. diag::note_in_class_initializer_float_type_cxx11)
  9110. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  9111. } else {
  9112. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  9113. << DclT << Init->getSourceRange();
  9114. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  9115. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  9116. << Init->getSourceRange();
  9117. VDecl->setInvalidDecl();
  9118. }
  9119. }
  9120. // Suggest adding 'constexpr' in C++11 for literal types.
  9121. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  9122. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  9123. << DclT << Init->getSourceRange()
  9124. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  9125. VDecl->setConstexpr(true);
  9126. } else {
  9127. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  9128. << DclT << Init->getSourceRange();
  9129. VDecl->setInvalidDecl();
  9130. }
  9131. } else if (VDecl->isFileVarDecl()) {
  9132. // In C, extern is typically used to avoid tentative definitions when
  9133. // declaring variables in headers, but adding an intializer makes it a
  9134. // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
  9135. // In C++, extern is often used to give implictly static const variables
  9136. // external linkage, so don't warn in that case. If selectany is present,
  9137. // this might be header code intended for C and C++ inclusion, so apply the
  9138. // C++ rules.
  9139. if (VDecl->getStorageClass() == SC_Extern &&
  9140. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  9141. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  9142. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  9143. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  9144. Diag(VDecl->getLocation(), diag::warn_extern_init);
  9145. // C99 6.7.8p4. All file scoped initializers need to be constant.
  9146. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  9147. CheckForConstantInitializer(Init, DclT);
  9148. }
  9149. // We will represent direct-initialization similarly to copy-initialization:
  9150. // int x(1); -as-> int x = 1;
  9151. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  9152. //
  9153. // Clients that want to distinguish between the two forms, can check for
  9154. // direct initializer using VarDecl::getInitStyle().
  9155. // A major benefit is that clients that don't particularly care about which
  9156. // exactly form was it (like the CodeGen) can handle both cases without
  9157. // special case code.
  9158. // C++ 8.5p11:
  9159. // The form of initialization (using parentheses or '=') is generally
  9160. // insignificant, but does matter when the entity being initialized has a
  9161. // class type.
  9162. if (CXXDirectInit) {
  9163. assert(DirectInit && "Call-style initializer must be direct init.");
  9164. VDecl->setInitStyle(VarDecl::CallInit);
  9165. } else if (DirectInit) {
  9166. // This must be list-initialization. No other way is direct-initialization.
  9167. VDecl->setInitStyle(VarDecl::ListInit);
  9168. }
  9169. CheckCompleteVariableDeclaration(VDecl);
  9170. }
  9171. /// ActOnInitializerError - Given that there was an error parsing an
  9172. /// initializer for the given declaration, try to return to some form
  9173. /// of sanity.
  9174. void Sema::ActOnInitializerError(Decl *D) {
  9175. // Our main concern here is re-establishing invariants like "a
  9176. // variable's type is either dependent or complete".
  9177. if (!D || D->isInvalidDecl()) return;
  9178. VarDecl *VD = dyn_cast<VarDecl>(D);
  9179. if (!VD) return;
  9180. // Bindings are not usable if we can't make sense of the initializer.
  9181. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  9182. for (auto *BD : DD->bindings())
  9183. BD->setInvalidDecl();
  9184. // Auto types are meaningless if we can't make sense of the initializer.
  9185. if (ParsingInitForAutoVars.count(D)) {
  9186. D->setInvalidDecl();
  9187. return;
  9188. }
  9189. QualType Ty = VD->getType();
  9190. if (Ty->isDependentType()) return;
  9191. // Require a complete type.
  9192. if (RequireCompleteType(VD->getLocation(),
  9193. Context.getBaseElementType(Ty),
  9194. diag::err_typecheck_decl_incomplete_type)) {
  9195. VD->setInvalidDecl();
  9196. return;
  9197. }
  9198. // Require a non-abstract type.
  9199. if (RequireNonAbstractType(VD->getLocation(), Ty,
  9200. diag::err_abstract_type_in_decl,
  9201. AbstractVariableType)) {
  9202. VD->setInvalidDecl();
  9203. return;
  9204. }
  9205. // Don't bother complaining about constructors or destructors,
  9206. // though.
  9207. }
  9208. /// Checks if an object of the given type can be initialized with parenthesized
  9209. /// init-list.
  9210. ///
  9211. /// \param TargetType Type of object being initialized.
  9212. ///
  9213. /// The function is used to detect wrong initializations, such as 'int({0})'.
  9214. ///
  9215. bool Sema::canInitializeWithParenthesizedList(QualType TargetType) {
  9216. return TargetType->isDependentType() || TargetType->isRecordType() ||
  9217. TargetType->getContainedAutoType();
  9218. }
  9219. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  9220. // If there is no declaration, there was an error parsing it. Just ignore it.
  9221. if (!RealDecl)
  9222. return;
  9223. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  9224. QualType Type = Var->getType();
  9225. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  9226. if (isa<DecompositionDecl>(RealDecl)) {
  9227. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  9228. Var->setInvalidDecl();
  9229. return;
  9230. }
  9231. if (Type->isUndeducedType() &&
  9232. DeduceVariableDeclarationType(Var, false, nullptr))
  9233. return;
  9234. // C++11 [class.static.data]p3: A static data member can be declared with
  9235. // the constexpr specifier; if so, its declaration shall specify
  9236. // a brace-or-equal-initializer.
  9237. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  9238. // the definition of a variable [...] or the declaration of a static data
  9239. // member.
  9240. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  9241. !Var->isThisDeclarationADemotedDefinition()) {
  9242. if (Var->isStaticDataMember()) {
  9243. // C++1z removes the relevant rule; the in-class declaration is always
  9244. // a definition there.
  9245. if (!getLangOpts().CPlusPlus1z) {
  9246. Diag(Var->getLocation(),
  9247. diag::err_constexpr_static_mem_var_requires_init)
  9248. << Var->getDeclName();
  9249. Var->setInvalidDecl();
  9250. return;
  9251. }
  9252. } else {
  9253. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  9254. Var->setInvalidDecl();
  9255. return;
  9256. }
  9257. }
  9258. // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
  9259. // definition having the concept specifier is called a variable concept. A
  9260. // concept definition refers to [...] a variable concept and its initializer.
  9261. if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
  9262. if (VTD->isConcept()) {
  9263. Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
  9264. Var->setInvalidDecl();
  9265. return;
  9266. }
  9267. }
  9268. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  9269. // be initialized.
  9270. if (!Var->isInvalidDecl() &&
  9271. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  9272. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  9273. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  9274. Var->setInvalidDecl();
  9275. return;
  9276. }
  9277. switch (Var->isThisDeclarationADefinition()) {
  9278. case VarDecl::Definition:
  9279. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  9280. break;
  9281. // We have an out-of-line definition of a static data member
  9282. // that has an in-class initializer, so we type-check this like
  9283. // a declaration.
  9284. //
  9285. // Fall through
  9286. case VarDecl::DeclarationOnly:
  9287. // It's only a declaration.
  9288. // Block scope. C99 6.7p7: If an identifier for an object is
  9289. // declared with no linkage (C99 6.2.2p6), the type for the
  9290. // object shall be complete.
  9291. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  9292. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  9293. RequireCompleteType(Var->getLocation(), Type,
  9294. diag::err_typecheck_decl_incomplete_type))
  9295. Var->setInvalidDecl();
  9296. // Make sure that the type is not abstract.
  9297. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  9298. RequireNonAbstractType(Var->getLocation(), Type,
  9299. diag::err_abstract_type_in_decl,
  9300. AbstractVariableType))
  9301. Var->setInvalidDecl();
  9302. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  9303. Var->getStorageClass() == SC_PrivateExtern) {
  9304. Diag(Var->getLocation(), diag::warn_private_extern);
  9305. Diag(Var->getLocation(), diag::note_private_extern);
  9306. }
  9307. return;
  9308. case VarDecl::TentativeDefinition:
  9309. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  9310. // object that has file scope without an initializer, and without a
  9311. // storage-class specifier or with the storage-class specifier "static",
  9312. // constitutes a tentative definition. Note: A tentative definition with
  9313. // external linkage is valid (C99 6.2.2p5).
  9314. if (!Var->isInvalidDecl()) {
  9315. if (const IncompleteArrayType *ArrayT
  9316. = Context.getAsIncompleteArrayType(Type)) {
  9317. if (RequireCompleteType(Var->getLocation(),
  9318. ArrayT->getElementType(),
  9319. diag::err_illegal_decl_array_incomplete_type))
  9320. Var->setInvalidDecl();
  9321. } else if (Var->getStorageClass() == SC_Static) {
  9322. // C99 6.9.2p3: If the declaration of an identifier for an object is
  9323. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  9324. // declared type shall not be an incomplete type.
  9325. // NOTE: code such as the following
  9326. // static struct s;
  9327. // struct s { int a; };
  9328. // is accepted by gcc. Hence here we issue a warning instead of
  9329. // an error and we do not invalidate the static declaration.
  9330. // NOTE: to avoid multiple warnings, only check the first declaration.
  9331. if (Var->isFirstDecl())
  9332. RequireCompleteType(Var->getLocation(), Type,
  9333. diag::ext_typecheck_decl_incomplete_type);
  9334. }
  9335. }
  9336. // Record the tentative definition; we're done.
  9337. if (!Var->isInvalidDecl())
  9338. TentativeDefinitions.push_back(Var);
  9339. return;
  9340. }
  9341. // Provide a specific diagnostic for uninitialized variable
  9342. // definitions with incomplete array type.
  9343. if (Type->isIncompleteArrayType()) {
  9344. Diag(Var->getLocation(),
  9345. diag::err_typecheck_incomplete_array_needs_initializer);
  9346. Var->setInvalidDecl();
  9347. return;
  9348. }
  9349. // Provide a specific diagnostic for uninitialized variable
  9350. // definitions with reference type.
  9351. if (Type->isReferenceType()) {
  9352. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  9353. << Var->getDeclName()
  9354. << SourceRange(Var->getLocation(), Var->getLocation());
  9355. Var->setInvalidDecl();
  9356. return;
  9357. }
  9358. // Do not attempt to type-check the default initializer for a
  9359. // variable with dependent type.
  9360. if (Type->isDependentType())
  9361. return;
  9362. if (Var->isInvalidDecl())
  9363. return;
  9364. if (!Var->hasAttr<AliasAttr>()) {
  9365. if (RequireCompleteType(Var->getLocation(),
  9366. Context.getBaseElementType(Type),
  9367. diag::err_typecheck_decl_incomplete_type)) {
  9368. Var->setInvalidDecl();
  9369. return;
  9370. }
  9371. } else {
  9372. return;
  9373. }
  9374. // The variable can not have an abstract class type.
  9375. if (RequireNonAbstractType(Var->getLocation(), Type,
  9376. diag::err_abstract_type_in_decl,
  9377. AbstractVariableType)) {
  9378. Var->setInvalidDecl();
  9379. return;
  9380. }
  9381. // Check for jumps past the implicit initializer. C++0x
  9382. // clarifies that this applies to a "variable with automatic
  9383. // storage duration", not a "local variable".
  9384. // C++11 [stmt.dcl]p3
  9385. // A program that jumps from a point where a variable with automatic
  9386. // storage duration is not in scope to a point where it is in scope is
  9387. // ill-formed unless the variable has scalar type, class type with a
  9388. // trivial default constructor and a trivial destructor, a cv-qualified
  9389. // version of one of these types, or an array of one of the preceding
  9390. // types and is declared without an initializer.
  9391. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  9392. if (const RecordType *Record
  9393. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  9394. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  9395. // Mark the function for further checking even if the looser rules of
  9396. // C++11 do not require such checks, so that we can diagnose
  9397. // incompatibilities with C++98.
  9398. if (!CXXRecord->isPOD())
  9399. getCurFunction()->setHasBranchProtectedScope();
  9400. }
  9401. }
  9402. // C++03 [dcl.init]p9:
  9403. // If no initializer is specified for an object, and the
  9404. // object is of (possibly cv-qualified) non-POD class type (or
  9405. // array thereof), the object shall be default-initialized; if
  9406. // the object is of const-qualified type, the underlying class
  9407. // type shall have a user-declared default
  9408. // constructor. Otherwise, if no initializer is specified for
  9409. // a non- static object, the object and its subobjects, if
  9410. // any, have an indeterminate initial value); if the object
  9411. // or any of its subobjects are of const-qualified type, the
  9412. // program is ill-formed.
  9413. // C++0x [dcl.init]p11:
  9414. // If no initializer is specified for an object, the object is
  9415. // default-initialized; [...].
  9416. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  9417. InitializationKind Kind
  9418. = InitializationKind::CreateDefault(Var->getLocation());
  9419. InitializationSequence InitSeq(*this, Entity, Kind, None);
  9420. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  9421. if (Init.isInvalid())
  9422. Var->setInvalidDecl();
  9423. else if (Init.get()) {
  9424. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  9425. // This is important for template substitution.
  9426. Var->setInitStyle(VarDecl::CallInit);
  9427. }
  9428. CheckCompleteVariableDeclaration(Var);
  9429. }
  9430. }
  9431. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  9432. // If there is no declaration, there was an error parsing it. Ignore it.
  9433. if (!D)
  9434. return;
  9435. VarDecl *VD = dyn_cast<VarDecl>(D);
  9436. if (!VD) {
  9437. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  9438. D->setInvalidDecl();
  9439. return;
  9440. }
  9441. VD->setCXXForRangeDecl(true);
  9442. // for-range-declaration cannot be given a storage class specifier.
  9443. int Error = -1;
  9444. switch (VD->getStorageClass()) {
  9445. case SC_None:
  9446. break;
  9447. case SC_Extern:
  9448. Error = 0;
  9449. break;
  9450. case SC_Static:
  9451. Error = 1;
  9452. break;
  9453. case SC_PrivateExtern:
  9454. Error = 2;
  9455. break;
  9456. case SC_Auto:
  9457. Error = 3;
  9458. break;
  9459. case SC_Register:
  9460. Error = 4;
  9461. break;
  9462. }
  9463. if (Error != -1) {
  9464. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  9465. << VD->getDeclName() << Error;
  9466. D->setInvalidDecl();
  9467. }
  9468. }
  9469. StmtResult
  9470. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  9471. IdentifierInfo *Ident,
  9472. ParsedAttributes &Attrs,
  9473. SourceLocation AttrEnd) {
  9474. // C++1y [stmt.iter]p1:
  9475. // A range-based for statement of the form
  9476. // for ( for-range-identifier : for-range-initializer ) statement
  9477. // is equivalent to
  9478. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  9479. DeclSpec DS(Attrs.getPool().getFactory());
  9480. const char *PrevSpec;
  9481. unsigned DiagID;
  9482. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  9483. getPrintingPolicy());
  9484. Declarator D(DS, Declarator::ForContext);
  9485. D.SetIdentifier(Ident, IdentLoc);
  9486. D.takeAttributes(Attrs, AttrEnd);
  9487. ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
  9488. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
  9489. EmptyAttrs, IdentLoc);
  9490. Decl *Var = ActOnDeclarator(S, D);
  9491. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  9492. FinalizeDeclaration(Var);
  9493. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  9494. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  9495. }
  9496. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  9497. if (var->isInvalidDecl()) return;
  9498. if (getLangOpts().OpenCL) {
  9499. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  9500. // initialiser
  9501. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  9502. !var->hasInit()) {
  9503. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  9504. << 1 /*Init*/;
  9505. var->setInvalidDecl();
  9506. return;
  9507. }
  9508. }
  9509. // In Objective-C, don't allow jumps past the implicit initialization of a
  9510. // local retaining variable.
  9511. if (getLangOpts().ObjC1 &&
  9512. var->hasLocalStorage()) {
  9513. switch (var->getType().getObjCLifetime()) {
  9514. case Qualifiers::OCL_None:
  9515. case Qualifiers::OCL_ExplicitNone:
  9516. case Qualifiers::OCL_Autoreleasing:
  9517. break;
  9518. case Qualifiers::OCL_Weak:
  9519. case Qualifiers::OCL_Strong:
  9520. getCurFunction()->setHasBranchProtectedScope();
  9521. break;
  9522. }
  9523. }
  9524. // Warn about externally-visible variables being defined without a
  9525. // prior declaration. We only want to do this for global
  9526. // declarations, but we also specifically need to avoid doing it for
  9527. // class members because the linkage of an anonymous class can
  9528. // change if it's later given a typedef name.
  9529. if (var->isThisDeclarationADefinition() &&
  9530. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  9531. var->isExternallyVisible() && var->hasLinkage() &&
  9532. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  9533. var->getLocation())) {
  9534. // Find a previous declaration that's not a definition.
  9535. VarDecl *prev = var->getPreviousDecl();
  9536. while (prev && prev->isThisDeclarationADefinition())
  9537. prev = prev->getPreviousDecl();
  9538. if (!prev)
  9539. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  9540. }
  9541. // Cache the result of checking for constant initialization.
  9542. Optional<bool> CacheHasConstInit;
  9543. const Expr *CacheCulprit;
  9544. auto checkConstInit = [&]() mutable {
  9545. if (!CacheHasConstInit)
  9546. CacheHasConstInit = var->getInit()->isConstantInitializer(
  9547. Context, var->getType()->isReferenceType(), &CacheCulprit);
  9548. return *CacheHasConstInit;
  9549. };
  9550. if (var->getTLSKind() == VarDecl::TLS_Static) {
  9551. if (var->getType().isDestructedType()) {
  9552. // GNU C++98 edits for __thread, [basic.start.term]p3:
  9553. // The type of an object with thread storage duration shall not
  9554. // have a non-trivial destructor.
  9555. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  9556. if (getLangOpts().CPlusPlus11)
  9557. Diag(var->getLocation(), diag::note_use_thread_local);
  9558. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  9559. if (!checkConstInit()) {
  9560. // GNU C++98 edits for __thread, [basic.start.init]p4:
  9561. // An object of thread storage duration shall not require dynamic
  9562. // initialization.
  9563. // FIXME: Need strict checking here.
  9564. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  9565. << CacheCulprit->getSourceRange();
  9566. if (getLangOpts().CPlusPlus11)
  9567. Diag(var->getLocation(), diag::note_use_thread_local);
  9568. }
  9569. }
  9570. }
  9571. // Apply section attributes and pragmas to global variables.
  9572. bool GlobalStorage = var->hasGlobalStorage();
  9573. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  9574. ActiveTemplateInstantiations.empty()) {
  9575. PragmaStack<StringLiteral *> *Stack = nullptr;
  9576. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  9577. if (var->getType().isConstQualified())
  9578. Stack = &ConstSegStack;
  9579. else if (!var->getInit()) {
  9580. Stack = &BSSSegStack;
  9581. SectionFlags |= ASTContext::PSF_Write;
  9582. } else {
  9583. Stack = &DataSegStack;
  9584. SectionFlags |= ASTContext::PSF_Write;
  9585. }
  9586. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  9587. var->addAttr(SectionAttr::CreateImplicit(
  9588. Context, SectionAttr::Declspec_allocate,
  9589. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  9590. }
  9591. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  9592. if (UnifySection(SA->getName(), SectionFlags, var))
  9593. var->dropAttr<SectionAttr>();
  9594. // Apply the init_seg attribute if this has an initializer. If the
  9595. // initializer turns out to not be dynamic, we'll end up ignoring this
  9596. // attribute.
  9597. if (CurInitSeg && var->getInit())
  9598. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  9599. CurInitSegLoc));
  9600. }
  9601. // All the following checks are C++ only.
  9602. if (!getLangOpts().CPlusPlus) {
  9603. // If this variable must be emitted, add it as an initializer for the
  9604. // current module.
  9605. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  9606. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  9607. return;
  9608. }
  9609. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  9610. CheckCompleteDecompositionDeclaration(DD);
  9611. QualType type = var->getType();
  9612. if (type->isDependentType()) return;
  9613. // __block variables might require us to capture a copy-initializer.
  9614. if (var->hasAttr<BlocksAttr>()) {
  9615. // It's currently invalid to ever have a __block variable with an
  9616. // array type; should we diagnose that here?
  9617. // Regardless, we don't want to ignore array nesting when
  9618. // constructing this copy.
  9619. if (type->isStructureOrClassType()) {
  9620. EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
  9621. SourceLocation poi = var->getLocation();
  9622. Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
  9623. ExprResult result
  9624. = PerformMoveOrCopyInitialization(
  9625. InitializedEntity::InitializeBlock(poi, type, false),
  9626. var, var->getType(), varRef, /*AllowNRVO=*/true);
  9627. if (!result.isInvalid()) {
  9628. result = MaybeCreateExprWithCleanups(result);
  9629. Expr *init = result.getAs<Expr>();
  9630. Context.setBlockVarCopyInits(var, init);
  9631. }
  9632. }
  9633. }
  9634. Expr *Init = var->getInit();
  9635. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  9636. QualType baseType = Context.getBaseElementType(type);
  9637. if (!var->getDeclContext()->isDependentContext() &&
  9638. Init && !Init->isValueDependent()) {
  9639. if (var->isConstexpr()) {
  9640. SmallVector<PartialDiagnosticAt, 8> Notes;
  9641. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  9642. SourceLocation DiagLoc = var->getLocation();
  9643. // If the note doesn't add any useful information other than a source
  9644. // location, fold it into the primary diagnostic.
  9645. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  9646. diag::note_invalid_subexpr_in_const_expr) {
  9647. DiagLoc = Notes[0].first;
  9648. Notes.clear();
  9649. }
  9650. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  9651. << var << Init->getSourceRange();
  9652. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  9653. Diag(Notes[I].first, Notes[I].second);
  9654. }
  9655. } else if (var->isUsableInConstantExpressions(Context)) {
  9656. // Check whether the initializer of a const variable of integral or
  9657. // enumeration type is an ICE now, since we can't tell whether it was
  9658. // initialized by a constant expression if we check later.
  9659. var->checkInitIsICE();
  9660. }
  9661. // Don't emit further diagnostics about constexpr globals since they
  9662. // were just diagnosed.
  9663. if (!var->isConstexpr() && GlobalStorage &&
  9664. var->hasAttr<RequireConstantInitAttr>()) {
  9665. // FIXME: Need strict checking in C++03 here.
  9666. bool DiagErr = getLangOpts().CPlusPlus11
  9667. ? !var->checkInitIsICE() : !checkConstInit();
  9668. if (DiagErr) {
  9669. auto attr = var->getAttr<RequireConstantInitAttr>();
  9670. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  9671. << Init->getSourceRange();
  9672. Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
  9673. << attr->getRange();
  9674. }
  9675. }
  9676. else if (!var->isConstexpr() && IsGlobal &&
  9677. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  9678. var->getLocation())) {
  9679. // Warn about globals which don't have a constant initializer. Don't
  9680. // warn about globals with a non-trivial destructor because we already
  9681. // warned about them.
  9682. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  9683. if (!(RD && !RD->hasTrivialDestructor())) {
  9684. if (!checkConstInit())
  9685. Diag(var->getLocation(), diag::warn_global_constructor)
  9686. << Init->getSourceRange();
  9687. }
  9688. }
  9689. }
  9690. // Require the destructor.
  9691. if (const RecordType *recordType = baseType->getAs<RecordType>())
  9692. FinalizeVarWithDestructor(var, recordType);
  9693. // If this variable must be emitted, add it as an initializer for the current
  9694. // module.
  9695. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  9696. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  9697. }
  9698. /// \brief Determines if a variable's alignment is dependent.
  9699. static bool hasDependentAlignment(VarDecl *VD) {
  9700. if (VD->getType()->isDependentType())
  9701. return true;
  9702. for (auto *I : VD->specific_attrs<AlignedAttr>())
  9703. if (I->isAlignmentDependent())
  9704. return true;
  9705. return false;
  9706. }
  9707. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  9708. /// any semantic actions necessary after any initializer has been attached.
  9709. void
  9710. Sema::FinalizeDeclaration(Decl *ThisDecl) {
  9711. // Note that we are no longer parsing the initializer for this declaration.
  9712. ParsingInitForAutoVars.erase(ThisDecl);
  9713. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  9714. if (!VD)
  9715. return;
  9716. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  9717. for (auto *BD : DD->bindings()) {
  9718. FinalizeDeclaration(BD);
  9719. }
  9720. }
  9721. checkAttributesAfterMerging(*this, *VD);
  9722. // Perform TLS alignment check here after attributes attached to the variable
  9723. // which may affect the alignment have been processed. Only perform the check
  9724. // if the target has a maximum TLS alignment (zero means no constraints).
  9725. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  9726. // Protect the check so that it's not performed on dependent types and
  9727. // dependent alignments (we can't determine the alignment in that case).
  9728. if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
  9729. !VD->isInvalidDecl()) {
  9730. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  9731. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  9732. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  9733. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  9734. << (unsigned)MaxAlignChars.getQuantity();
  9735. }
  9736. }
  9737. }
  9738. if (VD->isStaticLocal()) {
  9739. if (FunctionDecl *FD =
  9740. dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  9741. // Static locals inherit dll attributes from their function.
  9742. if (Attr *A = getDLLAttr(FD)) {
  9743. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  9744. NewAttr->setInherited(true);
  9745. VD->addAttr(NewAttr);
  9746. }
  9747. // CUDA E.2.9.4: Within the body of a __device__ or __global__
  9748. // function, only __shared__ variables may be declared with
  9749. // static storage class.
  9750. if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
  9751. CUDADiagIfDeviceCode(VD->getLocation(),
  9752. diag::err_device_static_local_var)
  9753. << CurrentCUDATarget())
  9754. VD->setInvalidDecl();
  9755. }
  9756. }
  9757. // Perform check for initializers of device-side global variables.
  9758. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  9759. // 7.5). We must also apply the same checks to all __shared__
  9760. // variables whether they are local or not. CUDA also allows
  9761. // constant initializers for __constant__ and __device__ variables.
  9762. if (getLangOpts().CUDA) {
  9763. const Expr *Init = VD->getInit();
  9764. if (Init && VD->hasGlobalStorage()) {
  9765. if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
  9766. VD->hasAttr<CUDASharedAttr>()) {
  9767. assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
  9768. bool AllowedInit = false;
  9769. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
  9770. AllowedInit =
  9771. isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
  9772. // We'll allow constant initializers even if it's a non-empty
  9773. // constructor according to CUDA rules. This deviates from NVCC,
  9774. // but allows us to handle things like constexpr constructors.
  9775. if (!AllowedInit &&
  9776. (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  9777. AllowedInit = VD->getInit()->isConstantInitializer(
  9778. Context, VD->getType()->isReferenceType());
  9779. // Also make sure that destructor, if there is one, is empty.
  9780. if (AllowedInit)
  9781. if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
  9782. AllowedInit =
  9783. isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
  9784. if (!AllowedInit) {
  9785. Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
  9786. ? diag::err_shared_var_init
  9787. : diag::err_dynamic_var_init)
  9788. << Init->getSourceRange();
  9789. VD->setInvalidDecl();
  9790. }
  9791. } else {
  9792. // This is a host-side global variable. Check that the initializer is
  9793. // callable from the host side.
  9794. const FunctionDecl *InitFn = nullptr;
  9795. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
  9796. InitFn = CE->getConstructor();
  9797. } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
  9798. InitFn = CE->getDirectCallee();
  9799. }
  9800. if (InitFn) {
  9801. CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
  9802. if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
  9803. Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
  9804. << InitFnTarget << InitFn;
  9805. Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
  9806. VD->setInvalidDecl();
  9807. }
  9808. }
  9809. }
  9810. }
  9811. }
  9812. // Grab the dllimport or dllexport attribute off of the VarDecl.
  9813. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  9814. // Imported static data members cannot be defined out-of-line.
  9815. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  9816. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  9817. VD->isThisDeclarationADefinition()) {
  9818. // We allow definitions of dllimport class template static data members
  9819. // with a warning.
  9820. CXXRecordDecl *Context =
  9821. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  9822. bool IsClassTemplateMember =
  9823. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  9824. Context->getDescribedClassTemplate();
  9825. Diag(VD->getLocation(),
  9826. IsClassTemplateMember
  9827. ? diag::warn_attribute_dllimport_static_field_definition
  9828. : diag::err_attribute_dllimport_static_field_definition);
  9829. Diag(IA->getLocation(), diag::note_attribute);
  9830. if (!IsClassTemplateMember)
  9831. VD->setInvalidDecl();
  9832. }
  9833. }
  9834. // dllimport/dllexport variables cannot be thread local, their TLS index
  9835. // isn't exported with the variable.
  9836. if (DLLAttr && VD->getTLSKind()) {
  9837. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  9838. if (F && getDLLAttr(F)) {
  9839. assert(VD->isStaticLocal());
  9840. // But if this is a static local in a dlimport/dllexport function, the
  9841. // function will never be inlined, which means the var would never be
  9842. // imported, so having it marked import/export is safe.
  9843. } else {
  9844. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  9845. << DLLAttr;
  9846. VD->setInvalidDecl();
  9847. }
  9848. }
  9849. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  9850. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  9851. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  9852. VD->dropAttr<UsedAttr>();
  9853. }
  9854. }
  9855. const DeclContext *DC = VD->getDeclContext();
  9856. // If there's a #pragma GCC visibility in scope, and this isn't a class
  9857. // member, set the visibility of this variable.
  9858. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  9859. AddPushedVisibilityAttribute(VD);
  9860. // FIXME: Warn on unused templates.
  9861. if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
  9862. !isa<VarTemplatePartialSpecializationDecl>(VD))
  9863. MarkUnusedFileScopedDecl(VD);
  9864. // Now we have parsed the initializer and can update the table of magic
  9865. // tag values.
  9866. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  9867. !VD->getType()->isIntegralOrEnumerationType())
  9868. return;
  9869. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  9870. const Expr *MagicValueExpr = VD->getInit();
  9871. if (!MagicValueExpr) {
  9872. continue;
  9873. }
  9874. llvm::APSInt MagicValueInt;
  9875. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  9876. Diag(I->getRange().getBegin(),
  9877. diag::err_type_tag_for_datatype_not_ice)
  9878. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  9879. continue;
  9880. }
  9881. if (MagicValueInt.getActiveBits() > 64) {
  9882. Diag(I->getRange().getBegin(),
  9883. diag::err_type_tag_for_datatype_too_large)
  9884. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  9885. continue;
  9886. }
  9887. uint64_t MagicValue = MagicValueInt.getZExtValue();
  9888. RegisterTypeTagForDatatype(I->getArgumentKind(),
  9889. MagicValue,
  9890. I->getMatchingCType(),
  9891. I->getLayoutCompatible(),
  9892. I->getMustBeNull());
  9893. }
  9894. }
  9895. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  9896. auto *VD = dyn_cast<VarDecl>(DD);
  9897. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  9898. }
  9899. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  9900. ArrayRef<Decl *> Group) {
  9901. SmallVector<Decl*, 8> Decls;
  9902. if (DS.isTypeSpecOwned())
  9903. Decls.push_back(DS.getRepAsDecl());
  9904. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  9905. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  9906. bool DiagnosedMultipleDecomps = false;
  9907. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  9908. bool DiagnosedNonDeducedAuto = false;
  9909. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  9910. if (Decl *D = Group[i]) {
  9911. // For declarators, there are some additional syntactic-ish checks we need
  9912. // to perform.
  9913. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  9914. if (!FirstDeclaratorInGroup)
  9915. FirstDeclaratorInGroup = DD;
  9916. if (!FirstDecompDeclaratorInGroup)
  9917. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  9918. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  9919. !hasDeducedAuto(DD))
  9920. FirstNonDeducedAutoInGroup = DD;
  9921. if (FirstDeclaratorInGroup != DD) {
  9922. // A decomposition declaration cannot be combined with any other
  9923. // declaration in the same group.
  9924. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  9925. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  9926. diag::err_decomp_decl_not_alone)
  9927. << FirstDeclaratorInGroup->getSourceRange()
  9928. << DD->getSourceRange();
  9929. DiagnosedMultipleDecomps = true;
  9930. }
  9931. // A declarator that uses 'auto' in any way other than to declare a
  9932. // variable with a deduced type cannot be combined with any other
  9933. // declarator in the same group.
  9934. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  9935. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  9936. diag::err_auto_non_deduced_not_alone)
  9937. << FirstNonDeducedAutoInGroup->getType()
  9938. ->hasAutoForTrailingReturnType()
  9939. << FirstDeclaratorInGroup->getSourceRange()
  9940. << DD->getSourceRange();
  9941. DiagnosedNonDeducedAuto = true;
  9942. }
  9943. }
  9944. }
  9945. Decls.push_back(D);
  9946. }
  9947. }
  9948. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  9949. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  9950. handleTagNumbering(Tag, S);
  9951. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  9952. getLangOpts().CPlusPlus)
  9953. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  9954. }
  9955. }
  9956. return BuildDeclaratorGroup(Decls);
  9957. }
  9958. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  9959. /// group, performing any necessary semantic checking.
  9960. Sema::DeclGroupPtrTy
  9961. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  9962. // C++14 [dcl.spec.auto]p7: (DR1347)
  9963. // If the type that replaces the placeholder type is not the same in each
  9964. // deduction, the program is ill-formed.
  9965. if (Group.size() > 1) {
  9966. QualType Deduced;
  9967. VarDecl *DeducedDecl = nullptr;
  9968. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  9969. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  9970. if (!D || D->isInvalidDecl())
  9971. break;
  9972. DeducedType *DT = D->getType()->getContainedDeducedType();
  9973. if (!DT || DT->getDeducedType().isNull())
  9974. continue;
  9975. if (Deduced.isNull()) {
  9976. Deduced = DT->getDeducedType();
  9977. DeducedDecl = D;
  9978. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  9979. auto *AT = dyn_cast<AutoType>(DT);
  9980. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  9981. diag::err_auto_different_deductions)
  9982. << (AT ? (unsigned)AT->getKeyword() : 3)
  9983. << Deduced << DeducedDecl->getDeclName()
  9984. << DT->getDeducedType() << D->getDeclName()
  9985. << DeducedDecl->getInit()->getSourceRange()
  9986. << D->getInit()->getSourceRange();
  9987. D->setInvalidDecl();
  9988. break;
  9989. }
  9990. }
  9991. }
  9992. ActOnDocumentableDecls(Group);
  9993. return DeclGroupPtrTy::make(
  9994. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  9995. }
  9996. void Sema::ActOnDocumentableDecl(Decl *D) {
  9997. ActOnDocumentableDecls(D);
  9998. }
  9999. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  10000. // Don't parse the comment if Doxygen diagnostics are ignored.
  10001. if (Group.empty() || !Group[0])
  10002. return;
  10003. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  10004. Group[0]->getLocation()) &&
  10005. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  10006. Group[0]->getLocation()))
  10007. return;
  10008. if (Group.size() >= 2) {
  10009. // This is a decl group. Normally it will contain only declarations
  10010. // produced from declarator list. But in case we have any definitions or
  10011. // additional declaration references:
  10012. // 'typedef struct S {} S;'
  10013. // 'typedef struct S *S;'
  10014. // 'struct S *pS;'
  10015. // FinalizeDeclaratorGroup adds these as separate declarations.
  10016. Decl *MaybeTagDecl = Group[0];
  10017. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  10018. Group = Group.slice(1);
  10019. }
  10020. }
  10021. // See if there are any new comments that are not attached to a decl.
  10022. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  10023. if (!Comments.empty() &&
  10024. !Comments.back()->isAttached()) {
  10025. // There is at least one comment that not attached to a decl.
  10026. // Maybe it should be attached to one of these decls?
  10027. //
  10028. // Note that this way we pick up not only comments that precede the
  10029. // declaration, but also comments that *follow* the declaration -- thanks to
  10030. // the lookahead in the lexer: we've consumed the semicolon and looked
  10031. // ahead through comments.
  10032. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  10033. Context.getCommentForDecl(Group[i], &PP);
  10034. }
  10035. }
  10036. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  10037. /// to introduce parameters into function prototype scope.
  10038. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  10039. const DeclSpec &DS = D.getDeclSpec();
  10040. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  10041. // C++03 [dcl.stc]p2 also permits 'auto'.
  10042. StorageClass SC = SC_None;
  10043. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  10044. SC = SC_Register;
  10045. } else if (getLangOpts().CPlusPlus &&
  10046. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  10047. SC = SC_Auto;
  10048. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  10049. Diag(DS.getStorageClassSpecLoc(),
  10050. diag::err_invalid_storage_class_in_func_decl);
  10051. D.getMutableDeclSpec().ClearStorageClassSpecs();
  10052. }
  10053. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  10054. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  10055. << DeclSpec::getSpecifierName(TSCS);
  10056. if (DS.isInlineSpecified())
  10057. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  10058. << getLangOpts().CPlusPlus1z;
  10059. if (DS.isConstexprSpecified())
  10060. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  10061. << 0;
  10062. if (DS.isConceptSpecified())
  10063. Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
  10064. DiagnoseFunctionSpecifiers(DS);
  10065. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  10066. QualType parmDeclType = TInfo->getType();
  10067. if (getLangOpts().CPlusPlus) {
  10068. // Check that there are no default arguments inside the type of this
  10069. // parameter.
  10070. CheckExtraCXXDefaultArguments(D);
  10071. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  10072. if (D.getCXXScopeSpec().isSet()) {
  10073. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  10074. << D.getCXXScopeSpec().getRange();
  10075. D.getCXXScopeSpec().clear();
  10076. }
  10077. }
  10078. // Ensure we have a valid name
  10079. IdentifierInfo *II = nullptr;
  10080. if (D.hasName()) {
  10081. II = D.getIdentifier();
  10082. if (!II) {
  10083. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  10084. << GetNameForDeclarator(D).getName();
  10085. D.setInvalidType(true);
  10086. }
  10087. }
  10088. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  10089. if (II) {
  10090. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  10091. ForRedeclaration);
  10092. LookupName(R, S);
  10093. if (R.isSingleResult()) {
  10094. NamedDecl *PrevDecl = R.getFoundDecl();
  10095. if (PrevDecl->isTemplateParameter()) {
  10096. // Maybe we will complain about the shadowed template parameter.
  10097. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  10098. // Just pretend that we didn't see the previous declaration.
  10099. PrevDecl = nullptr;
  10100. } else if (S->isDeclScope(PrevDecl)) {
  10101. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  10102. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  10103. // Recover by removing the name
  10104. II = nullptr;
  10105. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  10106. D.setInvalidType(true);
  10107. }
  10108. }
  10109. }
  10110. // Temporarily put parameter variables in the translation unit, not
  10111. // the enclosing context. This prevents them from accidentally
  10112. // looking like class members in C++.
  10113. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  10114. D.getLocStart(),
  10115. D.getIdentifierLoc(), II,
  10116. parmDeclType, TInfo,
  10117. SC);
  10118. if (D.isInvalidType())
  10119. New->setInvalidDecl();
  10120. assert(S->isFunctionPrototypeScope());
  10121. assert(S->getFunctionPrototypeDepth() >= 1);
  10122. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  10123. S->getNextFunctionPrototypeIndex());
  10124. // Add the parameter declaration into this scope.
  10125. S->AddDecl(New);
  10126. if (II)
  10127. IdResolver.AddDecl(New);
  10128. ProcessDeclAttributes(S, New, D);
  10129. if (D.getDeclSpec().isModulePrivateSpecified())
  10130. Diag(New->getLocation(), diag::err_module_private_local)
  10131. << 1 << New->getDeclName()
  10132. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  10133. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  10134. if (New->hasAttr<BlocksAttr>()) {
  10135. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  10136. }
  10137. return New;
  10138. }
  10139. /// \brief Synthesizes a variable for a parameter arising from a
  10140. /// typedef.
  10141. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  10142. SourceLocation Loc,
  10143. QualType T) {
  10144. /* FIXME: setting StartLoc == Loc.
  10145. Would it be worth to modify callers so as to provide proper source
  10146. location for the unnamed parameters, embedding the parameter's type? */
  10147. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  10148. T, Context.getTrivialTypeSourceInfo(T, Loc),
  10149. SC_None, nullptr);
  10150. Param->setImplicit();
  10151. return Param;
  10152. }
  10153. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  10154. // Don't diagnose unused-parameter errors in template instantiations; we
  10155. // will already have done so in the template itself.
  10156. if (!ActiveTemplateInstantiations.empty())
  10157. return;
  10158. for (const ParmVarDecl *Parameter : Parameters) {
  10159. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  10160. !Parameter->hasAttr<UnusedAttr>()) {
  10161. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  10162. << Parameter->getDeclName();
  10163. }
  10164. }
  10165. }
  10166. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  10167. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  10168. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  10169. return;
  10170. // Warn if the return value is pass-by-value and larger than the specified
  10171. // threshold.
  10172. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  10173. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  10174. if (Size > LangOpts.NumLargeByValueCopy)
  10175. Diag(D->getLocation(), diag::warn_return_value_size)
  10176. << D->getDeclName() << Size;
  10177. }
  10178. // Warn if any parameter is pass-by-value and larger than the specified
  10179. // threshold.
  10180. for (const ParmVarDecl *Parameter : Parameters) {
  10181. QualType T = Parameter->getType();
  10182. if (T->isDependentType() || !T.isPODType(Context))
  10183. continue;
  10184. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  10185. if (Size > LangOpts.NumLargeByValueCopy)
  10186. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  10187. << Parameter->getDeclName() << Size;
  10188. }
  10189. }
  10190. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  10191. SourceLocation NameLoc, IdentifierInfo *Name,
  10192. QualType T, TypeSourceInfo *TSInfo,
  10193. StorageClass SC) {
  10194. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  10195. if (getLangOpts().ObjCAutoRefCount &&
  10196. T.getObjCLifetime() == Qualifiers::OCL_None &&
  10197. T->isObjCLifetimeType()) {
  10198. Qualifiers::ObjCLifetime lifetime;
  10199. // Special cases for arrays:
  10200. // - if it's const, use __unsafe_unretained
  10201. // - otherwise, it's an error
  10202. if (T->isArrayType()) {
  10203. if (!T.isConstQualified()) {
  10204. DelayedDiagnostics.add(
  10205. sema::DelayedDiagnostic::makeForbiddenType(
  10206. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  10207. }
  10208. lifetime = Qualifiers::OCL_ExplicitNone;
  10209. } else {
  10210. lifetime = T->getObjCARCImplicitLifetime();
  10211. }
  10212. T = Context.getLifetimeQualifiedType(T, lifetime);
  10213. }
  10214. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  10215. Context.getAdjustedParameterType(T),
  10216. TSInfo, SC, nullptr);
  10217. // Parameters can not be abstract class types.
  10218. // For record types, this is done by the AbstractClassUsageDiagnoser once
  10219. // the class has been completely parsed.
  10220. if (!CurContext->isRecord() &&
  10221. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  10222. AbstractParamType))
  10223. New->setInvalidDecl();
  10224. // Parameter declarators cannot be interface types. All ObjC objects are
  10225. // passed by reference.
  10226. if (T->isObjCObjectType()) {
  10227. SourceLocation TypeEndLoc =
  10228. getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
  10229. Diag(NameLoc,
  10230. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  10231. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  10232. T = Context.getObjCObjectPointerType(T);
  10233. New->setType(T);
  10234. }
  10235. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  10236. // duration shall not be qualified by an address-space qualifier."
  10237. // Since all parameters have automatic store duration, they can not have
  10238. // an address space.
  10239. if (T.getAddressSpace() != 0) {
  10240. // OpenCL allows function arguments declared to be an array of a type
  10241. // to be qualified with an address space.
  10242. if (!(getLangOpts().OpenCL && T->isArrayType())) {
  10243. Diag(NameLoc, diag::err_arg_with_address_space);
  10244. New->setInvalidDecl();
  10245. }
  10246. }
  10247. return New;
  10248. }
  10249. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  10250. SourceLocation LocAfterDecls) {
  10251. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  10252. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  10253. // for a K&R function.
  10254. if (!FTI.hasPrototype) {
  10255. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  10256. --i;
  10257. if (FTI.Params[i].Param == nullptr) {
  10258. SmallString<256> Code;
  10259. llvm::raw_svector_ostream(Code)
  10260. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  10261. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  10262. << FTI.Params[i].Ident
  10263. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  10264. // Implicitly declare the argument as type 'int' for lack of a better
  10265. // type.
  10266. AttributeFactory attrs;
  10267. DeclSpec DS(attrs);
  10268. const char* PrevSpec; // unused
  10269. unsigned DiagID; // unused
  10270. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  10271. DiagID, Context.getPrintingPolicy());
  10272. // Use the identifier location for the type source range.
  10273. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  10274. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  10275. Declarator ParamD(DS, Declarator::KNRTypeListContext);
  10276. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  10277. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  10278. }
  10279. }
  10280. }
  10281. }
  10282. Decl *
  10283. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  10284. MultiTemplateParamsArg TemplateParameterLists,
  10285. SkipBodyInfo *SkipBody) {
  10286. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  10287. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  10288. Scope *ParentScope = FnBodyScope->getParent();
  10289. D.setFunctionDefinitionKind(FDK_Definition);
  10290. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  10291. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  10292. }
  10293. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  10294. Consumer.HandleInlineFunctionDefinition(D);
  10295. }
  10296. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  10297. const FunctionDecl*& PossibleZeroParamPrototype) {
  10298. // Don't warn about invalid declarations.
  10299. if (FD->isInvalidDecl())
  10300. return false;
  10301. // Or declarations that aren't global.
  10302. if (!FD->isGlobal())
  10303. return false;
  10304. // Don't warn about C++ member functions.
  10305. if (isa<CXXMethodDecl>(FD))
  10306. return false;
  10307. // Don't warn about 'main'.
  10308. if (FD->isMain())
  10309. return false;
  10310. // Don't warn about inline functions.
  10311. if (FD->isInlined())
  10312. return false;
  10313. // Don't warn about function templates.
  10314. if (FD->getDescribedFunctionTemplate())
  10315. return false;
  10316. // Don't warn about function template specializations.
  10317. if (FD->isFunctionTemplateSpecialization())
  10318. return false;
  10319. // Don't warn for OpenCL kernels.
  10320. if (FD->hasAttr<OpenCLKernelAttr>())
  10321. return false;
  10322. // Don't warn on explicitly deleted functions.
  10323. if (FD->isDeleted())
  10324. return false;
  10325. bool MissingPrototype = true;
  10326. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  10327. Prev; Prev = Prev->getPreviousDecl()) {
  10328. // Ignore any declarations that occur in function or method
  10329. // scope, because they aren't visible from the header.
  10330. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  10331. continue;
  10332. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  10333. if (FD->getNumParams() == 0)
  10334. PossibleZeroParamPrototype = Prev;
  10335. break;
  10336. }
  10337. return MissingPrototype;
  10338. }
  10339. void
  10340. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  10341. const FunctionDecl *EffectiveDefinition,
  10342. SkipBodyInfo *SkipBody) {
  10343. const FunctionDecl *Definition = EffectiveDefinition;
  10344. if (!Definition)
  10345. if (!FD->isDefined(Definition))
  10346. return;
  10347. if (canRedefineFunction(Definition, getLangOpts()))
  10348. return;
  10349. // If we don't have a visible definition of the function, and it's inline or
  10350. // a template, skip the new definition.
  10351. if (SkipBody && !hasVisibleDefinition(Definition) &&
  10352. (Definition->getFormalLinkage() == InternalLinkage ||
  10353. Definition->isInlined() ||
  10354. Definition->getDescribedFunctionTemplate() ||
  10355. Definition->getNumTemplateParameterLists())) {
  10356. SkipBody->ShouldSkip = true;
  10357. if (auto *TD = Definition->getDescribedFunctionTemplate())
  10358. makeMergedDefinitionVisible(TD, FD->getLocation());
  10359. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
  10360. FD->getLocation());
  10361. return;
  10362. }
  10363. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  10364. Definition->getStorageClass() == SC_Extern)
  10365. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  10366. << FD->getDeclName() << getLangOpts().CPlusPlus;
  10367. else
  10368. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  10369. Diag(Definition->getLocation(), diag::note_previous_definition);
  10370. FD->setInvalidDecl();
  10371. }
  10372. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  10373. Sema &S) {
  10374. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  10375. LambdaScopeInfo *LSI = S.PushLambdaScope();
  10376. LSI->CallOperator = CallOperator;
  10377. LSI->Lambda = LambdaClass;
  10378. LSI->ReturnType = CallOperator->getReturnType();
  10379. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  10380. if (LCD == LCD_None)
  10381. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  10382. else if (LCD == LCD_ByCopy)
  10383. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  10384. else if (LCD == LCD_ByRef)
  10385. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  10386. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  10387. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  10388. LSI->Mutable = !CallOperator->isConst();
  10389. // Add the captures to the LSI so they can be noted as already
  10390. // captured within tryCaptureVar.
  10391. auto I = LambdaClass->field_begin();
  10392. for (const auto &C : LambdaClass->captures()) {
  10393. if (C.capturesVariable()) {
  10394. VarDecl *VD = C.getCapturedVar();
  10395. if (VD->isInitCapture())
  10396. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  10397. QualType CaptureType = VD->getType();
  10398. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  10399. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  10400. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  10401. /*EllipsisLoc*/C.isPackExpansion()
  10402. ? C.getEllipsisLoc() : SourceLocation(),
  10403. CaptureType, /*Expr*/ nullptr);
  10404. } else if (C.capturesThis()) {
  10405. LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
  10406. /*Expr*/ nullptr,
  10407. C.getCaptureKind() == LCK_StarThis);
  10408. } else {
  10409. LSI->addVLATypeCapture(C.getLocation(), I->getType());
  10410. }
  10411. ++I;
  10412. }
  10413. }
  10414. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  10415. SkipBodyInfo *SkipBody) {
  10416. // Clear the last template instantiation error context.
  10417. LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
  10418. if (!D)
  10419. return D;
  10420. FunctionDecl *FD = nullptr;
  10421. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  10422. FD = FunTmpl->getTemplatedDecl();
  10423. else
  10424. FD = cast<FunctionDecl>(D);
  10425. // See if this is a redefinition.
  10426. if (!FD->isLateTemplateParsed()) {
  10427. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  10428. // If we're skipping the body, we're done. Don't enter the scope.
  10429. if (SkipBody && SkipBody->ShouldSkip)
  10430. return D;
  10431. }
  10432. // Mark this function as "will have a body eventually". This lets users to
  10433. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  10434. // this function.
  10435. FD->setWillHaveBody();
  10436. // If we are instantiating a generic lambda call operator, push
  10437. // a LambdaScopeInfo onto the function stack. But use the information
  10438. // that's already been calculated (ActOnLambdaExpr) to prime the current
  10439. // LambdaScopeInfo.
  10440. // When the template operator is being specialized, the LambdaScopeInfo,
  10441. // has to be properly restored so that tryCaptureVariable doesn't try
  10442. // and capture any new variables. In addition when calculating potential
  10443. // captures during transformation of nested lambdas, it is necessary to
  10444. // have the LSI properly restored.
  10445. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  10446. assert(ActiveTemplateInstantiations.size() &&
  10447. "There should be an active template instantiation on the stack "
  10448. "when instantiating a generic lambda!");
  10449. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  10450. }
  10451. else
  10452. // Enter a new function scope
  10453. PushFunctionScope();
  10454. // Builtin functions cannot be defined.
  10455. if (unsigned BuiltinID = FD->getBuiltinID()) {
  10456. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  10457. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  10458. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  10459. FD->setInvalidDecl();
  10460. }
  10461. }
  10462. // The return type of a function definition must be complete
  10463. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  10464. QualType ResultType = FD->getReturnType();
  10465. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  10466. !FD->isInvalidDecl() &&
  10467. RequireCompleteType(FD->getLocation(), ResultType,
  10468. diag::err_func_def_incomplete_result))
  10469. FD->setInvalidDecl();
  10470. if (FnBodyScope)
  10471. PushDeclContext(FnBodyScope, FD);
  10472. // Check the validity of our function parameters
  10473. CheckParmsForFunctionDef(FD->parameters(),
  10474. /*CheckParameterNames=*/true);
  10475. // Add non-parameter declarations already in the function to the current
  10476. // scope.
  10477. if (FnBodyScope) {
  10478. for (Decl *NPD : FD->decls()) {
  10479. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  10480. if (!NonParmDecl)
  10481. continue;
  10482. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  10483. "parameters should not be in newly created FD yet");
  10484. // If the decl has a name, make it accessible in the current scope.
  10485. if (NonParmDecl->getDeclName())
  10486. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  10487. // Similarly, dive into enums and fish their constants out, making them
  10488. // accessible in this scope.
  10489. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  10490. for (auto *EI : ED->enumerators())
  10491. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  10492. }
  10493. }
  10494. }
  10495. // Introduce our parameters into the function scope
  10496. for (auto Param : FD->parameters()) {
  10497. Param->setOwningFunction(FD);
  10498. // If this has an identifier, add it to the scope stack.
  10499. if (Param->getIdentifier() && FnBodyScope) {
  10500. CheckShadow(FnBodyScope, Param);
  10501. PushOnScopeChains(Param, FnBodyScope);
  10502. }
  10503. }
  10504. // Ensure that the function's exception specification is instantiated.
  10505. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  10506. ResolveExceptionSpec(D->getLocation(), FPT);
  10507. // dllimport cannot be applied to non-inline function definitions.
  10508. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  10509. !FD->isTemplateInstantiation()) {
  10510. assert(!FD->hasAttr<DLLExportAttr>());
  10511. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  10512. FD->setInvalidDecl();
  10513. return D;
  10514. }
  10515. // We want to attach documentation to original Decl (which might be
  10516. // a function template).
  10517. ActOnDocumentableDecl(D);
  10518. if (getCurLexicalContext()->isObjCContainer() &&
  10519. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  10520. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  10521. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  10522. return D;
  10523. }
  10524. /// \brief Given the set of return statements within a function body,
  10525. /// compute the variables that are subject to the named return value
  10526. /// optimization.
  10527. ///
  10528. /// Each of the variables that is subject to the named return value
  10529. /// optimization will be marked as NRVO variables in the AST, and any
  10530. /// return statement that has a marked NRVO variable as its NRVO candidate can
  10531. /// use the named return value optimization.
  10532. ///
  10533. /// This function applies a very simplistic algorithm for NRVO: if every return
  10534. /// statement in the scope of a variable has the same NRVO candidate, that
  10535. /// candidate is an NRVO variable.
  10536. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  10537. ReturnStmt **Returns = Scope->Returns.data();
  10538. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  10539. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  10540. if (!NRVOCandidate->isNRVOVariable())
  10541. Returns[I]->setNRVOCandidate(nullptr);
  10542. }
  10543. }
  10544. }
  10545. bool Sema::canDelayFunctionBody(const Declarator &D) {
  10546. // We can't delay parsing the body of a constexpr function template (yet).
  10547. if (D.getDeclSpec().isConstexprSpecified())
  10548. return false;
  10549. // We can't delay parsing the body of a function template with a deduced
  10550. // return type (yet).
  10551. if (D.getDeclSpec().hasAutoTypeSpec()) {
  10552. // If the placeholder introduces a non-deduced trailing return type,
  10553. // we can still delay parsing it.
  10554. if (D.getNumTypeObjects()) {
  10555. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  10556. if (Outer.Kind == DeclaratorChunk::Function &&
  10557. Outer.Fun.hasTrailingReturnType()) {
  10558. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  10559. return Ty.isNull() || !Ty->isUndeducedType();
  10560. }
  10561. }
  10562. return false;
  10563. }
  10564. return true;
  10565. }
  10566. bool Sema::canSkipFunctionBody(Decl *D) {
  10567. // We cannot skip the body of a function (or function template) which is
  10568. // constexpr, since we may need to evaluate its body in order to parse the
  10569. // rest of the file.
  10570. // We cannot skip the body of a function with an undeduced return type,
  10571. // because any callers of that function need to know the type.
  10572. if (const FunctionDecl *FD = D->getAsFunction())
  10573. if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
  10574. return false;
  10575. return Consumer.shouldSkipFunctionBody(D);
  10576. }
  10577. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  10578. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
  10579. FD->setHasSkippedBody();
  10580. else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
  10581. MD->setHasSkippedBody();
  10582. return Decl;
  10583. }
  10584. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  10585. return ActOnFinishFunctionBody(D, BodyArg, false);
  10586. }
  10587. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  10588. bool IsInstantiation) {
  10589. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  10590. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  10591. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  10592. if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty())
  10593. CheckCompletedCoroutineBody(FD, Body);
  10594. if (FD) {
  10595. FD->setBody(Body);
  10596. if (getLangOpts().CPlusPlus14) {
  10597. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  10598. FD->getReturnType()->isUndeducedType()) {
  10599. // If the function has a deduced result type but contains no 'return'
  10600. // statements, the result type as written must be exactly 'auto', and
  10601. // the deduced result type is 'void'.
  10602. if (!FD->getReturnType()->getAs<AutoType>()) {
  10603. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  10604. << FD->getReturnType();
  10605. FD->setInvalidDecl();
  10606. } else {
  10607. // Substitute 'void' for the 'auto' in the type.
  10608. TypeLoc ResultType = getReturnTypeLoc(FD);
  10609. Context.adjustDeducedFunctionResultType(
  10610. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  10611. }
  10612. }
  10613. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  10614. // In C++11, we don't use 'auto' deduction rules for lambda call
  10615. // operators because we don't support return type deduction.
  10616. auto *LSI = getCurLambda();
  10617. if (LSI->HasImplicitReturnType) {
  10618. deduceClosureReturnType(*LSI);
  10619. // C++11 [expr.prim.lambda]p4:
  10620. // [...] if there are no return statements in the compound-statement
  10621. // [the deduced type is] the type void
  10622. QualType RetType =
  10623. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  10624. // Update the return type to the deduced type.
  10625. const FunctionProtoType *Proto =
  10626. FD->getType()->getAs<FunctionProtoType>();
  10627. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  10628. Proto->getExtProtoInfo()));
  10629. }
  10630. }
  10631. // The only way to be included in UndefinedButUsed is if there is an
  10632. // ODR use before the definition. Avoid the expensive map lookup if this
  10633. // is the first declaration.
  10634. if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
  10635. if (!FD->isExternallyVisible())
  10636. UndefinedButUsed.erase(FD);
  10637. else if (FD->isInlined() &&
  10638. !LangOpts.GNUInline &&
  10639. (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
  10640. UndefinedButUsed.erase(FD);
  10641. }
  10642. // If the function implicitly returns zero (like 'main') or is naked,
  10643. // don't complain about missing return statements.
  10644. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  10645. WP.disableCheckFallThrough();
  10646. // MSVC permits the use of pure specifier (=0) on function definition,
  10647. // defined at class scope, warn about this non-standard construct.
  10648. if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
  10649. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  10650. if (!FD->isInvalidDecl()) {
  10651. // Don't diagnose unused parameters of defaulted or deleted functions.
  10652. if (!FD->isDeleted() && !FD->isDefaulted())
  10653. DiagnoseUnusedParameters(FD->parameters());
  10654. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  10655. FD->getReturnType(), FD);
  10656. // If this is a structor, we need a vtable.
  10657. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  10658. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  10659. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  10660. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  10661. // Try to apply the named return value optimization. We have to check
  10662. // if we can do this here because lambdas keep return statements around
  10663. // to deduce an implicit return type.
  10664. if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
  10665. !FD->isDependentContext())
  10666. computeNRVO(Body, getCurFunction());
  10667. }
  10668. // GNU warning -Wmissing-prototypes:
  10669. // Warn if a global function is defined without a previous
  10670. // prototype declaration. This warning is issued even if the
  10671. // definition itself provides a prototype. The aim is to detect
  10672. // global functions that fail to be declared in header files.
  10673. const FunctionDecl *PossibleZeroParamPrototype = nullptr;
  10674. if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
  10675. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  10676. if (PossibleZeroParamPrototype) {
  10677. // We found a declaration that is not a prototype,
  10678. // but that could be a zero-parameter prototype
  10679. if (TypeSourceInfo *TI =
  10680. PossibleZeroParamPrototype->getTypeSourceInfo()) {
  10681. TypeLoc TL = TI->getTypeLoc();
  10682. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  10683. Diag(PossibleZeroParamPrototype->getLocation(),
  10684. diag::note_declaration_not_a_prototype)
  10685. << PossibleZeroParamPrototype
  10686. << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
  10687. }
  10688. }
  10689. // GNU warning -Wstrict-prototypes
  10690. // Warn if K&R function is defined without a previous declaration.
  10691. // This warning is issued only if the definition itself does not provide
  10692. // a prototype. Only K&R definitions do not provide a prototype.
  10693. // An empty list in a function declarator that is part of a definition
  10694. // of that function specifies that the function has no parameters
  10695. // (C99 6.7.5.3p14)
  10696. if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
  10697. !LangOpts.CPlusPlus) {
  10698. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  10699. TypeLoc TL = TI->getTypeLoc();
  10700. FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
  10701. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
  10702. }
  10703. }
  10704. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  10705. const CXXMethodDecl *KeyFunction;
  10706. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  10707. MD->isVirtual() &&
  10708. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  10709. MD == KeyFunction->getCanonicalDecl()) {
  10710. // Update the key-function state if necessary for this ABI.
  10711. if (FD->isInlined() &&
  10712. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  10713. Context.setNonKeyFunction(MD);
  10714. // If the newly-chosen key function is already defined, then we
  10715. // need to mark the vtable as used retroactively.
  10716. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  10717. const FunctionDecl *Definition;
  10718. if (KeyFunction && KeyFunction->isDefined(Definition))
  10719. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  10720. } else {
  10721. // We just defined they key function; mark the vtable as used.
  10722. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  10723. }
  10724. }
  10725. }
  10726. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  10727. "Function parsing confused");
  10728. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  10729. assert(MD == getCurMethodDecl() && "Method parsing confused");
  10730. MD->setBody(Body);
  10731. if (!MD->isInvalidDecl()) {
  10732. DiagnoseUnusedParameters(MD->parameters());
  10733. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  10734. MD->getReturnType(), MD);
  10735. if (Body)
  10736. computeNRVO(Body, getCurFunction());
  10737. }
  10738. if (getCurFunction()->ObjCShouldCallSuper) {
  10739. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
  10740. << MD->getSelector().getAsString();
  10741. getCurFunction()->ObjCShouldCallSuper = false;
  10742. }
  10743. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  10744. const ObjCMethodDecl *InitMethod = nullptr;
  10745. bool isDesignated =
  10746. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  10747. assert(isDesignated && InitMethod);
  10748. (void)isDesignated;
  10749. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  10750. auto IFace = MD->getClassInterface();
  10751. if (!IFace)
  10752. return false;
  10753. auto SuperD = IFace->getSuperClass();
  10754. if (!SuperD)
  10755. return false;
  10756. return SuperD->getIdentifier() ==
  10757. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  10758. };
  10759. // Don't issue this warning for unavailable inits or direct subclasses
  10760. // of NSObject.
  10761. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  10762. Diag(MD->getLocation(),
  10763. diag::warn_objc_designated_init_missing_super_call);
  10764. Diag(InitMethod->getLocation(),
  10765. diag::note_objc_designated_init_marked_here);
  10766. }
  10767. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  10768. }
  10769. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  10770. // Don't issue this warning for unavaialable inits.
  10771. if (!MD->isUnavailable())
  10772. Diag(MD->getLocation(),
  10773. diag::warn_objc_secondary_init_missing_init_call);
  10774. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  10775. }
  10776. } else {
  10777. return nullptr;
  10778. }
  10779. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  10780. DiagnoseUnguardedAvailabilityViolations(dcl);
  10781. assert(!getCurFunction()->ObjCShouldCallSuper &&
  10782. "This should only be set for ObjC methods, which should have been "
  10783. "handled in the block above.");
  10784. // Verify and clean out per-function state.
  10785. if (Body && (!FD || !FD->isDefaulted())) {
  10786. // C++ constructors that have function-try-blocks can't have return
  10787. // statements in the handlers of that block. (C++ [except.handle]p14)
  10788. // Verify this.
  10789. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  10790. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  10791. // Verify that gotos and switch cases don't jump into scopes illegally.
  10792. if (getCurFunction()->NeedsScopeChecking() &&
  10793. !PP.isCodeCompletionEnabled())
  10794. DiagnoseInvalidJumps(Body);
  10795. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  10796. if (!Destructor->getParent()->isDependentType())
  10797. CheckDestructor(Destructor);
  10798. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  10799. Destructor->getParent());
  10800. }
  10801. // If any errors have occurred, clear out any temporaries that may have
  10802. // been leftover. This ensures that these temporaries won't be picked up for
  10803. // deletion in some later function.
  10804. if (getDiagnostics().hasErrorOccurred() ||
  10805. getDiagnostics().getSuppressAllDiagnostics()) {
  10806. DiscardCleanupsInEvaluationContext();
  10807. }
  10808. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  10809. !isa<FunctionTemplateDecl>(dcl)) {
  10810. // Since the body is valid, issue any analysis-based warnings that are
  10811. // enabled.
  10812. ActivePolicy = &WP;
  10813. }
  10814. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  10815. (!CheckConstexprFunctionDecl(FD) ||
  10816. !CheckConstexprFunctionBody(FD, Body)))
  10817. FD->setInvalidDecl();
  10818. if (FD && FD->hasAttr<NakedAttr>()) {
  10819. for (const Stmt *S : Body->children()) {
  10820. // Allow local register variables without initializer as they don't
  10821. // require prologue.
  10822. bool RegisterVariables = false;
  10823. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  10824. for (const auto *Decl : DS->decls()) {
  10825. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  10826. RegisterVariables =
  10827. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  10828. if (!RegisterVariables)
  10829. break;
  10830. }
  10831. }
  10832. }
  10833. if (RegisterVariables)
  10834. continue;
  10835. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  10836. Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
  10837. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  10838. FD->setInvalidDecl();
  10839. break;
  10840. }
  10841. }
  10842. }
  10843. assert(ExprCleanupObjects.size() ==
  10844. ExprEvalContexts.back().NumCleanupObjects &&
  10845. "Leftover temporaries in function");
  10846. assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
  10847. assert(MaybeODRUseExprs.empty() &&
  10848. "Leftover expressions for odr-use checking");
  10849. }
  10850. if (!IsInstantiation)
  10851. PopDeclContext();
  10852. PopFunctionScopeInfo(ActivePolicy, dcl);
  10853. // If any errors have occurred, clear out any temporaries that may have
  10854. // been leftover. This ensures that these temporaries won't be picked up for
  10855. // deletion in some later function.
  10856. if (getDiagnostics().hasErrorOccurred()) {
  10857. DiscardCleanupsInEvaluationContext();
  10858. }
  10859. return dcl;
  10860. }
  10861. /// When we finish delayed parsing of an attribute, we must attach it to the
  10862. /// relevant Decl.
  10863. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  10864. ParsedAttributes &Attrs) {
  10865. // Always attach attributes to the underlying decl.
  10866. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  10867. D = TD->getTemplatedDecl();
  10868. ProcessDeclAttributeList(S, D, Attrs.getList());
  10869. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  10870. if (Method->isStatic())
  10871. checkThisInStaticMemberFunctionAttributes(Method);
  10872. }
  10873. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  10874. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  10875. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  10876. IdentifierInfo &II, Scope *S) {
  10877. // Before we produce a declaration for an implicitly defined
  10878. // function, see whether there was a locally-scoped declaration of
  10879. // this name as a function or variable. If so, use that
  10880. // (non-visible) declaration, and complain about it.
  10881. if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
  10882. Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
  10883. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  10884. return ExternCPrev;
  10885. }
  10886. // Extension in C99. Legal in C90, but warn about it.
  10887. unsigned diag_id;
  10888. if (II.getName().startswith("__builtin_"))
  10889. diag_id = diag::warn_builtin_unknown;
  10890. else if (getLangOpts().C99)
  10891. diag_id = diag::ext_implicit_function_decl;
  10892. else
  10893. diag_id = diag::warn_implicit_function_decl;
  10894. Diag(Loc, diag_id) << &II;
  10895. // Because typo correction is expensive, only do it if the implicit
  10896. // function declaration is going to be treated as an error.
  10897. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  10898. TypoCorrection Corrected;
  10899. if (S &&
  10900. (Corrected = CorrectTypo(
  10901. DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
  10902. llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
  10903. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  10904. /*ErrorRecovery*/false);
  10905. }
  10906. // Set a Declarator for the implicit definition: int foo();
  10907. const char *Dummy;
  10908. AttributeFactory attrFactory;
  10909. DeclSpec DS(attrFactory);
  10910. unsigned DiagID;
  10911. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  10912. Context.getPrintingPolicy());
  10913. (void)Error; // Silence warning.
  10914. assert(!Error && "Error setting up implicit decl!");
  10915. SourceLocation NoLoc;
  10916. Declarator D(DS, Declarator::BlockContext);
  10917. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  10918. /*IsAmbiguous=*/false,
  10919. /*LParenLoc=*/NoLoc,
  10920. /*Params=*/nullptr,
  10921. /*NumParams=*/0,
  10922. /*EllipsisLoc=*/NoLoc,
  10923. /*RParenLoc=*/NoLoc,
  10924. /*TypeQuals=*/0,
  10925. /*RefQualifierIsLvalueRef=*/true,
  10926. /*RefQualifierLoc=*/NoLoc,
  10927. /*ConstQualifierLoc=*/NoLoc,
  10928. /*VolatileQualifierLoc=*/NoLoc,
  10929. /*RestrictQualifierLoc=*/NoLoc,
  10930. /*MutableLoc=*/NoLoc,
  10931. EST_None,
  10932. /*ESpecRange=*/SourceRange(),
  10933. /*Exceptions=*/nullptr,
  10934. /*ExceptionRanges=*/nullptr,
  10935. /*NumExceptions=*/0,
  10936. /*NoexceptExpr=*/nullptr,
  10937. /*ExceptionSpecTokens=*/nullptr,
  10938. /*DeclsInPrototype=*/None,
  10939. Loc, Loc, D),
  10940. DS.getAttributes(),
  10941. SourceLocation());
  10942. D.SetIdentifier(&II, Loc);
  10943. // Insert this function into translation-unit scope.
  10944. DeclContext *PrevDC = CurContext;
  10945. CurContext = Context.getTranslationUnitDecl();
  10946. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
  10947. FD->setImplicit();
  10948. CurContext = PrevDC;
  10949. AddKnownFunctionAttributes(FD);
  10950. return FD;
  10951. }
  10952. /// \brief Adds any function attributes that we know a priori based on
  10953. /// the declaration of this function.
  10954. ///
  10955. /// These attributes can apply both to implicitly-declared builtins
  10956. /// (like __builtin___printf_chk) or to library-declared functions
  10957. /// like NSLog or printf.
  10958. ///
  10959. /// We need to check for duplicate attributes both here and where user-written
  10960. /// attributes are applied to declarations.
  10961. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  10962. if (FD->isInvalidDecl())
  10963. return;
  10964. // If this is a built-in function, map its builtin attributes to
  10965. // actual attributes.
  10966. if (unsigned BuiltinID = FD->getBuiltinID()) {
  10967. // Handle printf-formatting attributes.
  10968. unsigned FormatIdx;
  10969. bool HasVAListArg;
  10970. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  10971. if (!FD->hasAttr<FormatAttr>()) {
  10972. const char *fmt = "printf";
  10973. unsigned int NumParams = FD->getNumParams();
  10974. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  10975. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  10976. fmt = "NSString";
  10977. FD->addAttr(FormatAttr::CreateImplicit(Context,
  10978. &Context.Idents.get(fmt),
  10979. FormatIdx+1,
  10980. HasVAListArg ? 0 : FormatIdx+2,
  10981. FD->getLocation()));
  10982. }
  10983. }
  10984. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  10985. HasVAListArg)) {
  10986. if (!FD->hasAttr<FormatAttr>())
  10987. FD->addAttr(FormatAttr::CreateImplicit(Context,
  10988. &Context.Idents.get("scanf"),
  10989. FormatIdx+1,
  10990. HasVAListArg ? 0 : FormatIdx+2,
  10991. FD->getLocation()));
  10992. }
  10993. // Mark const if we don't care about errno and that is the only
  10994. // thing preventing the function from being const. This allows
  10995. // IRgen to use LLVM intrinsics for such functions.
  10996. if (!getLangOpts().MathErrno &&
  10997. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
  10998. if (!FD->hasAttr<ConstAttr>())
  10999. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  11000. }
  11001. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  11002. !FD->hasAttr<ReturnsTwiceAttr>())
  11003. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  11004. FD->getLocation()));
  11005. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  11006. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  11007. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  11008. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  11009. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  11010. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  11011. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  11012. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  11013. // Add the appropriate attribute, depending on the CUDA compilation mode
  11014. // and which target the builtin belongs to. For example, during host
  11015. // compilation, aux builtins are __device__, while the rest are __host__.
  11016. if (getLangOpts().CUDAIsDevice !=
  11017. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  11018. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  11019. else
  11020. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  11021. }
  11022. }
  11023. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  11024. // throw, add an implicit nothrow attribute to any extern "C" function we come
  11025. // across.
  11026. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  11027. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  11028. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  11029. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  11030. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  11031. }
  11032. IdentifierInfo *Name = FD->getIdentifier();
  11033. if (!Name)
  11034. return;
  11035. if ((!getLangOpts().CPlusPlus &&
  11036. FD->getDeclContext()->isTranslationUnit()) ||
  11037. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  11038. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  11039. LinkageSpecDecl::lang_c)) {
  11040. // Okay: this could be a libc/libm/Objective-C function we know
  11041. // about.
  11042. } else
  11043. return;
  11044. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  11045. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  11046. // target-specific builtins, perhaps?
  11047. if (!FD->hasAttr<FormatAttr>())
  11048. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11049. &Context.Idents.get("printf"), 2,
  11050. Name->isStr("vasprintf") ? 0 : 3,
  11051. FD->getLocation()));
  11052. }
  11053. if (Name->isStr("__CFStringMakeConstantString")) {
  11054. // We already have a __builtin___CFStringMakeConstantString,
  11055. // but builds that use -fno-constant-cfstrings don't go through that.
  11056. if (!FD->hasAttr<FormatArgAttr>())
  11057. FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
  11058. FD->getLocation()));
  11059. }
  11060. }
  11061. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  11062. TypeSourceInfo *TInfo) {
  11063. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  11064. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  11065. if (!TInfo) {
  11066. assert(D.isInvalidType() && "no declarator info for valid type");
  11067. TInfo = Context.getTrivialTypeSourceInfo(T);
  11068. }
  11069. // Scope manipulation handled by caller.
  11070. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  11071. D.getLocStart(),
  11072. D.getIdentifierLoc(),
  11073. D.getIdentifier(),
  11074. TInfo);
  11075. // Bail out immediately if we have an invalid declaration.
  11076. if (D.isInvalidType()) {
  11077. NewTD->setInvalidDecl();
  11078. return NewTD;
  11079. }
  11080. if (D.getDeclSpec().isModulePrivateSpecified()) {
  11081. if (CurContext->isFunctionOrMethod())
  11082. Diag(NewTD->getLocation(), diag::err_module_private_local)
  11083. << 2 << NewTD->getDeclName()
  11084. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  11085. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  11086. else
  11087. NewTD->setModulePrivate();
  11088. }
  11089. // C++ [dcl.typedef]p8:
  11090. // If the typedef declaration defines an unnamed class (or
  11091. // enum), the first typedef-name declared by the declaration
  11092. // to be that class type (or enum type) is used to denote the
  11093. // class type (or enum type) for linkage purposes only.
  11094. // We need to check whether the type was declared in the declaration.
  11095. switch (D.getDeclSpec().getTypeSpecType()) {
  11096. case TST_enum:
  11097. case TST_struct:
  11098. case TST_interface:
  11099. case TST_union:
  11100. case TST_class: {
  11101. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  11102. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  11103. break;
  11104. }
  11105. default:
  11106. break;
  11107. }
  11108. return NewTD;
  11109. }
  11110. /// \brief Check that this is a valid underlying type for an enum declaration.
  11111. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  11112. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  11113. QualType T = TI->getType();
  11114. if (T->isDependentType())
  11115. return false;
  11116. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  11117. if (BT->isInteger())
  11118. return false;
  11119. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  11120. return true;
  11121. }
  11122. /// Check whether this is a valid redeclaration of a previous enumeration.
  11123. /// \return true if the redeclaration was invalid.
  11124. bool Sema::CheckEnumRedeclaration(
  11125. SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
  11126. bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
  11127. bool IsFixed = !EnumUnderlyingTy.isNull();
  11128. if (IsScoped != Prev->isScoped()) {
  11129. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  11130. << Prev->isScoped();
  11131. Diag(Prev->getLocation(), diag::note_previous_declaration);
  11132. return true;
  11133. }
  11134. if (IsFixed && Prev->isFixed()) {
  11135. if (!EnumUnderlyingTy->isDependentType() &&
  11136. !Prev->getIntegerType()->isDependentType() &&
  11137. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  11138. Prev->getIntegerType())) {
  11139. // TODO: Highlight the underlying type of the redeclaration.
  11140. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  11141. << EnumUnderlyingTy << Prev->getIntegerType();
  11142. Diag(Prev->getLocation(), diag::note_previous_declaration)
  11143. << Prev->getIntegerTypeRange();
  11144. return true;
  11145. }
  11146. } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
  11147. ;
  11148. } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
  11149. ;
  11150. } else if (IsFixed != Prev->isFixed()) {
  11151. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  11152. << Prev->isFixed();
  11153. Diag(Prev->getLocation(), diag::note_previous_declaration);
  11154. return true;
  11155. }
  11156. return false;
  11157. }
  11158. /// \brief Get diagnostic %select index for tag kind for
  11159. /// redeclaration diagnostic message.
  11160. /// WARNING: Indexes apply to particular diagnostics only!
  11161. ///
  11162. /// \returns diagnostic %select index.
  11163. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  11164. switch (Tag) {
  11165. case TTK_Struct: return 0;
  11166. case TTK_Interface: return 1;
  11167. case TTK_Class: return 2;
  11168. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  11169. }
  11170. }
  11171. /// \brief Determine if tag kind is a class-key compatible with
  11172. /// class for redeclaration (class, struct, or __interface).
  11173. ///
  11174. /// \returns true iff the tag kind is compatible.
  11175. static bool isClassCompatTagKind(TagTypeKind Tag)
  11176. {
  11177. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  11178. }
  11179. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  11180. TagTypeKind TTK) {
  11181. if (isa<TypedefDecl>(PrevDecl))
  11182. return NTK_Typedef;
  11183. else if (isa<TypeAliasDecl>(PrevDecl))
  11184. return NTK_TypeAlias;
  11185. else if (isa<ClassTemplateDecl>(PrevDecl))
  11186. return NTK_Template;
  11187. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  11188. return NTK_TypeAliasTemplate;
  11189. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  11190. return NTK_TemplateTemplateArgument;
  11191. switch (TTK) {
  11192. case TTK_Struct:
  11193. case TTK_Interface:
  11194. case TTK_Class:
  11195. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  11196. case TTK_Union:
  11197. return NTK_NonUnion;
  11198. case TTK_Enum:
  11199. return NTK_NonEnum;
  11200. }
  11201. llvm_unreachable("invalid TTK");
  11202. }
  11203. /// \brief Determine whether a tag with a given kind is acceptable
  11204. /// as a redeclaration of the given tag declaration.
  11205. ///
  11206. /// \returns true if the new tag kind is acceptable, false otherwise.
  11207. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  11208. TagTypeKind NewTag, bool isDefinition,
  11209. SourceLocation NewTagLoc,
  11210. const IdentifierInfo *Name) {
  11211. // C++ [dcl.type.elab]p3:
  11212. // The class-key or enum keyword present in the
  11213. // elaborated-type-specifier shall agree in kind with the
  11214. // declaration to which the name in the elaborated-type-specifier
  11215. // refers. This rule also applies to the form of
  11216. // elaborated-type-specifier that declares a class-name or
  11217. // friend class since it can be construed as referring to the
  11218. // definition of the class. Thus, in any
  11219. // elaborated-type-specifier, the enum keyword shall be used to
  11220. // refer to an enumeration (7.2), the union class-key shall be
  11221. // used to refer to a union (clause 9), and either the class or
  11222. // struct class-key shall be used to refer to a class (clause 9)
  11223. // declared using the class or struct class-key.
  11224. TagTypeKind OldTag = Previous->getTagKind();
  11225. if (!isDefinition || !isClassCompatTagKind(NewTag))
  11226. if (OldTag == NewTag)
  11227. return true;
  11228. if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
  11229. // Warn about the struct/class tag mismatch.
  11230. bool isTemplate = false;
  11231. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  11232. isTemplate = Record->getDescribedClassTemplate();
  11233. if (!ActiveTemplateInstantiations.empty()) {
  11234. // In a template instantiation, do not offer fix-its for tag mismatches
  11235. // since they usually mess up the template instead of fixing the problem.
  11236. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  11237. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11238. << getRedeclDiagFromTagKind(OldTag);
  11239. return true;
  11240. }
  11241. if (isDefinition) {
  11242. // On definitions, check previous tags and issue a fix-it for each
  11243. // one that doesn't match the current tag.
  11244. if (Previous->getDefinition()) {
  11245. // Don't suggest fix-its for redefinitions.
  11246. return true;
  11247. }
  11248. bool previousMismatch = false;
  11249. for (auto I : Previous->redecls()) {
  11250. if (I->getTagKind() != NewTag) {
  11251. if (!previousMismatch) {
  11252. previousMismatch = true;
  11253. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  11254. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11255. << getRedeclDiagFromTagKind(I->getTagKind());
  11256. }
  11257. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  11258. << getRedeclDiagFromTagKind(NewTag)
  11259. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  11260. TypeWithKeyword::getTagTypeKindName(NewTag));
  11261. }
  11262. }
  11263. return true;
  11264. }
  11265. // Check for a previous definition. If current tag and definition
  11266. // are same type, do nothing. If no definition, but disagree with
  11267. // with previous tag type, give a warning, but no fix-it.
  11268. const TagDecl *Redecl = Previous->getDefinition() ?
  11269. Previous->getDefinition() : Previous;
  11270. if (Redecl->getTagKind() == NewTag) {
  11271. return true;
  11272. }
  11273. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  11274. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11275. << getRedeclDiagFromTagKind(OldTag);
  11276. Diag(Redecl->getLocation(), diag::note_previous_use);
  11277. // If there is a previous definition, suggest a fix-it.
  11278. if (Previous->getDefinition()) {
  11279. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  11280. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  11281. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  11282. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  11283. }
  11284. return true;
  11285. }
  11286. return false;
  11287. }
  11288. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  11289. /// from an outer enclosing namespace or file scope inside a friend declaration.
  11290. /// This should provide the commented out code in the following snippet:
  11291. /// namespace N {
  11292. /// struct X;
  11293. /// namespace M {
  11294. /// struct Y { friend struct /*N::*/ X; };
  11295. /// }
  11296. /// }
  11297. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  11298. SourceLocation NameLoc) {
  11299. // While the decl is in a namespace, do repeated lookup of that name and see
  11300. // if we get the same namespace back. If we do not, continue until
  11301. // translation unit scope, at which point we have a fully qualified NNS.
  11302. SmallVector<IdentifierInfo *, 4> Namespaces;
  11303. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  11304. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  11305. // This tag should be declared in a namespace, which can only be enclosed by
  11306. // other namespaces. Bail if there's an anonymous namespace in the chain.
  11307. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  11308. if (!Namespace || Namespace->isAnonymousNamespace())
  11309. return FixItHint();
  11310. IdentifierInfo *II = Namespace->getIdentifier();
  11311. Namespaces.push_back(II);
  11312. NamedDecl *Lookup = SemaRef.LookupSingleName(
  11313. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  11314. if (Lookup == Namespace)
  11315. break;
  11316. }
  11317. // Once we have all the namespaces, reverse them to go outermost first, and
  11318. // build an NNS.
  11319. SmallString<64> Insertion;
  11320. llvm::raw_svector_ostream OS(Insertion);
  11321. if (DC->isTranslationUnit())
  11322. OS << "::";
  11323. std::reverse(Namespaces.begin(), Namespaces.end());
  11324. for (auto *II : Namespaces)
  11325. OS << II->getName() << "::";
  11326. return FixItHint::CreateInsertion(NameLoc, Insertion);
  11327. }
  11328. /// \brief Determine whether a tag originally declared in context \p OldDC can
  11329. /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
  11330. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  11331. /// using-declaration).
  11332. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  11333. DeclContext *NewDC) {
  11334. OldDC = OldDC->getRedeclContext();
  11335. NewDC = NewDC->getRedeclContext();
  11336. if (OldDC->Equals(NewDC))
  11337. return true;
  11338. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  11339. // encloses the other).
  11340. if (S.getLangOpts().MSVCCompat &&
  11341. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  11342. return true;
  11343. return false;
  11344. }
  11345. /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
  11346. /// former case, Name will be non-null. In the later case, Name will be null.
  11347. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  11348. /// reference/declaration/definition of a tag.
  11349. ///
  11350. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  11351. /// trailing-type-specifier) other than one in an alias-declaration.
  11352. ///
  11353. /// \param SkipBody If non-null, will be set to indicate if the caller should
  11354. /// skip the definition of this tag and treat it as if it were a declaration.
  11355. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  11356. SourceLocation KWLoc, CXXScopeSpec &SS,
  11357. IdentifierInfo *Name, SourceLocation NameLoc,
  11358. AttributeList *Attr, AccessSpecifier AS,
  11359. SourceLocation ModulePrivateLoc,
  11360. MultiTemplateParamsArg TemplateParameterLists,
  11361. bool &OwnedDecl, bool &IsDependent,
  11362. SourceLocation ScopedEnumKWLoc,
  11363. bool ScopedEnumUsesClassTag,
  11364. TypeResult UnderlyingType,
  11365. bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
  11366. // If this is not a definition, it must have a name.
  11367. IdentifierInfo *OrigName = Name;
  11368. assert((Name != nullptr || TUK == TUK_Definition) &&
  11369. "Nameless record must be a definition!");
  11370. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  11371. OwnedDecl = false;
  11372. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  11373. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  11374. // FIXME: Check member specializations more carefully.
  11375. bool isMemberSpecialization = false;
  11376. bool Invalid = false;
  11377. // We only need to do this matching if we have template parameters
  11378. // or a scope specifier, which also conveniently avoids this work
  11379. // for non-C++ cases.
  11380. if (TemplateParameterLists.size() > 0 ||
  11381. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  11382. if (TemplateParameterList *TemplateParams =
  11383. MatchTemplateParametersToScopeSpecifier(
  11384. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  11385. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  11386. if (Kind == TTK_Enum) {
  11387. Diag(KWLoc, diag::err_enum_template);
  11388. return nullptr;
  11389. }
  11390. if (TemplateParams->size() > 0) {
  11391. // This is a declaration or definition of a class template (which may
  11392. // be a member of another template).
  11393. if (Invalid)
  11394. return nullptr;
  11395. OwnedDecl = false;
  11396. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  11397. SS, Name, NameLoc, Attr,
  11398. TemplateParams, AS,
  11399. ModulePrivateLoc,
  11400. /*FriendLoc*/SourceLocation(),
  11401. TemplateParameterLists.size()-1,
  11402. TemplateParameterLists.data(),
  11403. SkipBody);
  11404. return Result.get();
  11405. } else {
  11406. // The "template<>" header is extraneous.
  11407. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  11408. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  11409. isMemberSpecialization = true;
  11410. }
  11411. }
  11412. }
  11413. // Figure out the underlying type if this a enum declaration. We need to do
  11414. // this early, because it's needed to detect if this is an incompatible
  11415. // redeclaration.
  11416. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  11417. bool EnumUnderlyingIsImplicit = false;
  11418. if (Kind == TTK_Enum) {
  11419. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
  11420. // No underlying type explicitly specified, or we failed to parse the
  11421. // type, default to int.
  11422. EnumUnderlying = Context.IntTy.getTypePtr();
  11423. else if (UnderlyingType.get()) {
  11424. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  11425. // integral type; any cv-qualification is ignored.
  11426. TypeSourceInfo *TI = nullptr;
  11427. GetTypeFromParser(UnderlyingType.get(), &TI);
  11428. EnumUnderlying = TI;
  11429. if (CheckEnumUnderlyingType(TI))
  11430. // Recover by falling back to int.
  11431. EnumUnderlying = Context.IntTy.getTypePtr();
  11432. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  11433. UPPC_FixedUnderlyingType))
  11434. EnumUnderlying = Context.IntTy.getTypePtr();
  11435. } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  11436. if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
  11437. // Microsoft enums are always of int type.
  11438. EnumUnderlying = Context.IntTy.getTypePtr();
  11439. EnumUnderlyingIsImplicit = true;
  11440. }
  11441. }
  11442. }
  11443. DeclContext *SearchDC = CurContext;
  11444. DeclContext *DC = CurContext;
  11445. bool isStdBadAlloc = false;
  11446. bool isStdAlignValT = false;
  11447. RedeclarationKind Redecl = ForRedeclaration;
  11448. if (TUK == TUK_Friend || TUK == TUK_Reference)
  11449. Redecl = NotForRedeclaration;
  11450. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  11451. if (Name && SS.isNotEmpty()) {
  11452. // We have a nested-name tag ('struct foo::bar').
  11453. // Check for invalid 'foo::'.
  11454. if (SS.isInvalid()) {
  11455. Name = nullptr;
  11456. goto CreateNewDecl;
  11457. }
  11458. // If this is a friend or a reference to a class in a dependent
  11459. // context, don't try to make a decl for it.
  11460. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  11461. DC = computeDeclContext(SS, false);
  11462. if (!DC) {
  11463. IsDependent = true;
  11464. return nullptr;
  11465. }
  11466. } else {
  11467. DC = computeDeclContext(SS, true);
  11468. if (!DC) {
  11469. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  11470. << SS.getRange();
  11471. return nullptr;
  11472. }
  11473. }
  11474. if (RequireCompleteDeclContext(SS, DC))
  11475. return nullptr;
  11476. SearchDC = DC;
  11477. // Look-up name inside 'foo::'.
  11478. LookupQualifiedName(Previous, DC);
  11479. if (Previous.isAmbiguous())
  11480. return nullptr;
  11481. if (Previous.empty()) {
  11482. // Name lookup did not find anything. However, if the
  11483. // nested-name-specifier refers to the current instantiation,
  11484. // and that current instantiation has any dependent base
  11485. // classes, we might find something at instantiation time: treat
  11486. // this as a dependent elaborated-type-specifier.
  11487. // But this only makes any sense for reference-like lookups.
  11488. if (Previous.wasNotFoundInCurrentInstantiation() &&
  11489. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  11490. IsDependent = true;
  11491. return nullptr;
  11492. }
  11493. // A tag 'foo::bar' must already exist.
  11494. Diag(NameLoc, diag::err_not_tag_in_scope)
  11495. << Kind << Name << DC << SS.getRange();
  11496. Name = nullptr;
  11497. Invalid = true;
  11498. goto CreateNewDecl;
  11499. }
  11500. } else if (Name) {
  11501. // C++14 [class.mem]p14:
  11502. // If T is the name of a class, then each of the following shall have a
  11503. // name different from T:
  11504. // -- every member of class T that is itself a type
  11505. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  11506. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  11507. return nullptr;
  11508. // If this is a named struct, check to see if there was a previous forward
  11509. // declaration or definition.
  11510. // FIXME: We're looking into outer scopes here, even when we
  11511. // shouldn't be. Doing so can result in ambiguities that we
  11512. // shouldn't be diagnosing.
  11513. LookupName(Previous, S);
  11514. // When declaring or defining a tag, ignore ambiguities introduced
  11515. // by types using'ed into this scope.
  11516. if (Previous.isAmbiguous() &&
  11517. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  11518. LookupResult::Filter F = Previous.makeFilter();
  11519. while (F.hasNext()) {
  11520. NamedDecl *ND = F.next();
  11521. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  11522. SearchDC->getRedeclContext()))
  11523. F.erase();
  11524. }
  11525. F.done();
  11526. }
  11527. // C++11 [namespace.memdef]p3:
  11528. // If the name in a friend declaration is neither qualified nor
  11529. // a template-id and the declaration is a function or an
  11530. // elaborated-type-specifier, the lookup to determine whether
  11531. // the entity has been previously declared shall not consider
  11532. // any scopes outside the innermost enclosing namespace.
  11533. //
  11534. // MSVC doesn't implement the above rule for types, so a friend tag
  11535. // declaration may be a redeclaration of a type declared in an enclosing
  11536. // scope. They do implement this rule for friend functions.
  11537. //
  11538. // Does it matter that this should be by scope instead of by
  11539. // semantic context?
  11540. if (!Previous.empty() && TUK == TUK_Friend) {
  11541. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  11542. LookupResult::Filter F = Previous.makeFilter();
  11543. bool FriendSawTagOutsideEnclosingNamespace = false;
  11544. while (F.hasNext()) {
  11545. NamedDecl *ND = F.next();
  11546. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  11547. if (DC->isFileContext() &&
  11548. !EnclosingNS->Encloses(ND->getDeclContext())) {
  11549. if (getLangOpts().MSVCCompat)
  11550. FriendSawTagOutsideEnclosingNamespace = true;
  11551. else
  11552. F.erase();
  11553. }
  11554. }
  11555. F.done();
  11556. // Diagnose this MSVC extension in the easy case where lookup would have
  11557. // unambiguously found something outside the enclosing namespace.
  11558. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  11559. NamedDecl *ND = Previous.getFoundDecl();
  11560. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  11561. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  11562. }
  11563. }
  11564. // Note: there used to be some attempt at recovery here.
  11565. if (Previous.isAmbiguous())
  11566. return nullptr;
  11567. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  11568. // FIXME: This makes sure that we ignore the contexts associated
  11569. // with C structs, unions, and enums when looking for a matching
  11570. // tag declaration or definition. See the similar lookup tweak
  11571. // in Sema::LookupName; is there a better way to deal with this?
  11572. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  11573. SearchDC = SearchDC->getParent();
  11574. }
  11575. }
  11576. if (Previous.isSingleResult() &&
  11577. Previous.getFoundDecl()->isTemplateParameter()) {
  11578. // Maybe we will complain about the shadowed template parameter.
  11579. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  11580. // Just pretend that we didn't see the previous declaration.
  11581. Previous.clear();
  11582. }
  11583. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  11584. DC->Equals(getStdNamespace())) {
  11585. if (Name->isStr("bad_alloc")) {
  11586. // This is a declaration of or a reference to "std::bad_alloc".
  11587. isStdBadAlloc = true;
  11588. // If std::bad_alloc has been implicitly declared (but made invisible to
  11589. // name lookup), fill in this implicit declaration as the previous
  11590. // declaration, so that the declarations get chained appropriately.
  11591. if (Previous.empty() && StdBadAlloc)
  11592. Previous.addDecl(getStdBadAlloc());
  11593. } else if (Name->isStr("align_val_t")) {
  11594. isStdAlignValT = true;
  11595. if (Previous.empty() && StdAlignValT)
  11596. Previous.addDecl(getStdAlignValT());
  11597. }
  11598. }
  11599. // If we didn't find a previous declaration, and this is a reference
  11600. // (or friend reference), move to the correct scope. In C++, we
  11601. // also need to do a redeclaration lookup there, just in case
  11602. // there's a shadow friend decl.
  11603. if (Name && Previous.empty() &&
  11604. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  11605. if (Invalid) goto CreateNewDecl;
  11606. assert(SS.isEmpty());
  11607. if (TUK == TUK_Reference) {
  11608. // C++ [basic.scope.pdecl]p5:
  11609. // -- for an elaborated-type-specifier of the form
  11610. //
  11611. // class-key identifier
  11612. //
  11613. // if the elaborated-type-specifier is used in the
  11614. // decl-specifier-seq or parameter-declaration-clause of a
  11615. // function defined in namespace scope, the identifier is
  11616. // declared as a class-name in the namespace that contains
  11617. // the declaration; otherwise, except as a friend
  11618. // declaration, the identifier is declared in the smallest
  11619. // non-class, non-function-prototype scope that contains the
  11620. // declaration.
  11621. //
  11622. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  11623. // C structs and unions.
  11624. //
  11625. // It is an error in C++ to declare (rather than define) an enum
  11626. // type, including via an elaborated type specifier. We'll
  11627. // diagnose that later; for now, declare the enum in the same
  11628. // scope as we would have picked for any other tag type.
  11629. //
  11630. // GNU C also supports this behavior as part of its incomplete
  11631. // enum types extension, while GNU C++ does not.
  11632. //
  11633. // Find the context where we'll be declaring the tag.
  11634. // FIXME: We would like to maintain the current DeclContext as the
  11635. // lexical context,
  11636. SearchDC = getTagInjectionContext(SearchDC);
  11637. // Find the scope where we'll be declaring the tag.
  11638. S = getTagInjectionScope(S, getLangOpts());
  11639. } else {
  11640. assert(TUK == TUK_Friend);
  11641. // C++ [namespace.memdef]p3:
  11642. // If a friend declaration in a non-local class first declares a
  11643. // class or function, the friend class or function is a member of
  11644. // the innermost enclosing namespace.
  11645. SearchDC = SearchDC->getEnclosingNamespaceContext();
  11646. }
  11647. // In C++, we need to do a redeclaration lookup to properly
  11648. // diagnose some problems.
  11649. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  11650. // hidden declaration so that we don't get ambiguity errors when using a
  11651. // type declared by an elaborated-type-specifier. In C that is not correct
  11652. // and we should instead merge compatible types found by lookup.
  11653. if (getLangOpts().CPlusPlus) {
  11654. Previous.setRedeclarationKind(ForRedeclaration);
  11655. LookupQualifiedName(Previous, SearchDC);
  11656. } else {
  11657. Previous.setRedeclarationKind(ForRedeclaration);
  11658. LookupName(Previous, S);
  11659. }
  11660. }
  11661. // If we have a known previous declaration to use, then use it.
  11662. if (Previous.empty() && SkipBody && SkipBody->Previous)
  11663. Previous.addDecl(SkipBody->Previous);
  11664. if (!Previous.empty()) {
  11665. NamedDecl *PrevDecl = Previous.getFoundDecl();
  11666. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  11667. // It's okay to have a tag decl in the same scope as a typedef
  11668. // which hides a tag decl in the same scope. Finding this
  11669. // insanity with a redeclaration lookup can only actually happen
  11670. // in C++.
  11671. //
  11672. // This is also okay for elaborated-type-specifiers, which is
  11673. // technically forbidden by the current standard but which is
  11674. // okay according to the likely resolution of an open issue;
  11675. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  11676. if (getLangOpts().CPlusPlus) {
  11677. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  11678. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  11679. TagDecl *Tag = TT->getDecl();
  11680. if (Tag->getDeclName() == Name &&
  11681. Tag->getDeclContext()->getRedeclContext()
  11682. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  11683. PrevDecl = Tag;
  11684. Previous.clear();
  11685. Previous.addDecl(Tag);
  11686. Previous.resolveKind();
  11687. }
  11688. }
  11689. }
  11690. }
  11691. // If this is a redeclaration of a using shadow declaration, it must
  11692. // declare a tag in the same context. In MSVC mode, we allow a
  11693. // redefinition if either context is within the other.
  11694. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  11695. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  11696. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  11697. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  11698. !(OldTag && isAcceptableTagRedeclContext(
  11699. *this, OldTag->getDeclContext(), SearchDC))) {
  11700. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  11701. Diag(Shadow->getTargetDecl()->getLocation(),
  11702. diag::note_using_decl_target);
  11703. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  11704. << 0;
  11705. // Recover by ignoring the old declaration.
  11706. Previous.clear();
  11707. goto CreateNewDecl;
  11708. }
  11709. }
  11710. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  11711. // If this is a use of a previous tag, or if the tag is already declared
  11712. // in the same scope (so that the definition/declaration completes or
  11713. // rementions the tag), reuse the decl.
  11714. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  11715. isDeclInScope(DirectPrevDecl, SearchDC, S,
  11716. SS.isNotEmpty() || isMemberSpecialization)) {
  11717. // Make sure that this wasn't declared as an enum and now used as a
  11718. // struct or something similar.
  11719. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  11720. TUK == TUK_Definition, KWLoc,
  11721. Name)) {
  11722. bool SafeToContinue
  11723. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  11724. Kind != TTK_Enum);
  11725. if (SafeToContinue)
  11726. Diag(KWLoc, diag::err_use_with_wrong_tag)
  11727. << Name
  11728. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  11729. PrevTagDecl->getKindName());
  11730. else
  11731. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  11732. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  11733. if (SafeToContinue)
  11734. Kind = PrevTagDecl->getTagKind();
  11735. else {
  11736. // Recover by making this an anonymous redefinition.
  11737. Name = nullptr;
  11738. Previous.clear();
  11739. Invalid = true;
  11740. }
  11741. }
  11742. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  11743. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  11744. // If this is an elaborated-type-specifier for a scoped enumeration,
  11745. // the 'class' keyword is not necessary and not permitted.
  11746. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  11747. if (ScopedEnum)
  11748. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  11749. << PrevEnum->isScoped()
  11750. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  11751. return PrevTagDecl;
  11752. }
  11753. QualType EnumUnderlyingTy;
  11754. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  11755. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  11756. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  11757. EnumUnderlyingTy = QualType(T, 0);
  11758. // All conflicts with previous declarations are recovered by
  11759. // returning the previous declaration, unless this is a definition,
  11760. // in which case we want the caller to bail out.
  11761. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  11762. ScopedEnum, EnumUnderlyingTy,
  11763. EnumUnderlyingIsImplicit, PrevEnum))
  11764. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  11765. }
  11766. // C++11 [class.mem]p1:
  11767. // A member shall not be declared twice in the member-specification,
  11768. // except that a nested class or member class template can be declared
  11769. // and then later defined.
  11770. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  11771. S->isDeclScope(PrevDecl)) {
  11772. Diag(NameLoc, diag::ext_member_redeclared);
  11773. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  11774. }
  11775. if (!Invalid) {
  11776. // If this is a use, just return the declaration we found, unless
  11777. // we have attributes.
  11778. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  11779. if (Attr) {
  11780. // FIXME: Diagnose these attributes. For now, we create a new
  11781. // declaration to hold them.
  11782. } else if (TUK == TUK_Reference &&
  11783. (PrevTagDecl->getFriendObjectKind() ==
  11784. Decl::FOK_Undeclared ||
  11785. PP.getModuleContainingLocation(
  11786. PrevDecl->getLocation()) !=
  11787. PP.getModuleContainingLocation(KWLoc)) &&
  11788. SS.isEmpty()) {
  11789. // This declaration is a reference to an existing entity, but
  11790. // has different visibility from that entity: it either makes
  11791. // a friend visible or it makes a type visible in a new module.
  11792. // In either case, create a new declaration. We only do this if
  11793. // the declaration would have meant the same thing if no prior
  11794. // declaration were found, that is, if it was found in the same
  11795. // scope where we would have injected a declaration.
  11796. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  11797. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  11798. return PrevTagDecl;
  11799. // This is in the injected scope, create a new declaration in
  11800. // that scope.
  11801. S = getTagInjectionScope(S, getLangOpts());
  11802. } else {
  11803. return PrevTagDecl;
  11804. }
  11805. }
  11806. // Diagnose attempts to redefine a tag.
  11807. if (TUK == TUK_Definition) {
  11808. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  11809. // If we're defining a specialization and the previous definition
  11810. // is from an implicit instantiation, don't emit an error
  11811. // here; we'll catch this in the general case below.
  11812. bool IsExplicitSpecializationAfterInstantiation = false;
  11813. if (isMemberSpecialization) {
  11814. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  11815. IsExplicitSpecializationAfterInstantiation =
  11816. RD->getTemplateSpecializationKind() !=
  11817. TSK_ExplicitSpecialization;
  11818. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  11819. IsExplicitSpecializationAfterInstantiation =
  11820. ED->getTemplateSpecializationKind() !=
  11821. TSK_ExplicitSpecialization;
  11822. }
  11823. NamedDecl *Hidden = nullptr;
  11824. if (SkipBody && getLangOpts().CPlusPlus &&
  11825. !hasVisibleDefinition(Def, &Hidden)) {
  11826. // There is a definition of this tag, but it is not visible. We
  11827. // explicitly make use of C++'s one definition rule here, and
  11828. // assume that this definition is identical to the hidden one
  11829. // we already have. Make the existing definition visible and
  11830. // use it in place of this one.
  11831. SkipBody->ShouldSkip = true;
  11832. makeMergedDefinitionVisible(Hidden, KWLoc);
  11833. return Def;
  11834. } else if (!IsExplicitSpecializationAfterInstantiation) {
  11835. // A redeclaration in function prototype scope in C isn't
  11836. // visible elsewhere, so merely issue a warning.
  11837. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  11838. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  11839. else
  11840. Diag(NameLoc, diag::err_redefinition) << Name;
  11841. Diag(Def->getLocation(), diag::note_previous_definition);
  11842. // If this is a redefinition, recover by making this
  11843. // struct be anonymous, which will make any later
  11844. // references get the previous definition.
  11845. Name = nullptr;
  11846. Previous.clear();
  11847. Invalid = true;
  11848. }
  11849. } else {
  11850. // If the type is currently being defined, complain
  11851. // about a nested redefinition.
  11852. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  11853. if (TD->isBeingDefined()) {
  11854. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  11855. Diag(PrevTagDecl->getLocation(),
  11856. diag::note_previous_definition);
  11857. Name = nullptr;
  11858. Previous.clear();
  11859. Invalid = true;
  11860. }
  11861. }
  11862. // Okay, this is definition of a previously declared or referenced
  11863. // tag. We're going to create a new Decl for it.
  11864. }
  11865. // Okay, we're going to make a redeclaration. If this is some kind
  11866. // of reference, make sure we build the redeclaration in the same DC
  11867. // as the original, and ignore the current access specifier.
  11868. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  11869. SearchDC = PrevTagDecl->getDeclContext();
  11870. AS = AS_none;
  11871. }
  11872. }
  11873. // If we get here we have (another) forward declaration or we
  11874. // have a definition. Just create a new decl.
  11875. } else {
  11876. // If we get here, this is a definition of a new tag type in a nested
  11877. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  11878. // new decl/type. We set PrevDecl to NULL so that the entities
  11879. // have distinct types.
  11880. Previous.clear();
  11881. }
  11882. // If we get here, we're going to create a new Decl. If PrevDecl
  11883. // is non-NULL, it's a definition of the tag declared by
  11884. // PrevDecl. If it's NULL, we have a new definition.
  11885. // Otherwise, PrevDecl is not a tag, but was found with tag
  11886. // lookup. This is only actually possible in C++, where a few
  11887. // things like templates still live in the tag namespace.
  11888. } else {
  11889. // Use a better diagnostic if an elaborated-type-specifier
  11890. // found the wrong kind of type on the first
  11891. // (non-redeclaration) lookup.
  11892. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  11893. !Previous.isForRedeclaration()) {
  11894. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  11895. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  11896. << Kind;
  11897. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  11898. Invalid = true;
  11899. // Otherwise, only diagnose if the declaration is in scope.
  11900. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  11901. SS.isNotEmpty() || isMemberSpecialization)) {
  11902. // do nothing
  11903. // Diagnose implicit declarations introduced by elaborated types.
  11904. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  11905. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  11906. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  11907. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  11908. Invalid = true;
  11909. // Otherwise it's a declaration. Call out a particularly common
  11910. // case here.
  11911. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  11912. unsigned Kind = 0;
  11913. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  11914. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  11915. << Name << Kind << TND->getUnderlyingType();
  11916. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  11917. Invalid = true;
  11918. // Otherwise, diagnose.
  11919. } else {
  11920. // The tag name clashes with something else in the target scope,
  11921. // issue an error and recover by making this tag be anonymous.
  11922. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  11923. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  11924. Name = nullptr;
  11925. Invalid = true;
  11926. }
  11927. // The existing declaration isn't relevant to us; we're in a
  11928. // new scope, so clear out the previous declaration.
  11929. Previous.clear();
  11930. }
  11931. }
  11932. CreateNewDecl:
  11933. TagDecl *PrevDecl = nullptr;
  11934. if (Previous.isSingleResult())
  11935. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  11936. // If there is an identifier, use the location of the identifier as the
  11937. // location of the decl, otherwise use the location of the struct/union
  11938. // keyword.
  11939. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  11940. // Otherwise, create a new declaration. If there is a previous
  11941. // declaration of the same entity, the two will be linked via
  11942. // PrevDecl.
  11943. TagDecl *New;
  11944. bool IsForwardReference = false;
  11945. if (Kind == TTK_Enum) {
  11946. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  11947. // enum X { A, B, C } D; D should chain to X.
  11948. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  11949. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  11950. ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
  11951. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  11952. StdAlignValT = cast<EnumDecl>(New);
  11953. // If this is an undefined enum, warn.
  11954. if (TUK != TUK_Definition && !Invalid) {
  11955. TagDecl *Def;
  11956. if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
  11957. cast<EnumDecl>(New)->isFixed()) {
  11958. // C++0x: 7.2p2: opaque-enum-declaration.
  11959. // Conflicts are diagnosed above. Do nothing.
  11960. }
  11961. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  11962. Diag(Loc, diag::ext_forward_ref_enum_def)
  11963. << New;
  11964. Diag(Def->getLocation(), diag::note_previous_definition);
  11965. } else {
  11966. unsigned DiagID = diag::ext_forward_ref_enum;
  11967. if (getLangOpts().MSVCCompat)
  11968. DiagID = diag::ext_ms_forward_ref_enum;
  11969. else if (getLangOpts().CPlusPlus)
  11970. DiagID = diag::err_forward_ref_enum;
  11971. Diag(Loc, DiagID);
  11972. // If this is a forward-declared reference to an enumeration, make a
  11973. // note of it; we won't actually be introducing the declaration into
  11974. // the declaration context.
  11975. if (TUK == TUK_Reference)
  11976. IsForwardReference = true;
  11977. }
  11978. }
  11979. if (EnumUnderlying) {
  11980. EnumDecl *ED = cast<EnumDecl>(New);
  11981. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  11982. ED->setIntegerTypeSourceInfo(TI);
  11983. else
  11984. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  11985. ED->setPromotionType(ED->getIntegerType());
  11986. }
  11987. } else {
  11988. // struct/union/class
  11989. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  11990. // struct X { int A; } D; D should chain to X.
  11991. if (getLangOpts().CPlusPlus) {
  11992. // FIXME: Look for a way to use RecordDecl for simple structs.
  11993. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  11994. cast_or_null<CXXRecordDecl>(PrevDecl));
  11995. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  11996. StdBadAlloc = cast<CXXRecordDecl>(New);
  11997. } else
  11998. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  11999. cast_or_null<RecordDecl>(PrevDecl));
  12000. }
  12001. // C++11 [dcl.type]p3:
  12002. // A type-specifier-seq shall not define a class or enumeration [...].
  12003. if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
  12004. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  12005. << Context.getTagDeclType(New);
  12006. Invalid = true;
  12007. }
  12008. // Maybe add qualifier info.
  12009. if (SS.isNotEmpty()) {
  12010. if (SS.isSet()) {
  12011. // If this is either a declaration or a definition, check the
  12012. // nested-name-specifier against the current context. We don't do this
  12013. // for explicit specializations, because they have similar checking
  12014. // (with more specific diagnostics) in the call to
  12015. // CheckMemberSpecialization, below.
  12016. if (!isMemberSpecialization &&
  12017. (TUK == TUK_Definition || TUK == TUK_Declaration) &&
  12018. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
  12019. Invalid = true;
  12020. New->setQualifierInfo(SS.getWithLocInContext(Context));
  12021. if (TemplateParameterLists.size() > 0) {
  12022. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  12023. }
  12024. }
  12025. else
  12026. Invalid = true;
  12027. }
  12028. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  12029. // Add alignment attributes if necessary; these attributes are checked when
  12030. // the ASTContext lays out the structure.
  12031. //
  12032. // It is important for implementing the correct semantics that this
  12033. // happen here (in act on tag decl). The #pragma pack stack is
  12034. // maintained as a result of parser callbacks which can occur at
  12035. // many points during the parsing of a struct declaration (because
  12036. // the #pragma tokens are effectively skipped over during the
  12037. // parsing of the struct).
  12038. if (TUK == TUK_Definition) {
  12039. AddAlignmentAttributesForRecord(RD);
  12040. AddMsStructLayoutForRecord(RD);
  12041. }
  12042. }
  12043. if (ModulePrivateLoc.isValid()) {
  12044. if (isMemberSpecialization)
  12045. Diag(New->getLocation(), diag::err_module_private_specialization)
  12046. << 2
  12047. << FixItHint::CreateRemoval(ModulePrivateLoc);
  12048. // __module_private__ does not apply to local classes. However, we only
  12049. // diagnose this as an error when the declaration specifiers are
  12050. // freestanding. Here, we just ignore the __module_private__.
  12051. else if (!SearchDC->isFunctionOrMethod())
  12052. New->setModulePrivate();
  12053. }
  12054. // If this is a specialization of a member class (of a class template),
  12055. // check the specialization.
  12056. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  12057. Invalid = true;
  12058. // If we're declaring or defining a tag in function prototype scope in C,
  12059. // note that this type can only be used within the function and add it to
  12060. // the list of decls to inject into the function definition scope.
  12061. if ((Name || Kind == TTK_Enum) &&
  12062. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  12063. if (getLangOpts().CPlusPlus) {
  12064. // C++ [dcl.fct]p6:
  12065. // Types shall not be defined in return or parameter types.
  12066. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  12067. Diag(Loc, diag::err_type_defined_in_param_type)
  12068. << Name;
  12069. Invalid = true;
  12070. }
  12071. } else if (!PrevDecl) {
  12072. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  12073. }
  12074. }
  12075. if (Invalid)
  12076. New->setInvalidDecl();
  12077. if (Attr)
  12078. ProcessDeclAttributeList(S, New, Attr);
  12079. // Set the lexical context. If the tag has a C++ scope specifier, the
  12080. // lexical context will be different from the semantic context.
  12081. New->setLexicalDeclContext(CurContext);
  12082. // Mark this as a friend decl if applicable.
  12083. // In Microsoft mode, a friend declaration also acts as a forward
  12084. // declaration so we always pass true to setObjectOfFriendDecl to make
  12085. // the tag name visible.
  12086. if (TUK == TUK_Friend)
  12087. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  12088. // Set the access specifier.
  12089. if (!Invalid && SearchDC->isRecord())
  12090. SetMemberAccessSpecifier(New, PrevDecl, AS);
  12091. if (TUK == TUK_Definition)
  12092. New->startDefinition();
  12093. // If this has an identifier, add it to the scope stack.
  12094. if (TUK == TUK_Friend) {
  12095. // We might be replacing an existing declaration in the lookup tables;
  12096. // if so, borrow its access specifier.
  12097. if (PrevDecl)
  12098. New->setAccess(PrevDecl->getAccess());
  12099. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  12100. DC->makeDeclVisibleInContext(New);
  12101. if (Name) // can be null along some error paths
  12102. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  12103. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  12104. } else if (Name) {
  12105. S = getNonFieldDeclScope(S);
  12106. PushOnScopeChains(New, S, !IsForwardReference);
  12107. if (IsForwardReference)
  12108. SearchDC->makeDeclVisibleInContext(New);
  12109. } else {
  12110. CurContext->addDecl(New);
  12111. }
  12112. // If this is the C FILE type, notify the AST context.
  12113. if (IdentifierInfo *II = New->getIdentifier())
  12114. if (!New->isInvalidDecl() &&
  12115. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  12116. II->isStr("FILE"))
  12117. Context.setFILEDecl(New);
  12118. if (PrevDecl)
  12119. mergeDeclAttributes(New, PrevDecl);
  12120. // If there's a #pragma GCC visibility in scope, set the visibility of this
  12121. // record.
  12122. AddPushedVisibilityAttribute(New);
  12123. OwnedDecl = true;
  12124. // In C++, don't return an invalid declaration. We can't recover well from
  12125. // the cases where we make the type anonymous.
  12126. if (Invalid && getLangOpts().CPlusPlus) {
  12127. if (New->isBeingDefined())
  12128. if (auto RD = dyn_cast<RecordDecl>(New))
  12129. RD->completeDefinition();
  12130. return nullptr;
  12131. } else {
  12132. return New;
  12133. }
  12134. }
  12135. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  12136. AdjustDeclIfTemplate(TagD);
  12137. TagDecl *Tag = cast<TagDecl>(TagD);
  12138. // Enter the tag context.
  12139. PushDeclContext(S, Tag);
  12140. ActOnDocumentableDecl(TagD);
  12141. // If there's a #pragma GCC visibility in scope, set the visibility of this
  12142. // record.
  12143. AddPushedVisibilityAttribute(Tag);
  12144. }
  12145. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  12146. assert(isa<ObjCContainerDecl>(IDecl) &&
  12147. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  12148. DeclContext *OCD = cast<DeclContext>(IDecl);
  12149. assert(getContainingDC(OCD) == CurContext &&
  12150. "The next DeclContext should be lexically contained in the current one.");
  12151. CurContext = OCD;
  12152. return IDecl;
  12153. }
  12154. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  12155. SourceLocation FinalLoc,
  12156. bool IsFinalSpelledSealed,
  12157. SourceLocation LBraceLoc) {
  12158. AdjustDeclIfTemplate(TagD);
  12159. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  12160. FieldCollector->StartClass();
  12161. if (!Record->getIdentifier())
  12162. return;
  12163. if (FinalLoc.isValid())
  12164. Record->addAttr(new (Context)
  12165. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  12166. // C++ [class]p2:
  12167. // [...] The class-name is also inserted into the scope of the
  12168. // class itself; this is known as the injected-class-name. For
  12169. // purposes of access checking, the injected-class-name is treated
  12170. // as if it were a public member name.
  12171. CXXRecordDecl *InjectedClassName
  12172. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  12173. Record->getLocStart(), Record->getLocation(),
  12174. Record->getIdentifier(),
  12175. /*PrevDecl=*/nullptr,
  12176. /*DelayTypeCreation=*/true);
  12177. Context.getTypeDeclType(InjectedClassName, Record);
  12178. InjectedClassName->setImplicit();
  12179. InjectedClassName->setAccess(AS_public);
  12180. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  12181. InjectedClassName->setDescribedClassTemplate(Template);
  12182. PushOnScopeChains(InjectedClassName, S);
  12183. assert(InjectedClassName->isInjectedClassName() &&
  12184. "Broken injected-class-name");
  12185. }
  12186. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  12187. SourceRange BraceRange) {
  12188. AdjustDeclIfTemplate(TagD);
  12189. TagDecl *Tag = cast<TagDecl>(TagD);
  12190. Tag->setBraceRange(BraceRange);
  12191. // Make sure we "complete" the definition even it is invalid.
  12192. if (Tag->isBeingDefined()) {
  12193. assert(Tag->isInvalidDecl() && "We should already have completed it");
  12194. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  12195. RD->completeDefinition();
  12196. }
  12197. if (isa<CXXRecordDecl>(Tag))
  12198. FieldCollector->FinishClass();
  12199. // Exit this scope of this tag's definition.
  12200. PopDeclContext();
  12201. if (getCurLexicalContext()->isObjCContainer() &&
  12202. Tag->getDeclContext()->isFileContext())
  12203. Tag->setTopLevelDeclInObjCContainer();
  12204. // Notify the consumer that we've defined a tag.
  12205. if (!Tag->isInvalidDecl())
  12206. Consumer.HandleTagDeclDefinition(Tag);
  12207. }
  12208. void Sema::ActOnObjCContainerFinishDefinition() {
  12209. // Exit this scope of this interface definition.
  12210. PopDeclContext();
  12211. }
  12212. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  12213. assert(DC == CurContext && "Mismatch of container contexts");
  12214. OriginalLexicalContext = DC;
  12215. ActOnObjCContainerFinishDefinition();
  12216. }
  12217. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  12218. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  12219. OriginalLexicalContext = nullptr;
  12220. }
  12221. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  12222. AdjustDeclIfTemplate(TagD);
  12223. TagDecl *Tag = cast<TagDecl>(TagD);
  12224. Tag->setInvalidDecl();
  12225. // Make sure we "complete" the definition even it is invalid.
  12226. if (Tag->isBeingDefined()) {
  12227. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  12228. RD->completeDefinition();
  12229. }
  12230. // We're undoing ActOnTagStartDefinition here, not
  12231. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  12232. // the FieldCollector.
  12233. PopDeclContext();
  12234. }
  12235. // Note that FieldName may be null for anonymous bitfields.
  12236. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  12237. IdentifierInfo *FieldName,
  12238. QualType FieldTy, bool IsMsStruct,
  12239. Expr *BitWidth, bool *ZeroWidth) {
  12240. // Default to true; that shouldn't confuse checks for emptiness
  12241. if (ZeroWidth)
  12242. *ZeroWidth = true;
  12243. // C99 6.7.2.1p4 - verify the field type.
  12244. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  12245. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  12246. // Handle incomplete types with specific error.
  12247. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  12248. return ExprError();
  12249. if (FieldName)
  12250. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  12251. << FieldName << FieldTy << BitWidth->getSourceRange();
  12252. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  12253. << FieldTy << BitWidth->getSourceRange();
  12254. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  12255. UPPC_BitFieldWidth))
  12256. return ExprError();
  12257. // If the bit-width is type- or value-dependent, don't try to check
  12258. // it now.
  12259. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  12260. return BitWidth;
  12261. llvm::APSInt Value;
  12262. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  12263. if (ICE.isInvalid())
  12264. return ICE;
  12265. BitWidth = ICE.get();
  12266. if (Value != 0 && ZeroWidth)
  12267. *ZeroWidth = false;
  12268. // Zero-width bitfield is ok for anonymous field.
  12269. if (Value == 0 && FieldName)
  12270. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  12271. if (Value.isSigned() && Value.isNegative()) {
  12272. if (FieldName)
  12273. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  12274. << FieldName << Value.toString(10);
  12275. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  12276. << Value.toString(10);
  12277. }
  12278. if (!FieldTy->isDependentType()) {
  12279. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  12280. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  12281. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  12282. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  12283. // ABI.
  12284. bool CStdConstraintViolation =
  12285. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  12286. bool MSBitfieldViolation =
  12287. Value.ugt(TypeStorageSize) &&
  12288. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  12289. if (CStdConstraintViolation || MSBitfieldViolation) {
  12290. unsigned DiagWidth =
  12291. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  12292. if (FieldName)
  12293. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  12294. << FieldName << (unsigned)Value.getZExtValue()
  12295. << !CStdConstraintViolation << DiagWidth;
  12296. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  12297. << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
  12298. << DiagWidth;
  12299. }
  12300. // Warn on types where the user might conceivably expect to get all
  12301. // specified bits as value bits: that's all integral types other than
  12302. // 'bool'.
  12303. if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
  12304. if (FieldName)
  12305. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  12306. << FieldName << (unsigned)Value.getZExtValue()
  12307. << (unsigned)TypeWidth;
  12308. else
  12309. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  12310. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  12311. }
  12312. }
  12313. return BitWidth;
  12314. }
  12315. /// ActOnField - Each field of a C struct/union is passed into this in order
  12316. /// to create a FieldDecl object for it.
  12317. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  12318. Declarator &D, Expr *BitfieldWidth) {
  12319. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  12320. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  12321. /*InitStyle=*/ICIS_NoInit, AS_public);
  12322. return Res;
  12323. }
  12324. /// HandleField - Analyze a field of a C struct or a C++ data member.
  12325. ///
  12326. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  12327. SourceLocation DeclStart,
  12328. Declarator &D, Expr *BitWidth,
  12329. InClassInitStyle InitStyle,
  12330. AccessSpecifier AS) {
  12331. if (D.isDecompositionDeclarator()) {
  12332. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  12333. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  12334. << Decomp.getSourceRange();
  12335. return nullptr;
  12336. }
  12337. IdentifierInfo *II = D.getIdentifier();
  12338. SourceLocation Loc = DeclStart;
  12339. if (II) Loc = D.getIdentifierLoc();
  12340. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12341. QualType T = TInfo->getType();
  12342. if (getLangOpts().CPlusPlus) {
  12343. CheckExtraCXXDefaultArguments(D);
  12344. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  12345. UPPC_DataMemberType)) {
  12346. D.setInvalidType();
  12347. T = Context.IntTy;
  12348. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  12349. }
  12350. }
  12351. // TR 18037 does not allow fields to be declared with address spaces.
  12352. if (T.getQualifiers().hasAddressSpace()) {
  12353. Diag(Loc, diag::err_field_with_address_space);
  12354. D.setInvalidType();
  12355. }
  12356. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  12357. // used as structure or union field: image, sampler, event or block types.
  12358. if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
  12359. T->isSamplerT() || T->isBlockPointerType())) {
  12360. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  12361. D.setInvalidType();
  12362. }
  12363. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  12364. if (D.getDeclSpec().isInlineSpecified())
  12365. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  12366. << getLangOpts().CPlusPlus1z;
  12367. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  12368. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  12369. diag::err_invalid_thread)
  12370. << DeclSpec::getSpecifierName(TSCS);
  12371. // Check to see if this name was declared as a member previously
  12372. NamedDecl *PrevDecl = nullptr;
  12373. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  12374. LookupName(Previous, S);
  12375. switch (Previous.getResultKind()) {
  12376. case LookupResult::Found:
  12377. case LookupResult::FoundUnresolvedValue:
  12378. PrevDecl = Previous.getAsSingle<NamedDecl>();
  12379. break;
  12380. case LookupResult::FoundOverloaded:
  12381. PrevDecl = Previous.getRepresentativeDecl();
  12382. break;
  12383. case LookupResult::NotFound:
  12384. case LookupResult::NotFoundInCurrentInstantiation:
  12385. case LookupResult::Ambiguous:
  12386. break;
  12387. }
  12388. Previous.suppressDiagnostics();
  12389. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  12390. // Maybe we will complain about the shadowed template parameter.
  12391. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  12392. // Just pretend that we didn't see the previous declaration.
  12393. PrevDecl = nullptr;
  12394. }
  12395. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  12396. PrevDecl = nullptr;
  12397. bool Mutable
  12398. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  12399. SourceLocation TSSL = D.getLocStart();
  12400. FieldDecl *NewFD
  12401. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  12402. TSSL, AS, PrevDecl, &D);
  12403. if (NewFD->isInvalidDecl())
  12404. Record->setInvalidDecl();
  12405. if (D.getDeclSpec().isModulePrivateSpecified())
  12406. NewFD->setModulePrivate();
  12407. if (NewFD->isInvalidDecl() && PrevDecl) {
  12408. // Don't introduce NewFD into scope; there's already something
  12409. // with the same name in the same scope.
  12410. } else if (II) {
  12411. PushOnScopeChains(NewFD, S);
  12412. } else
  12413. Record->addDecl(NewFD);
  12414. return NewFD;
  12415. }
  12416. /// \brief Build a new FieldDecl and check its well-formedness.
  12417. ///
  12418. /// This routine builds a new FieldDecl given the fields name, type,
  12419. /// record, etc. \p PrevDecl should refer to any previous declaration
  12420. /// with the same name and in the same scope as the field to be
  12421. /// created.
  12422. ///
  12423. /// \returns a new FieldDecl.
  12424. ///
  12425. /// \todo The Declarator argument is a hack. It will be removed once
  12426. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  12427. TypeSourceInfo *TInfo,
  12428. RecordDecl *Record, SourceLocation Loc,
  12429. bool Mutable, Expr *BitWidth,
  12430. InClassInitStyle InitStyle,
  12431. SourceLocation TSSL,
  12432. AccessSpecifier AS, NamedDecl *PrevDecl,
  12433. Declarator *D) {
  12434. IdentifierInfo *II = Name.getAsIdentifierInfo();
  12435. bool InvalidDecl = false;
  12436. if (D) InvalidDecl = D->isInvalidType();
  12437. // If we receive a broken type, recover by assuming 'int' and
  12438. // marking this declaration as invalid.
  12439. if (T.isNull()) {
  12440. InvalidDecl = true;
  12441. T = Context.IntTy;
  12442. }
  12443. QualType EltTy = Context.getBaseElementType(T);
  12444. if (!EltTy->isDependentType()) {
  12445. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  12446. // Fields of incomplete type force their record to be invalid.
  12447. Record->setInvalidDecl();
  12448. InvalidDecl = true;
  12449. } else {
  12450. NamedDecl *Def;
  12451. EltTy->isIncompleteType(&Def);
  12452. if (Def && Def->isInvalidDecl()) {
  12453. Record->setInvalidDecl();
  12454. InvalidDecl = true;
  12455. }
  12456. }
  12457. }
  12458. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  12459. if (BitWidth && getLangOpts().OpenCL) {
  12460. Diag(Loc, diag::err_opencl_bitfields);
  12461. InvalidDecl = true;
  12462. }
  12463. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  12464. // than a variably modified type.
  12465. if (!InvalidDecl && T->isVariablyModifiedType()) {
  12466. bool SizeIsNegative;
  12467. llvm::APSInt Oversized;
  12468. TypeSourceInfo *FixedTInfo =
  12469. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  12470. SizeIsNegative,
  12471. Oversized);
  12472. if (FixedTInfo) {
  12473. Diag(Loc, diag::warn_illegal_constant_array_size);
  12474. TInfo = FixedTInfo;
  12475. T = FixedTInfo->getType();
  12476. } else {
  12477. if (SizeIsNegative)
  12478. Diag(Loc, diag::err_typecheck_negative_array_size);
  12479. else if (Oversized.getBoolValue())
  12480. Diag(Loc, diag::err_array_too_large)
  12481. << Oversized.toString(10);
  12482. else
  12483. Diag(Loc, diag::err_typecheck_field_variable_size);
  12484. InvalidDecl = true;
  12485. }
  12486. }
  12487. // Fields can not have abstract class types
  12488. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  12489. diag::err_abstract_type_in_decl,
  12490. AbstractFieldType))
  12491. InvalidDecl = true;
  12492. bool ZeroWidth = false;
  12493. if (InvalidDecl)
  12494. BitWidth = nullptr;
  12495. // If this is declared as a bit-field, check the bit-field.
  12496. if (BitWidth) {
  12497. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  12498. &ZeroWidth).get();
  12499. if (!BitWidth) {
  12500. InvalidDecl = true;
  12501. BitWidth = nullptr;
  12502. ZeroWidth = false;
  12503. }
  12504. }
  12505. // Check that 'mutable' is consistent with the type of the declaration.
  12506. if (!InvalidDecl && Mutable) {
  12507. unsigned DiagID = 0;
  12508. if (T->isReferenceType())
  12509. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  12510. : diag::err_mutable_reference;
  12511. else if (T.isConstQualified())
  12512. DiagID = diag::err_mutable_const;
  12513. if (DiagID) {
  12514. SourceLocation ErrLoc = Loc;
  12515. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  12516. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  12517. Diag(ErrLoc, DiagID);
  12518. if (DiagID != diag::ext_mutable_reference) {
  12519. Mutable = false;
  12520. InvalidDecl = true;
  12521. }
  12522. }
  12523. }
  12524. // C++11 [class.union]p8 (DR1460):
  12525. // At most one variant member of a union may have a
  12526. // brace-or-equal-initializer.
  12527. if (InitStyle != ICIS_NoInit)
  12528. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  12529. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  12530. BitWidth, Mutable, InitStyle);
  12531. if (InvalidDecl)
  12532. NewFD->setInvalidDecl();
  12533. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  12534. Diag(Loc, diag::err_duplicate_member) << II;
  12535. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  12536. NewFD->setInvalidDecl();
  12537. }
  12538. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  12539. if (Record->isUnion()) {
  12540. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  12541. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  12542. if (RDecl->getDefinition()) {
  12543. // C++ [class.union]p1: An object of a class with a non-trivial
  12544. // constructor, a non-trivial copy constructor, a non-trivial
  12545. // destructor, or a non-trivial copy assignment operator
  12546. // cannot be a member of a union, nor can an array of such
  12547. // objects.
  12548. if (CheckNontrivialField(NewFD))
  12549. NewFD->setInvalidDecl();
  12550. }
  12551. }
  12552. // C++ [class.union]p1: If a union contains a member of reference type,
  12553. // the program is ill-formed, except when compiling with MSVC extensions
  12554. // enabled.
  12555. if (EltTy->isReferenceType()) {
  12556. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  12557. diag::ext_union_member_of_reference_type :
  12558. diag::err_union_member_of_reference_type)
  12559. << NewFD->getDeclName() << EltTy;
  12560. if (!getLangOpts().MicrosoftExt)
  12561. NewFD->setInvalidDecl();
  12562. }
  12563. }
  12564. }
  12565. // FIXME: We need to pass in the attributes given an AST
  12566. // representation, not a parser representation.
  12567. if (D) {
  12568. // FIXME: The current scope is almost... but not entirely... correct here.
  12569. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  12570. if (NewFD->hasAttrs())
  12571. CheckAlignasUnderalignment(NewFD);
  12572. }
  12573. // In auto-retain/release, infer strong retension for fields of
  12574. // retainable type.
  12575. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  12576. NewFD->setInvalidDecl();
  12577. if (T.isObjCGCWeak())
  12578. Diag(Loc, diag::warn_attribute_weak_on_field);
  12579. NewFD->setAccess(AS);
  12580. return NewFD;
  12581. }
  12582. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  12583. assert(FD);
  12584. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  12585. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  12586. return false;
  12587. QualType EltTy = Context.getBaseElementType(FD->getType());
  12588. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  12589. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  12590. if (RDecl->getDefinition()) {
  12591. // We check for copy constructors before constructors
  12592. // because otherwise we'll never get complaints about
  12593. // copy constructors.
  12594. CXXSpecialMember member = CXXInvalid;
  12595. // We're required to check for any non-trivial constructors. Since the
  12596. // implicit default constructor is suppressed if there are any
  12597. // user-declared constructors, we just need to check that there is a
  12598. // trivial default constructor and a trivial copy constructor. (We don't
  12599. // worry about move constructors here, since this is a C++98 check.)
  12600. if (RDecl->hasNonTrivialCopyConstructor())
  12601. member = CXXCopyConstructor;
  12602. else if (!RDecl->hasTrivialDefaultConstructor())
  12603. member = CXXDefaultConstructor;
  12604. else if (RDecl->hasNonTrivialCopyAssignment())
  12605. member = CXXCopyAssignment;
  12606. else if (RDecl->hasNonTrivialDestructor())
  12607. member = CXXDestructor;
  12608. if (member != CXXInvalid) {
  12609. if (!getLangOpts().CPlusPlus11 &&
  12610. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  12611. // Objective-C++ ARC: it is an error to have a non-trivial field of
  12612. // a union. However, system headers in Objective-C programs
  12613. // occasionally have Objective-C lifetime objects within unions,
  12614. // and rather than cause the program to fail, we make those
  12615. // members unavailable.
  12616. SourceLocation Loc = FD->getLocation();
  12617. if (getSourceManager().isInSystemHeader(Loc)) {
  12618. if (!FD->hasAttr<UnavailableAttr>())
  12619. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  12620. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  12621. return false;
  12622. }
  12623. }
  12624. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  12625. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  12626. diag::err_illegal_union_or_anon_struct_member)
  12627. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  12628. DiagnoseNontrivial(RDecl, member);
  12629. return !getLangOpts().CPlusPlus11;
  12630. }
  12631. }
  12632. }
  12633. return false;
  12634. }
  12635. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  12636. /// AST enum value.
  12637. static ObjCIvarDecl::AccessControl
  12638. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  12639. switch (ivarVisibility) {
  12640. default: llvm_unreachable("Unknown visitibility kind");
  12641. case tok::objc_private: return ObjCIvarDecl::Private;
  12642. case tok::objc_public: return ObjCIvarDecl::Public;
  12643. case tok::objc_protected: return ObjCIvarDecl::Protected;
  12644. case tok::objc_package: return ObjCIvarDecl::Package;
  12645. }
  12646. }
  12647. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  12648. /// in order to create an IvarDecl object for it.
  12649. Decl *Sema::ActOnIvar(Scope *S,
  12650. SourceLocation DeclStart,
  12651. Declarator &D, Expr *BitfieldWidth,
  12652. tok::ObjCKeywordKind Visibility) {
  12653. IdentifierInfo *II = D.getIdentifier();
  12654. Expr *BitWidth = (Expr*)BitfieldWidth;
  12655. SourceLocation Loc = DeclStart;
  12656. if (II) Loc = D.getIdentifierLoc();
  12657. // FIXME: Unnamed fields can be handled in various different ways, for
  12658. // example, unnamed unions inject all members into the struct namespace!
  12659. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12660. QualType T = TInfo->getType();
  12661. if (BitWidth) {
  12662. // 6.7.2.1p3, 6.7.2.1p4
  12663. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  12664. if (!BitWidth)
  12665. D.setInvalidType();
  12666. } else {
  12667. // Not a bitfield.
  12668. // validate II.
  12669. }
  12670. if (T->isReferenceType()) {
  12671. Diag(Loc, diag::err_ivar_reference_type);
  12672. D.setInvalidType();
  12673. }
  12674. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  12675. // than a variably modified type.
  12676. else if (T->isVariablyModifiedType()) {
  12677. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  12678. D.setInvalidType();
  12679. }
  12680. // Get the visibility (access control) for this ivar.
  12681. ObjCIvarDecl::AccessControl ac =
  12682. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  12683. : ObjCIvarDecl::None;
  12684. // Must set ivar's DeclContext to its enclosing interface.
  12685. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  12686. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  12687. return nullptr;
  12688. ObjCContainerDecl *EnclosingContext;
  12689. if (ObjCImplementationDecl *IMPDecl =
  12690. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  12691. if (LangOpts.ObjCRuntime.isFragile()) {
  12692. // Case of ivar declared in an implementation. Context is that of its class.
  12693. EnclosingContext = IMPDecl->getClassInterface();
  12694. assert(EnclosingContext && "Implementation has no class interface!");
  12695. }
  12696. else
  12697. EnclosingContext = EnclosingDecl;
  12698. } else {
  12699. if (ObjCCategoryDecl *CDecl =
  12700. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  12701. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  12702. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  12703. return nullptr;
  12704. }
  12705. }
  12706. EnclosingContext = EnclosingDecl;
  12707. }
  12708. // Construct the decl.
  12709. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  12710. DeclStart, Loc, II, T,
  12711. TInfo, ac, (Expr *)BitfieldWidth);
  12712. if (II) {
  12713. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  12714. ForRedeclaration);
  12715. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  12716. && !isa<TagDecl>(PrevDecl)) {
  12717. Diag(Loc, diag::err_duplicate_member) << II;
  12718. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  12719. NewID->setInvalidDecl();
  12720. }
  12721. }
  12722. // Process attributes attached to the ivar.
  12723. ProcessDeclAttributes(S, NewID, D);
  12724. if (D.isInvalidType())
  12725. NewID->setInvalidDecl();
  12726. // In ARC, infer 'retaining' for ivars of retainable type.
  12727. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  12728. NewID->setInvalidDecl();
  12729. if (D.getDeclSpec().isModulePrivateSpecified())
  12730. NewID->setModulePrivate();
  12731. if (II) {
  12732. // FIXME: When interfaces are DeclContexts, we'll need to add
  12733. // these to the interface.
  12734. S->AddDecl(NewID);
  12735. IdResolver.AddDecl(NewID);
  12736. }
  12737. if (LangOpts.ObjCRuntime.isNonFragile() &&
  12738. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  12739. Diag(Loc, diag::warn_ivars_in_interface);
  12740. return NewID;
  12741. }
  12742. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  12743. /// class and class extensions. For every class \@interface and class
  12744. /// extension \@interface, if the last ivar is a bitfield of any type,
  12745. /// then add an implicit `char :0` ivar to the end of that interface.
  12746. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  12747. SmallVectorImpl<Decl *> &AllIvarDecls) {
  12748. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  12749. return;
  12750. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  12751. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  12752. if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
  12753. return;
  12754. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  12755. if (!ID) {
  12756. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  12757. if (!CD->IsClassExtension())
  12758. return;
  12759. }
  12760. // No need to add this to end of @implementation.
  12761. else
  12762. return;
  12763. }
  12764. // All conditions are met. Add a new bitfield to the tail end of ivars.
  12765. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  12766. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  12767. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  12768. DeclLoc, DeclLoc, nullptr,
  12769. Context.CharTy,
  12770. Context.getTrivialTypeSourceInfo(Context.CharTy,
  12771. DeclLoc),
  12772. ObjCIvarDecl::Private, BW,
  12773. true);
  12774. AllIvarDecls.push_back(Ivar);
  12775. }
  12776. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  12777. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  12778. SourceLocation RBrac, AttributeList *Attr) {
  12779. assert(EnclosingDecl && "missing record or interface decl");
  12780. // If this is an Objective-C @implementation or category and we have
  12781. // new fields here we should reset the layout of the interface since
  12782. // it will now change.
  12783. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  12784. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  12785. switch (DC->getKind()) {
  12786. default: break;
  12787. case Decl::ObjCCategory:
  12788. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  12789. break;
  12790. case Decl::ObjCImplementation:
  12791. Context.
  12792. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  12793. break;
  12794. }
  12795. }
  12796. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  12797. // Start counting up the number of named members; make sure to include
  12798. // members of anonymous structs and unions in the total.
  12799. unsigned NumNamedMembers = 0;
  12800. if (Record) {
  12801. for (const auto *I : Record->decls()) {
  12802. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  12803. if (IFD->getDeclName())
  12804. ++NumNamedMembers;
  12805. }
  12806. }
  12807. // Verify that all the fields are okay.
  12808. SmallVector<FieldDecl*, 32> RecFields;
  12809. bool ARCErrReported = false;
  12810. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  12811. i != end; ++i) {
  12812. FieldDecl *FD = cast<FieldDecl>(*i);
  12813. // Get the type for the field.
  12814. const Type *FDTy = FD->getType().getTypePtr();
  12815. if (!FD->isAnonymousStructOrUnion()) {
  12816. // Remember all fields written by the user.
  12817. RecFields.push_back(FD);
  12818. }
  12819. // If the field is already invalid for some reason, don't emit more
  12820. // diagnostics about it.
  12821. if (FD->isInvalidDecl()) {
  12822. EnclosingDecl->setInvalidDecl();
  12823. continue;
  12824. }
  12825. // C99 6.7.2.1p2:
  12826. // A structure or union shall not contain a member with
  12827. // incomplete or function type (hence, a structure shall not
  12828. // contain an instance of itself, but may contain a pointer to
  12829. // an instance of itself), except that the last member of a
  12830. // structure with more than one named member may have incomplete
  12831. // array type; such a structure (and any union containing,
  12832. // possibly recursively, a member that is such a structure)
  12833. // shall not be a member of a structure or an element of an
  12834. // array.
  12835. if (FDTy->isFunctionType()) {
  12836. // Field declared as a function.
  12837. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  12838. << FD->getDeclName();
  12839. FD->setInvalidDecl();
  12840. EnclosingDecl->setInvalidDecl();
  12841. continue;
  12842. } else if (FDTy->isIncompleteArrayType() && Record &&
  12843. ((i + 1 == Fields.end() && !Record->isUnion()) ||
  12844. ((getLangOpts().MicrosoftExt ||
  12845. getLangOpts().CPlusPlus) &&
  12846. (i + 1 == Fields.end() || Record->isUnion())))) {
  12847. // Flexible array member.
  12848. // Microsoft and g++ is more permissive regarding flexible array.
  12849. // It will accept flexible array in union and also
  12850. // as the sole element of a struct/class.
  12851. unsigned DiagID = 0;
  12852. if (Record->isUnion())
  12853. DiagID = getLangOpts().MicrosoftExt
  12854. ? diag::ext_flexible_array_union_ms
  12855. : getLangOpts().CPlusPlus
  12856. ? diag::ext_flexible_array_union_gnu
  12857. : diag::err_flexible_array_union;
  12858. else if (NumNamedMembers < 1)
  12859. DiagID = getLangOpts().MicrosoftExt
  12860. ? diag::ext_flexible_array_empty_aggregate_ms
  12861. : getLangOpts().CPlusPlus
  12862. ? diag::ext_flexible_array_empty_aggregate_gnu
  12863. : diag::err_flexible_array_empty_aggregate;
  12864. if (DiagID)
  12865. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  12866. << Record->getTagKind();
  12867. // While the layout of types that contain virtual bases is not specified
  12868. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  12869. // virtual bases after the derived members. This would make a flexible
  12870. // array member declared at the end of an object not adjacent to the end
  12871. // of the type.
  12872. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
  12873. if (RD->getNumVBases() != 0)
  12874. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  12875. << FD->getDeclName() << Record->getTagKind();
  12876. if (!getLangOpts().C99)
  12877. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  12878. << FD->getDeclName() << Record->getTagKind();
  12879. // If the element type has a non-trivial destructor, we would not
  12880. // implicitly destroy the elements, so disallow it for now.
  12881. //
  12882. // FIXME: GCC allows this. We should probably either implicitly delete
  12883. // the destructor of the containing class, or just allow this.
  12884. QualType BaseElem = Context.getBaseElementType(FD->getType());
  12885. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  12886. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  12887. << FD->getDeclName() << FD->getType();
  12888. FD->setInvalidDecl();
  12889. EnclosingDecl->setInvalidDecl();
  12890. continue;
  12891. }
  12892. // Okay, we have a legal flexible array member at the end of the struct.
  12893. Record->setHasFlexibleArrayMember(true);
  12894. } else if (!FDTy->isDependentType() &&
  12895. RequireCompleteType(FD->getLocation(), FD->getType(),
  12896. diag::err_field_incomplete)) {
  12897. // Incomplete type
  12898. FD->setInvalidDecl();
  12899. EnclosingDecl->setInvalidDecl();
  12900. continue;
  12901. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  12902. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  12903. // A type which contains a flexible array member is considered to be a
  12904. // flexible array member.
  12905. Record->setHasFlexibleArrayMember(true);
  12906. if (!Record->isUnion()) {
  12907. // If this is a struct/class and this is not the last element, reject
  12908. // it. Note that GCC supports variable sized arrays in the middle of
  12909. // structures.
  12910. if (i + 1 != Fields.end())
  12911. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  12912. << FD->getDeclName() << FD->getType();
  12913. else {
  12914. // We support flexible arrays at the end of structs in
  12915. // other structs as an extension.
  12916. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  12917. << FD->getDeclName();
  12918. }
  12919. }
  12920. }
  12921. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  12922. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  12923. diag::err_abstract_type_in_decl,
  12924. AbstractIvarType)) {
  12925. // Ivars can not have abstract class types
  12926. FD->setInvalidDecl();
  12927. }
  12928. if (Record && FDTTy->getDecl()->hasObjectMember())
  12929. Record->setHasObjectMember(true);
  12930. if (Record && FDTTy->getDecl()->hasVolatileMember())
  12931. Record->setHasVolatileMember(true);
  12932. } else if (FDTy->isObjCObjectType()) {
  12933. /// A field cannot be an Objective-c object
  12934. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  12935. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  12936. QualType T = Context.getObjCObjectPointerType(FD->getType());
  12937. FD->setType(T);
  12938. } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
  12939. (!getLangOpts().CPlusPlus || Record->isUnion())) {
  12940. // It's an error in ARC if a field has lifetime.
  12941. // We don't want to report this in a system header, though,
  12942. // so we just make the field unavailable.
  12943. // FIXME: that's really not sufficient; we need to make the type
  12944. // itself invalid to, say, initialize or copy.
  12945. QualType T = FD->getType();
  12946. Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
  12947. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
  12948. SourceLocation loc = FD->getLocation();
  12949. if (getSourceManager().isInSystemHeader(loc)) {
  12950. if (!FD->hasAttr<UnavailableAttr>()) {
  12951. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  12952. UnavailableAttr::IR_ARCFieldWithOwnership, loc));
  12953. }
  12954. } else {
  12955. Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
  12956. << T->isBlockPointerType() << Record->getTagKind();
  12957. }
  12958. ARCErrReported = true;
  12959. }
  12960. } else if (getLangOpts().ObjC1 &&
  12961. getLangOpts().getGC() != LangOptions::NonGC &&
  12962. Record && !Record->hasObjectMember()) {
  12963. if (FD->getType()->isObjCObjectPointerType() ||
  12964. FD->getType().isObjCGCStrong())
  12965. Record->setHasObjectMember(true);
  12966. else if (Context.getAsArrayType(FD->getType())) {
  12967. QualType BaseType = Context.getBaseElementType(FD->getType());
  12968. if (BaseType->isRecordType() &&
  12969. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  12970. Record->setHasObjectMember(true);
  12971. else if (BaseType->isObjCObjectPointerType() ||
  12972. BaseType.isObjCGCStrong())
  12973. Record->setHasObjectMember(true);
  12974. }
  12975. }
  12976. if (Record && FD->getType().isVolatileQualified())
  12977. Record->setHasVolatileMember(true);
  12978. // Keep track of the number of named members.
  12979. if (FD->getIdentifier())
  12980. ++NumNamedMembers;
  12981. }
  12982. // Okay, we successfully defined 'Record'.
  12983. if (Record) {
  12984. bool Completed = false;
  12985. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  12986. if (!CXXRecord->isInvalidDecl()) {
  12987. // Set access bits correctly on the directly-declared conversions.
  12988. for (CXXRecordDecl::conversion_iterator
  12989. I = CXXRecord->conversion_begin(),
  12990. E = CXXRecord->conversion_end(); I != E; ++I)
  12991. I.setAccess((*I)->getAccess());
  12992. }
  12993. if (!CXXRecord->isDependentType()) {
  12994. if (CXXRecord->hasUserDeclaredDestructor()) {
  12995. // Adjust user-defined destructor exception spec.
  12996. if (getLangOpts().CPlusPlus11)
  12997. AdjustDestructorExceptionSpec(CXXRecord,
  12998. CXXRecord->getDestructor());
  12999. }
  13000. if (!CXXRecord->isInvalidDecl()) {
  13001. // Add any implicitly-declared members to this class.
  13002. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  13003. // If we have virtual base classes, we may end up finding multiple
  13004. // final overriders for a given virtual function. Check for this
  13005. // problem now.
  13006. if (CXXRecord->getNumVBases()) {
  13007. CXXFinalOverriderMap FinalOverriders;
  13008. CXXRecord->getFinalOverriders(FinalOverriders);
  13009. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  13010. MEnd = FinalOverriders.end();
  13011. M != MEnd; ++M) {
  13012. for (OverridingMethods::iterator SO = M->second.begin(),
  13013. SOEnd = M->second.end();
  13014. SO != SOEnd; ++SO) {
  13015. assert(SO->second.size() > 0 &&
  13016. "Virtual function without overridding functions?");
  13017. if (SO->second.size() == 1)
  13018. continue;
  13019. // C++ [class.virtual]p2:
  13020. // In a derived class, if a virtual member function of a base
  13021. // class subobject has more than one final overrider the
  13022. // program is ill-formed.
  13023. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  13024. << (const NamedDecl *)M->first << Record;
  13025. Diag(M->first->getLocation(),
  13026. diag::note_overridden_virtual_function);
  13027. for (OverridingMethods::overriding_iterator
  13028. OM = SO->second.begin(),
  13029. OMEnd = SO->second.end();
  13030. OM != OMEnd; ++OM)
  13031. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  13032. << (const NamedDecl *)M->first << OM->Method->getParent();
  13033. Record->setInvalidDecl();
  13034. }
  13035. }
  13036. CXXRecord->completeDefinition(&FinalOverriders);
  13037. Completed = true;
  13038. }
  13039. }
  13040. }
  13041. }
  13042. if (!Completed)
  13043. Record->completeDefinition();
  13044. // We may have deferred checking for a deleted destructor. Check now.
  13045. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  13046. auto *Dtor = CXXRecord->getDestructor();
  13047. if (Dtor && Dtor->isImplicit() &&
  13048. ShouldDeleteSpecialMember(Dtor, CXXDestructor))
  13049. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  13050. }
  13051. if (Record->hasAttrs()) {
  13052. CheckAlignasUnderalignment(Record);
  13053. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  13054. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  13055. IA->getRange(), IA->getBestCase(),
  13056. IA->getSemanticSpelling());
  13057. }
  13058. // Check if the structure/union declaration is a type that can have zero
  13059. // size in C. For C this is a language extension, for C++ it may cause
  13060. // compatibility problems.
  13061. bool CheckForZeroSize;
  13062. if (!getLangOpts().CPlusPlus) {
  13063. CheckForZeroSize = true;
  13064. } else {
  13065. // For C++ filter out types that cannot be referenced in C code.
  13066. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  13067. CheckForZeroSize =
  13068. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  13069. !CXXRecord->isDependentType() &&
  13070. CXXRecord->isCLike();
  13071. }
  13072. if (CheckForZeroSize) {
  13073. bool ZeroSize = true;
  13074. bool IsEmpty = true;
  13075. unsigned NonBitFields = 0;
  13076. for (RecordDecl::field_iterator I = Record->field_begin(),
  13077. E = Record->field_end();
  13078. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  13079. IsEmpty = false;
  13080. if (I->isUnnamedBitfield()) {
  13081. if (I->getBitWidthValue(Context) > 0)
  13082. ZeroSize = false;
  13083. } else {
  13084. ++NonBitFields;
  13085. QualType FieldType = I->getType();
  13086. if (FieldType->isIncompleteType() ||
  13087. !Context.getTypeSizeInChars(FieldType).isZero())
  13088. ZeroSize = false;
  13089. }
  13090. }
  13091. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  13092. // allowed in C++, but warn if its declaration is inside
  13093. // extern "C" block.
  13094. if (ZeroSize) {
  13095. Diag(RecLoc, getLangOpts().CPlusPlus ?
  13096. diag::warn_zero_size_struct_union_in_extern_c :
  13097. diag::warn_zero_size_struct_union_compat)
  13098. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  13099. }
  13100. // Structs without named members are extension in C (C99 6.7.2.1p7),
  13101. // but are accepted by GCC.
  13102. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  13103. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  13104. diag::ext_no_named_members_in_struct_union)
  13105. << Record->isUnion();
  13106. }
  13107. }
  13108. } else {
  13109. ObjCIvarDecl **ClsFields =
  13110. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  13111. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  13112. ID->setEndOfDefinitionLoc(RBrac);
  13113. // Add ivar's to class's DeclContext.
  13114. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  13115. ClsFields[i]->setLexicalDeclContext(ID);
  13116. ID->addDecl(ClsFields[i]);
  13117. }
  13118. // Must enforce the rule that ivars in the base classes may not be
  13119. // duplicates.
  13120. if (ID->getSuperClass())
  13121. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  13122. } else if (ObjCImplementationDecl *IMPDecl =
  13123. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  13124. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  13125. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  13126. // Ivar declared in @implementation never belongs to the implementation.
  13127. // Only it is in implementation's lexical context.
  13128. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  13129. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  13130. IMPDecl->setIvarLBraceLoc(LBrac);
  13131. IMPDecl->setIvarRBraceLoc(RBrac);
  13132. } else if (ObjCCategoryDecl *CDecl =
  13133. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  13134. // case of ivars in class extension; all other cases have been
  13135. // reported as errors elsewhere.
  13136. // FIXME. Class extension does not have a LocEnd field.
  13137. // CDecl->setLocEnd(RBrac);
  13138. // Add ivar's to class extension's DeclContext.
  13139. // Diagnose redeclaration of private ivars.
  13140. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  13141. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  13142. if (IDecl) {
  13143. if (const ObjCIvarDecl *ClsIvar =
  13144. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  13145. Diag(ClsFields[i]->getLocation(),
  13146. diag::err_duplicate_ivar_declaration);
  13147. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  13148. continue;
  13149. }
  13150. for (const auto *Ext : IDecl->known_extensions()) {
  13151. if (const ObjCIvarDecl *ClsExtIvar
  13152. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  13153. Diag(ClsFields[i]->getLocation(),
  13154. diag::err_duplicate_ivar_declaration);
  13155. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  13156. continue;
  13157. }
  13158. }
  13159. }
  13160. ClsFields[i]->setLexicalDeclContext(CDecl);
  13161. CDecl->addDecl(ClsFields[i]);
  13162. }
  13163. CDecl->setIvarLBraceLoc(LBrac);
  13164. CDecl->setIvarRBraceLoc(RBrac);
  13165. }
  13166. }
  13167. if (Attr)
  13168. ProcessDeclAttributeList(S, Record, Attr);
  13169. }
  13170. /// \brief Determine whether the given integral value is representable within
  13171. /// the given type T.
  13172. static bool isRepresentableIntegerValue(ASTContext &Context,
  13173. llvm::APSInt &Value,
  13174. QualType T) {
  13175. assert(T->isIntegralType(Context) && "Integral type required!");
  13176. unsigned BitWidth = Context.getIntWidth(T);
  13177. if (Value.isUnsigned() || Value.isNonNegative()) {
  13178. if (T->isSignedIntegerOrEnumerationType())
  13179. --BitWidth;
  13180. return Value.getActiveBits() <= BitWidth;
  13181. }
  13182. return Value.getMinSignedBits() <= BitWidth;
  13183. }
  13184. // \brief Given an integral type, return the next larger integral type
  13185. // (or a NULL type of no such type exists).
  13186. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  13187. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  13188. // enum checking below.
  13189. assert(T->isIntegralType(Context) && "Integral type required!");
  13190. const unsigned NumTypes = 4;
  13191. QualType SignedIntegralTypes[NumTypes] = {
  13192. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  13193. };
  13194. QualType UnsignedIntegralTypes[NumTypes] = {
  13195. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  13196. Context.UnsignedLongLongTy
  13197. };
  13198. unsigned BitWidth = Context.getTypeSize(T);
  13199. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  13200. : UnsignedIntegralTypes;
  13201. for (unsigned I = 0; I != NumTypes; ++I)
  13202. if (Context.getTypeSize(Types[I]) > BitWidth)
  13203. return Types[I];
  13204. return QualType();
  13205. }
  13206. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  13207. EnumConstantDecl *LastEnumConst,
  13208. SourceLocation IdLoc,
  13209. IdentifierInfo *Id,
  13210. Expr *Val) {
  13211. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  13212. llvm::APSInt EnumVal(IntWidth);
  13213. QualType EltTy;
  13214. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  13215. Val = nullptr;
  13216. if (Val)
  13217. Val = DefaultLvalueConversion(Val).get();
  13218. if (Val) {
  13219. if (Enum->isDependentType() || Val->isTypeDependent())
  13220. EltTy = Context.DependentTy;
  13221. else {
  13222. SourceLocation ExpLoc;
  13223. if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
  13224. !getLangOpts().MSVCCompat) {
  13225. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  13226. // constant-expression in the enumerator-definition shall be a converted
  13227. // constant expression of the underlying type.
  13228. EltTy = Enum->getIntegerType();
  13229. ExprResult Converted =
  13230. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  13231. CCEK_Enumerator);
  13232. if (Converted.isInvalid())
  13233. Val = nullptr;
  13234. else
  13235. Val = Converted.get();
  13236. } else if (!Val->isValueDependent() &&
  13237. !(Val = VerifyIntegerConstantExpression(Val,
  13238. &EnumVal).get())) {
  13239. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  13240. } else {
  13241. if (Enum->isFixed()) {
  13242. EltTy = Enum->getIntegerType();
  13243. // In Obj-C and Microsoft mode, require the enumeration value to be
  13244. // representable in the underlying type of the enumeration. In C++11,
  13245. // we perform a non-narrowing conversion as part of converted constant
  13246. // expression checking.
  13247. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  13248. if (getLangOpts().MSVCCompat) {
  13249. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  13250. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  13251. } else
  13252. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  13253. } else
  13254. Val = ImpCastExprToType(Val, EltTy,
  13255. EltTy->isBooleanType() ?
  13256. CK_IntegralToBoolean : CK_IntegralCast)
  13257. .get();
  13258. } else if (getLangOpts().CPlusPlus) {
  13259. // C++11 [dcl.enum]p5:
  13260. // If the underlying type is not fixed, the type of each enumerator
  13261. // is the type of its initializing value:
  13262. // - If an initializer is specified for an enumerator, the
  13263. // initializing value has the same type as the expression.
  13264. EltTy = Val->getType();
  13265. } else {
  13266. // C99 6.7.2.2p2:
  13267. // The expression that defines the value of an enumeration constant
  13268. // shall be an integer constant expression that has a value
  13269. // representable as an int.
  13270. // Complain if the value is not representable in an int.
  13271. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  13272. Diag(IdLoc, diag::ext_enum_value_not_int)
  13273. << EnumVal.toString(10) << Val->getSourceRange()
  13274. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  13275. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  13276. // Force the type of the expression to 'int'.
  13277. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  13278. }
  13279. EltTy = Val->getType();
  13280. }
  13281. }
  13282. }
  13283. }
  13284. if (!Val) {
  13285. if (Enum->isDependentType())
  13286. EltTy = Context.DependentTy;
  13287. else if (!LastEnumConst) {
  13288. // C++0x [dcl.enum]p5:
  13289. // If the underlying type is not fixed, the type of each enumerator
  13290. // is the type of its initializing value:
  13291. // - If no initializer is specified for the first enumerator, the
  13292. // initializing value has an unspecified integral type.
  13293. //
  13294. // GCC uses 'int' for its unspecified integral type, as does
  13295. // C99 6.7.2.2p3.
  13296. if (Enum->isFixed()) {
  13297. EltTy = Enum->getIntegerType();
  13298. }
  13299. else {
  13300. EltTy = Context.IntTy;
  13301. }
  13302. } else {
  13303. // Assign the last value + 1.
  13304. EnumVal = LastEnumConst->getInitVal();
  13305. ++EnumVal;
  13306. EltTy = LastEnumConst->getType();
  13307. // Check for overflow on increment.
  13308. if (EnumVal < LastEnumConst->getInitVal()) {
  13309. // C++0x [dcl.enum]p5:
  13310. // If the underlying type is not fixed, the type of each enumerator
  13311. // is the type of its initializing value:
  13312. //
  13313. // - Otherwise the type of the initializing value is the same as
  13314. // the type of the initializing value of the preceding enumerator
  13315. // unless the incremented value is not representable in that type,
  13316. // in which case the type is an unspecified integral type
  13317. // sufficient to contain the incremented value. If no such type
  13318. // exists, the program is ill-formed.
  13319. QualType T = getNextLargerIntegralType(Context, EltTy);
  13320. if (T.isNull() || Enum->isFixed()) {
  13321. // There is no integral type larger enough to represent this
  13322. // value. Complain, then allow the value to wrap around.
  13323. EnumVal = LastEnumConst->getInitVal();
  13324. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  13325. ++EnumVal;
  13326. if (Enum->isFixed())
  13327. // When the underlying type is fixed, this is ill-formed.
  13328. Diag(IdLoc, diag::err_enumerator_wrapped)
  13329. << EnumVal.toString(10)
  13330. << EltTy;
  13331. else
  13332. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  13333. << EnumVal.toString(10);
  13334. } else {
  13335. EltTy = T;
  13336. }
  13337. // Retrieve the last enumerator's value, extent that type to the
  13338. // type that is supposed to be large enough to represent the incremented
  13339. // value, then increment.
  13340. EnumVal = LastEnumConst->getInitVal();
  13341. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  13342. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  13343. ++EnumVal;
  13344. // If we're not in C++, diagnose the overflow of enumerator values,
  13345. // which in C99 means that the enumerator value is not representable in
  13346. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  13347. // permits enumerator values that are representable in some larger
  13348. // integral type.
  13349. if (!getLangOpts().CPlusPlus && !T.isNull())
  13350. Diag(IdLoc, diag::warn_enum_value_overflow);
  13351. } else if (!getLangOpts().CPlusPlus &&
  13352. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  13353. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  13354. Diag(IdLoc, diag::ext_enum_value_not_int)
  13355. << EnumVal.toString(10) << 1;
  13356. }
  13357. }
  13358. }
  13359. if (!EltTy->isDependentType()) {
  13360. // Make the enumerator value match the signedness and size of the
  13361. // enumerator's type.
  13362. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  13363. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  13364. }
  13365. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  13366. Val, EnumVal);
  13367. }
  13368. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  13369. SourceLocation IILoc) {
  13370. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  13371. !getLangOpts().CPlusPlus)
  13372. return SkipBodyInfo();
  13373. // We have an anonymous enum definition. Look up the first enumerator to
  13374. // determine if we should merge the definition with an existing one and
  13375. // skip the body.
  13376. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  13377. ForRedeclaration);
  13378. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  13379. if (!PrevECD)
  13380. return SkipBodyInfo();
  13381. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  13382. NamedDecl *Hidden;
  13383. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  13384. SkipBodyInfo Skip;
  13385. Skip.Previous = Hidden;
  13386. return Skip;
  13387. }
  13388. return SkipBodyInfo();
  13389. }
  13390. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  13391. SourceLocation IdLoc, IdentifierInfo *Id,
  13392. AttributeList *Attr,
  13393. SourceLocation EqualLoc, Expr *Val) {
  13394. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  13395. EnumConstantDecl *LastEnumConst =
  13396. cast_or_null<EnumConstantDecl>(lastEnumConst);
  13397. // The scope passed in may not be a decl scope. Zip up the scope tree until
  13398. // we find one that is.
  13399. S = getNonFieldDeclScope(S);
  13400. // Verify that there isn't already something declared with this name in this
  13401. // scope.
  13402. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  13403. ForRedeclaration);
  13404. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13405. // Maybe we will complain about the shadowed template parameter.
  13406. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  13407. // Just pretend that we didn't see the previous declaration.
  13408. PrevDecl = nullptr;
  13409. }
  13410. // C++ [class.mem]p15:
  13411. // If T is the name of a class, then each of the following shall have a name
  13412. // different from T:
  13413. // - every enumerator of every member of class T that is an unscoped
  13414. // enumerated type
  13415. if (!TheEnumDecl->isScoped())
  13416. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  13417. DeclarationNameInfo(Id, IdLoc));
  13418. EnumConstantDecl *New =
  13419. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  13420. if (!New)
  13421. return nullptr;
  13422. if (PrevDecl) {
  13423. // When in C++, we may get a TagDecl with the same name; in this case the
  13424. // enum constant will 'hide' the tag.
  13425. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  13426. "Received TagDecl when not in C++!");
  13427. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
  13428. shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
  13429. if (isa<EnumConstantDecl>(PrevDecl))
  13430. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  13431. else
  13432. Diag(IdLoc, diag::err_redefinition) << Id;
  13433. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  13434. return nullptr;
  13435. }
  13436. }
  13437. // Process attributes.
  13438. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  13439. // Register this decl in the current scope stack.
  13440. New->setAccess(TheEnumDecl->getAccess());
  13441. PushOnScopeChains(New, S);
  13442. ActOnDocumentableDecl(New);
  13443. return New;
  13444. }
  13445. // Returns true when the enum initial expression does not trigger the
  13446. // duplicate enum warning. A few common cases are exempted as follows:
  13447. // Element2 = Element1
  13448. // Element2 = Element1 + 1
  13449. // Element2 = Element1 - 1
  13450. // Where Element2 and Element1 are from the same enum.
  13451. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  13452. Expr *InitExpr = ECD->getInitExpr();
  13453. if (!InitExpr)
  13454. return true;
  13455. InitExpr = InitExpr->IgnoreImpCasts();
  13456. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  13457. if (!BO->isAdditiveOp())
  13458. return true;
  13459. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  13460. if (!IL)
  13461. return true;
  13462. if (IL->getValue() != 1)
  13463. return true;
  13464. InitExpr = BO->getLHS();
  13465. }
  13466. // This checks if the elements are from the same enum.
  13467. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  13468. if (!DRE)
  13469. return true;
  13470. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  13471. if (!EnumConstant)
  13472. return true;
  13473. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  13474. Enum)
  13475. return true;
  13476. return false;
  13477. }
  13478. namespace {
  13479. struct DupKey {
  13480. int64_t val;
  13481. bool isTombstoneOrEmptyKey;
  13482. DupKey(int64_t val, bool isTombstoneOrEmptyKey)
  13483. : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
  13484. };
  13485. static DupKey GetDupKey(const llvm::APSInt& Val) {
  13486. return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
  13487. false);
  13488. }
  13489. struct DenseMapInfoDupKey {
  13490. static DupKey getEmptyKey() { return DupKey(0, true); }
  13491. static DupKey getTombstoneKey() { return DupKey(1, true); }
  13492. static unsigned getHashValue(const DupKey Key) {
  13493. return (unsigned)(Key.val * 37);
  13494. }
  13495. static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
  13496. return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
  13497. LHS.val == RHS.val;
  13498. }
  13499. };
  13500. } // end anonymous namespace
  13501. // Emits a warning when an element is implicitly set a value that
  13502. // a previous element has already been set to.
  13503. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  13504. EnumDecl *Enum,
  13505. QualType EnumType) {
  13506. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  13507. return;
  13508. // Avoid anonymous enums
  13509. if (!Enum->getIdentifier())
  13510. return;
  13511. // Only check for small enums.
  13512. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  13513. return;
  13514. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  13515. typedef SmallVector<ECDVector *, 3> DuplicatesVector;
  13516. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  13517. typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
  13518. ValueToVectorMap;
  13519. DuplicatesVector DupVector;
  13520. ValueToVectorMap EnumMap;
  13521. // Populate the EnumMap with all values represented by enum constants without
  13522. // an initialier.
  13523. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  13524. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  13525. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  13526. // this constant. Skip this enum since it may be ill-formed.
  13527. if (!ECD) {
  13528. return;
  13529. }
  13530. if (ECD->getInitExpr())
  13531. continue;
  13532. DupKey Key = GetDupKey(ECD->getInitVal());
  13533. DeclOrVector &Entry = EnumMap[Key];
  13534. // First time encountering this value.
  13535. if (Entry.isNull())
  13536. Entry = ECD;
  13537. }
  13538. // Create vectors for any values that has duplicates.
  13539. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  13540. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
  13541. if (!ValidDuplicateEnum(ECD, Enum))
  13542. continue;
  13543. DupKey Key = GetDupKey(ECD->getInitVal());
  13544. DeclOrVector& Entry = EnumMap[Key];
  13545. if (Entry.isNull())
  13546. continue;
  13547. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  13548. // Ensure constants are different.
  13549. if (D == ECD)
  13550. continue;
  13551. // Create new vector and push values onto it.
  13552. ECDVector *Vec = new ECDVector();
  13553. Vec->push_back(D);
  13554. Vec->push_back(ECD);
  13555. // Update entry to point to the duplicates vector.
  13556. Entry = Vec;
  13557. // Store the vector somewhere we can consult later for quick emission of
  13558. // diagnostics.
  13559. DupVector.push_back(Vec);
  13560. continue;
  13561. }
  13562. ECDVector *Vec = Entry.get<ECDVector*>();
  13563. // Make sure constants are not added more than once.
  13564. if (*Vec->begin() == ECD)
  13565. continue;
  13566. Vec->push_back(ECD);
  13567. }
  13568. // Emit diagnostics.
  13569. for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
  13570. DupVectorEnd = DupVector.end();
  13571. DupVectorIter != DupVectorEnd; ++DupVectorIter) {
  13572. ECDVector *Vec = *DupVectorIter;
  13573. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  13574. // Emit warning for one enum constant.
  13575. ECDVector::iterator I = Vec->begin();
  13576. S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
  13577. << (*I)->getName() << (*I)->getInitVal().toString(10)
  13578. << (*I)->getSourceRange();
  13579. ++I;
  13580. // Emit one note for each of the remaining enum constants with
  13581. // the same value.
  13582. for (ECDVector::iterator E = Vec->end(); I != E; ++I)
  13583. S.Diag((*I)->getLocation(), diag::note_duplicate_element)
  13584. << (*I)->getName() << (*I)->getInitVal().toString(10)
  13585. << (*I)->getSourceRange();
  13586. delete Vec;
  13587. }
  13588. }
  13589. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  13590. bool AllowMask) const {
  13591. assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
  13592. assert(ED->isCompleteDefinition() && "expected enum definition");
  13593. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  13594. llvm::APInt &FlagBits = R.first->second;
  13595. if (R.second) {
  13596. for (auto *E : ED->enumerators()) {
  13597. const auto &EVal = E->getInitVal();
  13598. // Only single-bit enumerators introduce new flag values.
  13599. if (EVal.isPowerOf2())
  13600. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  13601. }
  13602. }
  13603. // A value is in a flag enum if either its bits are a subset of the enum's
  13604. // flag bits (the first condition) or we are allowing masks and the same is
  13605. // true of its complement (the second condition). When masks are allowed, we
  13606. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  13607. //
  13608. // While it's true that any value could be used as a mask, the assumption is
  13609. // that a mask will have all of the insignificant bits set. Anything else is
  13610. // likely a logic error.
  13611. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  13612. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  13613. }
  13614. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  13615. Decl *EnumDeclX,
  13616. ArrayRef<Decl *> Elements,
  13617. Scope *S, AttributeList *Attr) {
  13618. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  13619. QualType EnumType = Context.getTypeDeclType(Enum);
  13620. if (Attr)
  13621. ProcessDeclAttributeList(S, Enum, Attr);
  13622. if (Enum->isDependentType()) {
  13623. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  13624. EnumConstantDecl *ECD =
  13625. cast_or_null<EnumConstantDecl>(Elements[i]);
  13626. if (!ECD) continue;
  13627. ECD->setType(EnumType);
  13628. }
  13629. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  13630. return;
  13631. }
  13632. // TODO: If the result value doesn't fit in an int, it must be a long or long
  13633. // long value. ISO C does not support this, but GCC does as an extension,
  13634. // emit a warning.
  13635. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  13636. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  13637. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  13638. // Verify that all the values are okay, compute the size of the values, and
  13639. // reverse the list.
  13640. unsigned NumNegativeBits = 0;
  13641. unsigned NumPositiveBits = 0;
  13642. // Keep track of whether all elements have type int.
  13643. bool AllElementsInt = true;
  13644. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  13645. EnumConstantDecl *ECD =
  13646. cast_or_null<EnumConstantDecl>(Elements[i]);
  13647. if (!ECD) continue; // Already issued a diagnostic.
  13648. const llvm::APSInt &InitVal = ECD->getInitVal();
  13649. // Keep track of the size of positive and negative values.
  13650. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  13651. NumPositiveBits = std::max(NumPositiveBits,
  13652. (unsigned)InitVal.getActiveBits());
  13653. else
  13654. NumNegativeBits = std::max(NumNegativeBits,
  13655. (unsigned)InitVal.getMinSignedBits());
  13656. // Keep track of whether every enum element has type int (very commmon).
  13657. if (AllElementsInt)
  13658. AllElementsInt = ECD->getType() == Context.IntTy;
  13659. }
  13660. // Figure out the type that should be used for this enum.
  13661. QualType BestType;
  13662. unsigned BestWidth;
  13663. // C++0x N3000 [conv.prom]p3:
  13664. // An rvalue of an unscoped enumeration type whose underlying
  13665. // type is not fixed can be converted to an rvalue of the first
  13666. // of the following types that can represent all the values of
  13667. // the enumeration: int, unsigned int, long int, unsigned long
  13668. // int, long long int, or unsigned long long int.
  13669. // C99 6.4.4.3p2:
  13670. // An identifier declared as an enumeration constant has type int.
  13671. // The C99 rule is modified by a gcc extension
  13672. QualType BestPromotionType;
  13673. bool Packed = Enum->hasAttr<PackedAttr>();
  13674. // -fshort-enums is the equivalent to specifying the packed attribute on all
  13675. // enum definitions.
  13676. if (LangOpts.ShortEnums)
  13677. Packed = true;
  13678. if (Enum->isFixed()) {
  13679. BestType = Enum->getIntegerType();
  13680. if (BestType->isPromotableIntegerType())
  13681. BestPromotionType = Context.getPromotedIntegerType(BestType);
  13682. else
  13683. BestPromotionType = BestType;
  13684. BestWidth = Context.getIntWidth(BestType);
  13685. }
  13686. else if (NumNegativeBits) {
  13687. // If there is a negative value, figure out the smallest integer type (of
  13688. // int/long/longlong) that fits.
  13689. // If it's packed, check also if it fits a char or a short.
  13690. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  13691. BestType = Context.SignedCharTy;
  13692. BestWidth = CharWidth;
  13693. } else if (Packed && NumNegativeBits <= ShortWidth &&
  13694. NumPositiveBits < ShortWidth) {
  13695. BestType = Context.ShortTy;
  13696. BestWidth = ShortWidth;
  13697. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  13698. BestType = Context.IntTy;
  13699. BestWidth = IntWidth;
  13700. } else {
  13701. BestWidth = Context.getTargetInfo().getLongWidth();
  13702. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  13703. BestType = Context.LongTy;
  13704. } else {
  13705. BestWidth = Context.getTargetInfo().getLongLongWidth();
  13706. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  13707. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  13708. BestType = Context.LongLongTy;
  13709. }
  13710. }
  13711. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  13712. } else {
  13713. // If there is no negative value, figure out the smallest type that fits
  13714. // all of the enumerator values.
  13715. // If it's packed, check also if it fits a char or a short.
  13716. if (Packed && NumPositiveBits <= CharWidth) {
  13717. BestType = Context.UnsignedCharTy;
  13718. BestPromotionType = Context.IntTy;
  13719. BestWidth = CharWidth;
  13720. } else if (Packed && NumPositiveBits <= ShortWidth) {
  13721. BestType = Context.UnsignedShortTy;
  13722. BestPromotionType = Context.IntTy;
  13723. BestWidth = ShortWidth;
  13724. } else if (NumPositiveBits <= IntWidth) {
  13725. BestType = Context.UnsignedIntTy;
  13726. BestWidth = IntWidth;
  13727. BestPromotionType
  13728. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  13729. ? Context.UnsignedIntTy : Context.IntTy;
  13730. } else if (NumPositiveBits <=
  13731. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  13732. BestType = Context.UnsignedLongTy;
  13733. BestPromotionType
  13734. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  13735. ? Context.UnsignedLongTy : Context.LongTy;
  13736. } else {
  13737. BestWidth = Context.getTargetInfo().getLongLongWidth();
  13738. assert(NumPositiveBits <= BestWidth &&
  13739. "How could an initializer get larger than ULL?");
  13740. BestType = Context.UnsignedLongLongTy;
  13741. BestPromotionType
  13742. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  13743. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  13744. }
  13745. }
  13746. // Loop over all of the enumerator constants, changing their types to match
  13747. // the type of the enum if needed.
  13748. for (auto *D : Elements) {
  13749. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  13750. if (!ECD) continue; // Already issued a diagnostic.
  13751. // Standard C says the enumerators have int type, but we allow, as an
  13752. // extension, the enumerators to be larger than int size. If each
  13753. // enumerator value fits in an int, type it as an int, otherwise type it the
  13754. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  13755. // that X has type 'int', not 'unsigned'.
  13756. // Determine whether the value fits into an int.
  13757. llvm::APSInt InitVal = ECD->getInitVal();
  13758. // If it fits into an integer type, force it. Otherwise force it to match
  13759. // the enum decl type.
  13760. QualType NewTy;
  13761. unsigned NewWidth;
  13762. bool NewSign;
  13763. if (!getLangOpts().CPlusPlus &&
  13764. !Enum->isFixed() &&
  13765. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  13766. NewTy = Context.IntTy;
  13767. NewWidth = IntWidth;
  13768. NewSign = true;
  13769. } else if (ECD->getType() == BestType) {
  13770. // Already the right type!
  13771. if (getLangOpts().CPlusPlus)
  13772. // C++ [dcl.enum]p4: Following the closing brace of an
  13773. // enum-specifier, each enumerator has the type of its
  13774. // enumeration.
  13775. ECD->setType(EnumType);
  13776. continue;
  13777. } else {
  13778. NewTy = BestType;
  13779. NewWidth = BestWidth;
  13780. NewSign = BestType->isSignedIntegerOrEnumerationType();
  13781. }
  13782. // Adjust the APSInt value.
  13783. InitVal = InitVal.extOrTrunc(NewWidth);
  13784. InitVal.setIsSigned(NewSign);
  13785. ECD->setInitVal(InitVal);
  13786. // Adjust the Expr initializer and type.
  13787. if (ECD->getInitExpr() &&
  13788. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  13789. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  13790. CK_IntegralCast,
  13791. ECD->getInitExpr(),
  13792. /*base paths*/ nullptr,
  13793. VK_RValue));
  13794. if (getLangOpts().CPlusPlus)
  13795. // C++ [dcl.enum]p4: Following the closing brace of an
  13796. // enum-specifier, each enumerator has the type of its
  13797. // enumeration.
  13798. ECD->setType(EnumType);
  13799. else
  13800. ECD->setType(NewTy);
  13801. }
  13802. Enum->completeDefinition(BestType, BestPromotionType,
  13803. NumPositiveBits, NumNegativeBits);
  13804. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  13805. if (Enum->hasAttr<FlagEnumAttr>()) {
  13806. for (Decl *D : Elements) {
  13807. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  13808. if (!ECD) continue; // Already issued a diagnostic.
  13809. llvm::APSInt InitVal = ECD->getInitVal();
  13810. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  13811. !IsValueInFlagEnum(Enum, InitVal, true))
  13812. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  13813. << ECD << Enum;
  13814. }
  13815. }
  13816. // Now that the enum type is defined, ensure it's not been underaligned.
  13817. if (Enum->hasAttrs())
  13818. CheckAlignasUnderalignment(Enum);
  13819. }
  13820. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  13821. SourceLocation StartLoc,
  13822. SourceLocation EndLoc) {
  13823. StringLiteral *AsmString = cast<StringLiteral>(expr);
  13824. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  13825. AsmString, StartLoc,
  13826. EndLoc);
  13827. CurContext->addDecl(New);
  13828. return New;
  13829. }
  13830. static void checkModuleImportContext(Sema &S, Module *M,
  13831. SourceLocation ImportLoc, DeclContext *DC,
  13832. bool FromInclude = false) {
  13833. SourceLocation ExternCLoc;
  13834. if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
  13835. switch (LSD->getLanguage()) {
  13836. case LinkageSpecDecl::lang_c:
  13837. if (ExternCLoc.isInvalid())
  13838. ExternCLoc = LSD->getLocStart();
  13839. break;
  13840. case LinkageSpecDecl::lang_cxx:
  13841. break;
  13842. }
  13843. DC = LSD->getParent();
  13844. }
  13845. while (isa<LinkageSpecDecl>(DC))
  13846. DC = DC->getParent();
  13847. if (!isa<TranslationUnitDecl>(DC)) {
  13848. S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
  13849. ? diag::ext_module_import_not_at_top_level_noop
  13850. : diag::err_module_import_not_at_top_level_fatal)
  13851. << M->getFullModuleName() << DC;
  13852. S.Diag(cast<Decl>(DC)->getLocStart(),
  13853. diag::note_module_import_not_at_top_level) << DC;
  13854. } else if (!M->IsExternC && ExternCLoc.isValid()) {
  13855. S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
  13856. << M->getFullModuleName();
  13857. S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
  13858. }
  13859. }
  13860. Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc,
  13861. ModuleDeclKind MDK,
  13862. ModuleIdPath Path) {
  13863. // 'module implementation' requires that we are not compiling a module of any
  13864. // kind. 'module' and 'module partition' require that we are compiling a
  13865. // module inteface (not a module map).
  13866. auto CMK = getLangOpts().getCompilingModule();
  13867. if (MDK == ModuleDeclKind::Implementation
  13868. ? CMK != LangOptions::CMK_None
  13869. : CMK != LangOptions::CMK_ModuleInterface) {
  13870. Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
  13871. << (unsigned)MDK;
  13872. return nullptr;
  13873. }
  13874. // FIXME: Create a ModuleDecl and return it.
  13875. // FIXME: Most of this work should be done by the preprocessor rather than
  13876. // here, in case we look ahead across something where the current
  13877. // module matters (eg a #include).
  13878. // The dots in a module name in the Modules TS are a lie. Unlike Clang's
  13879. // hierarchical module map modules, the dots here are just another character
  13880. // that can appear in a module name. Flatten down to the actual module name.
  13881. std::string ModuleName;
  13882. for (auto &Piece : Path) {
  13883. if (!ModuleName.empty())
  13884. ModuleName += ".";
  13885. ModuleName += Piece.first->getName();
  13886. }
  13887. // If a module name was explicitly specified on the command line, it must be
  13888. // correct.
  13889. if (!getLangOpts().CurrentModule.empty() &&
  13890. getLangOpts().CurrentModule != ModuleName) {
  13891. Diag(Path.front().second, diag::err_current_module_name_mismatch)
  13892. << SourceRange(Path.front().second, Path.back().second)
  13893. << getLangOpts().CurrentModule;
  13894. return nullptr;
  13895. }
  13896. const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
  13897. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  13898. switch (MDK) {
  13899. case ModuleDeclKind::Module: {
  13900. // FIXME: Check we're not in a submodule.
  13901. // We can't have imported a definition of this module or parsed a module
  13902. // map defining it already.
  13903. if (auto *M = Map.findModule(ModuleName)) {
  13904. Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
  13905. if (M->DefinitionLoc.isValid())
  13906. Diag(M->DefinitionLoc, diag::note_prev_module_definition);
  13907. else if (const auto *FE = M->getASTFile())
  13908. Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
  13909. << FE->getName();
  13910. return nullptr;
  13911. }
  13912. // Create a Module for the module that we're defining.
  13913. Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
  13914. assert(Mod && "module creation should not fail");
  13915. // Enter the semantic scope of the module.
  13916. ActOnModuleBegin(ModuleLoc, Mod);
  13917. return nullptr;
  13918. }
  13919. case ModuleDeclKind::Partition:
  13920. // FIXME: Check we are in a submodule of the named module.
  13921. return nullptr;
  13922. case ModuleDeclKind::Implementation:
  13923. std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
  13924. PP.getIdentifierInfo(ModuleName), Path[0].second);
  13925. DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
  13926. if (Import.isInvalid())
  13927. return nullptr;
  13928. return ConvertDeclToDeclGroup(Import.get());
  13929. }
  13930. llvm_unreachable("unexpected module decl kind");
  13931. }
  13932. DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
  13933. SourceLocation ImportLoc,
  13934. ModuleIdPath Path) {
  13935. Module *Mod =
  13936. getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
  13937. /*IsIncludeDirective=*/false);
  13938. if (!Mod)
  13939. return true;
  13940. VisibleModules.setVisible(Mod, ImportLoc);
  13941. checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
  13942. // FIXME: we should support importing a submodule within a different submodule
  13943. // of the same top-level module. Until we do, make it an error rather than
  13944. // silently ignoring the import.
  13945. // Import-from-implementation is valid in the Modules TS. FIXME: Should we
  13946. // warn on a redundant import of the current module?
  13947. if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  13948. (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
  13949. Diag(ImportLoc, getLangOpts().isCompilingModule()
  13950. ? diag::err_module_self_import
  13951. : diag::err_module_import_in_implementation)
  13952. << Mod->getFullModuleName() << getLangOpts().CurrentModule;
  13953. SmallVector<SourceLocation, 2> IdentifierLocs;
  13954. Module *ModCheck = Mod;
  13955. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  13956. // If we've run out of module parents, just drop the remaining identifiers.
  13957. // We need the length to be consistent.
  13958. if (!ModCheck)
  13959. break;
  13960. ModCheck = ModCheck->Parent;
  13961. IdentifierLocs.push_back(Path[I].second);
  13962. }
  13963. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  13964. ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
  13965. Mod, IdentifierLocs);
  13966. if (!ModuleScopes.empty())
  13967. Context.addModuleInitializer(ModuleScopes.back().Module, Import);
  13968. TU->addDecl(Import);
  13969. return Import;
  13970. }
  13971. void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  13972. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  13973. BuildModuleInclude(DirectiveLoc, Mod);
  13974. }
  13975. void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  13976. // Determine whether we're in the #include buffer for a module. The #includes
  13977. // in that buffer do not qualify as module imports; they're just an
  13978. // implementation detail of us building the module.
  13979. //
  13980. // FIXME: Should we even get ActOnModuleInclude calls for those?
  13981. bool IsInModuleIncludes =
  13982. TUKind == TU_Module &&
  13983. getSourceManager().isWrittenInMainFile(DirectiveLoc);
  13984. bool ShouldAddImport = !IsInModuleIncludes;
  13985. // If this module import was due to an inclusion directive, create an
  13986. // implicit import declaration to capture it in the AST.
  13987. if (ShouldAddImport) {
  13988. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  13989. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  13990. DirectiveLoc, Mod,
  13991. DirectiveLoc);
  13992. if (!ModuleScopes.empty())
  13993. Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
  13994. TU->addDecl(ImportD);
  13995. Consumer.HandleImplicitImportDecl(ImportD);
  13996. }
  13997. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
  13998. VisibleModules.setVisible(Mod, DirectiveLoc);
  13999. }
  14000. void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
  14001. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  14002. ModuleScopes.push_back({});
  14003. ModuleScopes.back().Module = Mod;
  14004. if (getLangOpts().ModulesLocalVisibility)
  14005. ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
  14006. VisibleModules.setVisible(Mod, DirectiveLoc);
  14007. }
  14008. void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
  14009. if (getLangOpts().ModulesLocalVisibility) {
  14010. VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
  14011. // Leaving a module hides namespace names, so our visible namespace cache
  14012. // is now out of date.
  14013. VisibleNamespaceCache.clear();
  14014. }
  14015. assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
  14016. "left the wrong module scope");
  14017. ModuleScopes.pop_back();
  14018. // We got to the end of processing a #include of a local module. Create an
  14019. // ImportDecl as we would for an imported module.
  14020. FileID File = getSourceManager().getFileID(EofLoc);
  14021. assert(File != getSourceManager().getMainFileID() &&
  14022. "end of submodule in main source file");
  14023. SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
  14024. BuildModuleInclude(DirectiveLoc, Mod);
  14025. }
  14026. void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
  14027. Module *Mod) {
  14028. // Bail if we're not allowed to implicitly import a module here.
  14029. if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
  14030. return;
  14031. // Create the implicit import declaration.
  14032. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  14033. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  14034. Loc, Mod, Loc);
  14035. TU->addDecl(ImportD);
  14036. Consumer.HandleImplicitImportDecl(ImportD);
  14037. // Make the module visible.
  14038. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
  14039. VisibleModules.setVisible(Mod, Loc);
  14040. }
  14041. /// We have parsed the start of an export declaration, including the '{'
  14042. /// (if present).
  14043. Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
  14044. SourceLocation LBraceLoc) {
  14045. ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
  14046. // C++ Modules TS draft:
  14047. // An export-declaration [...] shall not contain more than one
  14048. // export keyword.
  14049. //
  14050. // The intent here is that an export-declaration cannot appear within another
  14051. // export-declaration.
  14052. if (D->isExported())
  14053. Diag(ExportLoc, diag::err_export_within_export);
  14054. CurContext->addDecl(D);
  14055. PushDeclContext(S, D);
  14056. return D;
  14057. }
  14058. /// Complete the definition of an export declaration.
  14059. Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
  14060. auto *ED = cast<ExportDecl>(D);
  14061. if (RBraceLoc.isValid())
  14062. ED->setRBraceLoc(RBraceLoc);
  14063. // FIXME: Diagnose export of internal-linkage declaration (including
  14064. // anonymous namespace).
  14065. PopDeclContext();
  14066. return D;
  14067. }
  14068. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  14069. IdentifierInfo* AliasName,
  14070. SourceLocation PragmaLoc,
  14071. SourceLocation NameLoc,
  14072. SourceLocation AliasNameLoc) {
  14073. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  14074. LookupOrdinaryName);
  14075. AsmLabelAttr *Attr =
  14076. AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
  14077. // If a declaration that:
  14078. // 1) declares a function or a variable
  14079. // 2) has external linkage
  14080. // already exists, add a label attribute to it.
  14081. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  14082. if (isDeclExternC(PrevDecl))
  14083. PrevDecl->addAttr(Attr);
  14084. else
  14085. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  14086. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  14087. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  14088. } else
  14089. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  14090. }
  14091. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  14092. SourceLocation PragmaLoc,
  14093. SourceLocation NameLoc) {
  14094. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  14095. if (PrevDecl) {
  14096. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  14097. } else {
  14098. (void)WeakUndeclaredIdentifiers.insert(
  14099. std::pair<IdentifierInfo*,WeakInfo>
  14100. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  14101. }
  14102. }
  14103. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  14104. IdentifierInfo* AliasName,
  14105. SourceLocation PragmaLoc,
  14106. SourceLocation NameLoc,
  14107. SourceLocation AliasNameLoc) {
  14108. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  14109. LookupOrdinaryName);
  14110. WeakInfo W = WeakInfo(Name, NameLoc);
  14111. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  14112. if (!PrevDecl->hasAttr<AliasAttr>())
  14113. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  14114. DeclApplyPragmaWeak(TUScope, ND, W);
  14115. } else {
  14116. (void)WeakUndeclaredIdentifiers.insert(
  14117. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  14118. }
  14119. }
  14120. Decl *Sema::getObjCDeclContext() const {
  14121. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  14122. }