SemaDecl.cpp 654 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869
  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. bool AllowNonTemplates = true)
  64. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  65. AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
  66. WantExpressionKeywords = false;
  67. WantCXXNamedCasts = false;
  68. WantRemainingKeywords = false;
  69. }
  70. bool ValidateCandidate(const TypoCorrection &candidate) override {
  71. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  72. if (!AllowInvalidDecl && ND->isInvalidDecl())
  73. return false;
  74. if (getAsTypeTemplateDecl(ND))
  75. return AllowTemplates;
  76. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  77. if (!IsType)
  78. return false;
  79. if (AllowNonTemplates)
  80. return true;
  81. // An injected-class-name of a class template (specialization) is valid
  82. // as a template or as a non-template.
  83. if (AllowTemplates) {
  84. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  85. if (!RD || !RD->isInjectedClassName())
  86. return false;
  87. RD = cast<CXXRecordDecl>(RD->getDeclContext());
  88. return RD->getDescribedClassTemplate() ||
  89. isa<ClassTemplateSpecializationDecl>(RD);
  90. }
  91. return false;
  92. }
  93. return !WantClassName && candidate.isKeyword();
  94. }
  95. private:
  96. bool AllowInvalidDecl;
  97. bool WantClassName;
  98. bool AllowTemplates;
  99. bool AllowNonTemplates;
  100. };
  101. } // end anonymous namespace
  102. /// \brief Determine whether the token kind starts a simple-type-specifier.
  103. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  104. switch (Kind) {
  105. // FIXME: Take into account the current language when deciding whether a
  106. // token kind is a valid type specifier
  107. case tok::kw_short:
  108. case tok::kw_long:
  109. case tok::kw___int64:
  110. case tok::kw___int128:
  111. case tok::kw_signed:
  112. case tok::kw_unsigned:
  113. case tok::kw_void:
  114. case tok::kw_char:
  115. case tok::kw_int:
  116. case tok::kw_half:
  117. case tok::kw_float:
  118. case tok::kw_double:
  119. case tok::kw__Float16:
  120. case tok::kw___float128:
  121. case tok::kw_wchar_t:
  122. case tok::kw_bool:
  123. case tok::kw___underlying_type:
  124. case tok::kw___auto_type:
  125. return true;
  126. case tok::annot_typename:
  127. case tok::kw_char16_t:
  128. case tok::kw_char32_t:
  129. case tok::kw_typeof:
  130. case tok::annot_decltype:
  131. case tok::kw_decltype:
  132. return getLangOpts().CPlusPlus;
  133. default:
  134. break;
  135. }
  136. return false;
  137. }
  138. namespace {
  139. enum class UnqualifiedTypeNameLookupResult {
  140. NotFound,
  141. FoundNonType,
  142. FoundType
  143. };
  144. } // end anonymous namespace
  145. /// \brief Tries to perform unqualified lookup of the type decls in bases for
  146. /// dependent class.
  147. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  148. /// type decl, \a FoundType if only type decls are found.
  149. static UnqualifiedTypeNameLookupResult
  150. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  151. SourceLocation NameLoc,
  152. const CXXRecordDecl *RD) {
  153. if (!RD->hasDefinition())
  154. return UnqualifiedTypeNameLookupResult::NotFound;
  155. // Look for type decls in base classes.
  156. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  157. UnqualifiedTypeNameLookupResult::NotFound;
  158. for (const auto &Base : RD->bases()) {
  159. const CXXRecordDecl *BaseRD = nullptr;
  160. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  161. BaseRD = BaseTT->getAsCXXRecordDecl();
  162. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  163. // Look for type decls in dependent base classes that have known primary
  164. // templates.
  165. if (!TST || !TST->isDependentType())
  166. continue;
  167. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  168. if (!TD)
  169. continue;
  170. if (auto *BasePrimaryTemplate =
  171. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
  172. if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
  173. BaseRD = BasePrimaryTemplate;
  174. else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
  175. if (const ClassTemplatePartialSpecializationDecl *PS =
  176. CTD->findPartialSpecialization(Base.getType()))
  177. if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
  178. BaseRD = PS;
  179. }
  180. }
  181. }
  182. if (BaseRD) {
  183. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  184. if (!isa<TypeDecl>(ND))
  185. return UnqualifiedTypeNameLookupResult::FoundNonType;
  186. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  187. }
  188. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  189. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  190. case UnqualifiedTypeNameLookupResult::FoundNonType:
  191. return UnqualifiedTypeNameLookupResult::FoundNonType;
  192. case UnqualifiedTypeNameLookupResult::FoundType:
  193. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  194. break;
  195. case UnqualifiedTypeNameLookupResult::NotFound:
  196. break;
  197. }
  198. }
  199. }
  200. }
  201. return FoundTypeDecl;
  202. }
  203. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  204. const IdentifierInfo &II,
  205. SourceLocation NameLoc) {
  206. // Lookup in the parent class template context, if any.
  207. const CXXRecordDecl *RD = nullptr;
  208. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  209. UnqualifiedTypeNameLookupResult::NotFound;
  210. for (DeclContext *DC = S.CurContext;
  211. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  212. DC = DC->getParent()) {
  213. // Look for type decls in dependent base classes that have known primary
  214. // templates.
  215. RD = dyn_cast<CXXRecordDecl>(DC);
  216. if (RD && RD->getDescribedClassTemplate())
  217. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  218. }
  219. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  220. return nullptr;
  221. // We found some types in dependent base classes. Recover as if the user
  222. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  223. // lookup during template instantiation.
  224. S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
  225. ASTContext &Context = S.Context;
  226. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  227. cast<Type>(Context.getRecordType(RD)));
  228. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  229. CXXScopeSpec SS;
  230. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  231. TypeLocBuilder Builder;
  232. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  233. DepTL.setNameLoc(NameLoc);
  234. DepTL.setElaboratedKeywordLoc(SourceLocation());
  235. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  236. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  237. }
  238. /// \brief If the identifier refers to a type name within this scope,
  239. /// return the declaration of that type.
  240. ///
  241. /// This routine performs ordinary name lookup of the identifier II
  242. /// within the given scope, with optional C++ scope specifier SS, to
  243. /// determine whether the name refers to a type. If so, returns an
  244. /// opaque pointer (actually a QualType) corresponding to that
  245. /// type. Otherwise, returns NULL.
  246. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  247. Scope *S, CXXScopeSpec *SS,
  248. bool isClassName, bool HasTrailingDot,
  249. ParsedType ObjectTypePtr,
  250. bool IsCtorOrDtorName,
  251. bool WantNontrivialTypeSourceInfo,
  252. bool IsClassTemplateDeductionContext,
  253. IdentifierInfo **CorrectedII) {
  254. // FIXME: Consider allowing this outside C++1z mode as an extension.
  255. bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
  256. getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
  257. !isClassName && !HasTrailingDot;
  258. // Determine where we will perform name lookup.
  259. DeclContext *LookupCtx = nullptr;
  260. if (ObjectTypePtr) {
  261. QualType ObjectType = ObjectTypePtr.get();
  262. if (ObjectType->isRecordType())
  263. LookupCtx = computeDeclContext(ObjectType);
  264. } else if (SS && SS->isNotEmpty()) {
  265. LookupCtx = computeDeclContext(*SS, false);
  266. if (!LookupCtx) {
  267. if (isDependentScopeSpecifier(*SS)) {
  268. // C++ [temp.res]p3:
  269. // A qualified-id that refers to a type and in which the
  270. // nested-name-specifier depends on a template-parameter (14.6.2)
  271. // shall be prefixed by the keyword typename to indicate that the
  272. // qualified-id denotes a type, forming an
  273. // elaborated-type-specifier (7.1.5.3).
  274. //
  275. // We therefore do not perform any name lookup if the result would
  276. // refer to a member of an unknown specialization.
  277. if (!isClassName && !IsCtorOrDtorName)
  278. return nullptr;
  279. // We know from the grammar that this name refers to a type,
  280. // so build a dependent node to describe the type.
  281. if (WantNontrivialTypeSourceInfo)
  282. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  283. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  284. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  285. II, NameLoc);
  286. return ParsedType::make(T);
  287. }
  288. return nullptr;
  289. }
  290. if (!LookupCtx->isDependentContext() &&
  291. RequireCompleteDeclContext(*SS, LookupCtx))
  292. return nullptr;
  293. }
  294. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  295. // lookup for class-names.
  296. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  297. LookupOrdinaryName;
  298. LookupResult Result(*this, &II, NameLoc, Kind);
  299. if (LookupCtx) {
  300. // Perform "qualified" name lookup into the declaration context we
  301. // computed, which is either the type of the base of a member access
  302. // expression or the declaration context associated with a prior
  303. // nested-name-specifier.
  304. LookupQualifiedName(Result, LookupCtx);
  305. if (ObjectTypePtr && Result.empty()) {
  306. // C++ [basic.lookup.classref]p3:
  307. // If the unqualified-id is ~type-name, the type-name is looked up
  308. // in the context of the entire postfix-expression. If the type T of
  309. // the object expression is of a class type C, the type-name is also
  310. // looked up in the scope of class C. At least one of the lookups shall
  311. // find a name that refers to (possibly cv-qualified) T.
  312. LookupName(Result, S);
  313. }
  314. } else {
  315. // Perform unqualified name lookup.
  316. LookupName(Result, S);
  317. // For unqualified lookup in a class template in MSVC mode, look into
  318. // dependent base classes where the primary class template is known.
  319. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  320. if (ParsedType TypeInBase =
  321. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  322. return TypeInBase;
  323. }
  324. }
  325. NamedDecl *IIDecl = nullptr;
  326. switch (Result.getResultKind()) {
  327. case LookupResult::NotFound:
  328. case LookupResult::NotFoundInCurrentInstantiation:
  329. if (CorrectedII) {
  330. TypoCorrection Correction =
  331. CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
  332. llvm::make_unique<TypeNameValidatorCCC>(
  333. true, isClassName, AllowDeducedTemplate),
  334. CTK_ErrorRecovery);
  335. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  336. TemplateTy Template;
  337. bool MemberOfUnknownSpecialization;
  338. UnqualifiedId TemplateName;
  339. TemplateName.setIdentifier(NewII, NameLoc);
  340. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  341. CXXScopeSpec NewSS, *NewSSPtr = SS;
  342. if (SS && NNS) {
  343. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  344. NewSSPtr = &NewSS;
  345. }
  346. if (Correction && (NNS || NewII != &II) &&
  347. // Ignore a correction to a template type as the to-be-corrected
  348. // identifier is not a template (typo correction for template names
  349. // is handled elsewhere).
  350. !(getLangOpts().CPlusPlus && NewSSPtr &&
  351. isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
  352. Template, MemberOfUnknownSpecialization))) {
  353. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  354. isClassName, HasTrailingDot, ObjectTypePtr,
  355. IsCtorOrDtorName,
  356. WantNontrivialTypeSourceInfo,
  357. IsClassTemplateDeductionContext);
  358. if (Ty) {
  359. diagnoseTypo(Correction,
  360. PDiag(diag::err_unknown_type_or_class_name_suggest)
  361. << Result.getLookupName() << isClassName);
  362. if (SS && NNS)
  363. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  364. *CorrectedII = NewII;
  365. return Ty;
  366. }
  367. }
  368. }
  369. // If typo correction failed or was not performed, fall through
  370. LLVM_FALLTHROUGH;
  371. case LookupResult::FoundOverloaded:
  372. case LookupResult::FoundUnresolvedValue:
  373. Result.suppressDiagnostics();
  374. return nullptr;
  375. case LookupResult::Ambiguous:
  376. // Recover from type-hiding ambiguities by hiding the type. We'll
  377. // do the lookup again when looking for an object, and we can
  378. // diagnose the error then. If we don't do this, then the error
  379. // about hiding the type will be immediately followed by an error
  380. // that only makes sense if the identifier was treated like a type.
  381. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  382. Result.suppressDiagnostics();
  383. return nullptr;
  384. }
  385. // Look to see if we have a type anywhere in the list of results.
  386. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  387. Res != ResEnd; ++Res) {
  388. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
  389. (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
  390. if (!IIDecl ||
  391. (*Res)->getLocation().getRawEncoding() <
  392. IIDecl->getLocation().getRawEncoding())
  393. IIDecl = *Res;
  394. }
  395. }
  396. if (!IIDecl) {
  397. // None of the entities we found is a type, so there is no way
  398. // to even assume that the result is a type. In this case, don't
  399. // complain about the ambiguity. The parser will either try to
  400. // perform this lookup again (e.g., as an object name), which
  401. // will produce the ambiguity, or will complain that it expected
  402. // a type name.
  403. Result.suppressDiagnostics();
  404. return nullptr;
  405. }
  406. // We found a type within the ambiguous lookup; diagnose the
  407. // ambiguity and then return that type. This might be the right
  408. // answer, or it might not be, but it suppresses any attempt to
  409. // perform the name lookup again.
  410. break;
  411. case LookupResult::Found:
  412. IIDecl = Result.getFoundDecl();
  413. break;
  414. }
  415. assert(IIDecl && "Didn't find decl");
  416. QualType T;
  417. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  418. // C++ [class.qual]p2: A lookup that would find the injected-class-name
  419. // instead names the constructors of the class, except when naming a class.
  420. // This is ill-formed when we're not actually forming a ctor or dtor name.
  421. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  422. auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
  423. if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
  424. FoundRD->isInjectedClassName() &&
  425. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  426. Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
  427. << &II << /*Type*/1;
  428. DiagnoseUseOfDecl(IIDecl, NameLoc);
  429. T = Context.getTypeDeclType(TD);
  430. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  431. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  432. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  433. if (!HasTrailingDot)
  434. T = Context.getObjCInterfaceType(IDecl);
  435. } else if (AllowDeducedTemplate) {
  436. if (auto *TD = getAsTypeTemplateDecl(IIDecl))
  437. T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  438. QualType(), false);
  439. }
  440. if (T.isNull()) {
  441. // If it's not plausibly a type, suppress diagnostics.
  442. Result.suppressDiagnostics();
  443. return nullptr;
  444. }
  445. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  446. // constructor or destructor name (in such a case, the scope specifier
  447. // will be attached to the enclosing Expr or Decl node).
  448. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
  449. !isa<ObjCInterfaceDecl>(IIDecl)) {
  450. if (WantNontrivialTypeSourceInfo) {
  451. // Construct a type with type-source information.
  452. TypeLocBuilder Builder;
  453. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  454. T = getElaboratedType(ETK_None, *SS, T);
  455. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  456. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  457. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  458. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  459. } else {
  460. T = getElaboratedType(ETK_None, *SS, T);
  461. }
  462. }
  463. return ParsedType::make(T);
  464. }
  465. // Builds a fake NNS for the given decl context.
  466. static NestedNameSpecifier *
  467. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  468. for (;; DC = DC->getLookupParent()) {
  469. DC = DC->getPrimaryContext();
  470. auto *ND = dyn_cast<NamespaceDecl>(DC);
  471. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  472. return NestedNameSpecifier::Create(Context, nullptr, ND);
  473. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  474. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  475. RD->getTypeForDecl());
  476. else if (isa<TranslationUnitDecl>(DC))
  477. return NestedNameSpecifier::GlobalSpecifier(Context);
  478. }
  479. llvm_unreachable("something isn't in TU scope?");
  480. }
  481. /// Find the parent class with dependent bases of the innermost enclosing method
  482. /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
  483. /// up allowing unqualified dependent type names at class-level, which MSVC
  484. /// correctly rejects.
  485. static const CXXRecordDecl *
  486. findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
  487. for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
  488. DC = DC->getPrimaryContext();
  489. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  490. if (MD->getParent()->hasAnyDependentBases())
  491. return MD->getParent();
  492. }
  493. return nullptr;
  494. }
  495. ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
  496. SourceLocation NameLoc,
  497. bool IsTemplateTypeArg) {
  498. assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
  499. NestedNameSpecifier *NNS = nullptr;
  500. if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
  501. // If we weren't able to parse a default template argument, delay lookup
  502. // until instantiation time by making a non-dependent DependentTypeName. We
  503. // pretend we saw a NestedNameSpecifier referring to the current scope, and
  504. // lookup is retried.
  505. // FIXME: This hurts our diagnostic quality, since we get errors like "no
  506. // type named 'Foo' in 'current_namespace'" when the user didn't write any
  507. // name specifiers.
  508. NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  509. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  510. } else if (const CXXRecordDecl *RD =
  511. findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
  512. // Build a DependentNameType that will perform lookup into RD at
  513. // instantiation time.
  514. NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  515. RD->getTypeForDecl());
  516. // Diagnose that this identifier was undeclared, and retry the lookup during
  517. // template instantiation.
  518. Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
  519. << RD;
  520. } else {
  521. // This is not a situation that we should recover from.
  522. return ParsedType();
  523. }
  524. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  525. // Build type location information. We synthesized the qualifier, so we have
  526. // to build a fake NestedNameSpecifierLoc.
  527. NestedNameSpecifierLocBuilder NNSLocBuilder;
  528. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  529. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  530. TypeLocBuilder Builder;
  531. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  532. DepTL.setNameLoc(NameLoc);
  533. DepTL.setElaboratedKeywordLoc(SourceLocation());
  534. DepTL.setQualifierLoc(QualifierLoc);
  535. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  536. }
  537. /// isTagName() - This method is called *for error recovery purposes only*
  538. /// to determine if the specified name is a valid tag name ("struct foo"). If
  539. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  540. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  541. /// cases in C where the user forgot to specify the tag.
  542. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  543. // Do a tag name lookup in this scope.
  544. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  545. LookupName(R, S, false);
  546. R.suppressDiagnostics();
  547. if (R.getResultKind() == LookupResult::Found)
  548. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  549. switch (TD->getTagKind()) {
  550. case TTK_Struct: return DeclSpec::TST_struct;
  551. case TTK_Interface: return DeclSpec::TST_interface;
  552. case TTK_Union: return DeclSpec::TST_union;
  553. case TTK_Class: return DeclSpec::TST_class;
  554. case TTK_Enum: return DeclSpec::TST_enum;
  555. }
  556. }
  557. return DeclSpec::TST_unspecified;
  558. }
  559. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  560. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  561. /// then downgrade the missing typename error to a warning.
  562. /// This is needed for MSVC compatibility; Example:
  563. /// @code
  564. /// template<class T> class A {
  565. /// public:
  566. /// typedef int TYPE;
  567. /// };
  568. /// template<class T> class B : public A<T> {
  569. /// public:
  570. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  571. /// };
  572. /// @endcode
  573. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  574. if (CurContext->isRecord()) {
  575. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  576. return true;
  577. const Type *Ty = SS->getScopeRep()->getAsType();
  578. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  579. for (const auto &Base : RD->bases())
  580. if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  581. return true;
  582. return S->isFunctionPrototypeScope();
  583. }
  584. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  585. }
  586. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  587. SourceLocation IILoc,
  588. Scope *S,
  589. CXXScopeSpec *SS,
  590. ParsedType &SuggestedType,
  591. bool IsTemplateName) {
  592. // Don't report typename errors for editor placeholders.
  593. if (II->isEditorPlaceholder())
  594. return;
  595. // We don't have anything to suggest (yet).
  596. SuggestedType = nullptr;
  597. // There may have been a typo in the name of the type. Look up typo
  598. // results, in case we have something that we can suggest.
  599. if (TypoCorrection Corrected =
  600. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  601. llvm::make_unique<TypeNameValidatorCCC>(
  602. false, false, IsTemplateName, !IsTemplateName),
  603. CTK_ErrorRecovery)) {
  604. // FIXME: Support error recovery for the template-name case.
  605. bool CanRecover = !IsTemplateName;
  606. if (Corrected.isKeyword()) {
  607. // We corrected to a keyword.
  608. diagnoseTypo(Corrected,
  609. PDiag(IsTemplateName ? diag::err_no_template_suggest
  610. : diag::err_unknown_typename_suggest)
  611. << II);
  612. II = Corrected.getCorrectionAsIdentifierInfo();
  613. } else {
  614. // We found a similarly-named type or interface; suggest that.
  615. if (!SS || !SS->isSet()) {
  616. diagnoseTypo(Corrected,
  617. PDiag(IsTemplateName ? diag::err_no_template_suggest
  618. : diag::err_unknown_typename_suggest)
  619. << II, CanRecover);
  620. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  621. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  622. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  623. II->getName().equals(CorrectedStr);
  624. diagnoseTypo(Corrected,
  625. PDiag(IsTemplateName
  626. ? diag::err_no_member_template_suggest
  627. : diag::err_unknown_nested_typename_suggest)
  628. << II << DC << DroppedSpecifier << SS->getRange(),
  629. CanRecover);
  630. } else {
  631. llvm_unreachable("could not have corrected a typo here");
  632. }
  633. if (!CanRecover)
  634. return;
  635. CXXScopeSpec tmpSS;
  636. if (Corrected.getCorrectionSpecifier())
  637. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  638. SourceRange(IILoc));
  639. // FIXME: Support class template argument deduction here.
  640. SuggestedType =
  641. getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
  642. tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
  643. /*IsCtorOrDtorName=*/false,
  644. /*NonTrivialTypeSourceInfo=*/true);
  645. }
  646. return;
  647. }
  648. if (getLangOpts().CPlusPlus && !IsTemplateName) {
  649. // See if II is a class template that the user forgot to pass arguments to.
  650. UnqualifiedId Name;
  651. Name.setIdentifier(II, IILoc);
  652. CXXScopeSpec EmptySS;
  653. TemplateTy TemplateResult;
  654. bool MemberOfUnknownSpecialization;
  655. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  656. Name, nullptr, true, TemplateResult,
  657. MemberOfUnknownSpecialization) == TNK_Type_template) {
  658. diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
  659. return;
  660. }
  661. }
  662. // FIXME: Should we move the logic that tries to recover from a missing tag
  663. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  664. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  665. Diag(IILoc, IsTemplateName ? diag::err_no_template
  666. : diag::err_unknown_typename)
  667. << II;
  668. else if (DeclContext *DC = computeDeclContext(*SS, false))
  669. Diag(IILoc, IsTemplateName ? diag::err_no_member_template
  670. : diag::err_typename_nested_not_found)
  671. << II << DC << SS->getRange();
  672. else if (isDependentScopeSpecifier(*SS)) {
  673. unsigned DiagID = diag::err_typename_missing;
  674. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  675. DiagID = diag::ext_typename_missing;
  676. Diag(SS->getRange().getBegin(), DiagID)
  677. << SS->getScopeRep() << II->getName()
  678. << SourceRange(SS->getRange().getBegin(), IILoc)
  679. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  680. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  681. *SS, *II, IILoc).get();
  682. } else {
  683. assert(SS && SS->isInvalid() &&
  684. "Invalid scope specifier has already been diagnosed");
  685. }
  686. }
  687. /// \brief Determine whether the given result set contains either a type name
  688. /// or
  689. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  690. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  691. NextToken.is(tok::less);
  692. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  693. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  694. return true;
  695. if (CheckTemplate && isa<TemplateDecl>(*I))
  696. return true;
  697. }
  698. return false;
  699. }
  700. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  701. Scope *S, CXXScopeSpec &SS,
  702. IdentifierInfo *&Name,
  703. SourceLocation NameLoc) {
  704. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  705. SemaRef.LookupParsedName(R, S, &SS);
  706. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  707. StringRef FixItTagName;
  708. switch (Tag->getTagKind()) {
  709. case TTK_Class:
  710. FixItTagName = "class ";
  711. break;
  712. case TTK_Enum:
  713. FixItTagName = "enum ";
  714. break;
  715. case TTK_Struct:
  716. FixItTagName = "struct ";
  717. break;
  718. case TTK_Interface:
  719. FixItTagName = "__interface ";
  720. break;
  721. case TTK_Union:
  722. FixItTagName = "union ";
  723. break;
  724. }
  725. StringRef TagName = FixItTagName.drop_back();
  726. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  727. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  728. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  729. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  730. I != IEnd; ++I)
  731. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  732. << Name << TagName;
  733. // Replace lookup results with just the tag decl.
  734. Result.clear(Sema::LookupTagName);
  735. SemaRef.LookupParsedName(Result, S, &SS);
  736. return true;
  737. }
  738. return false;
  739. }
  740. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  741. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  742. QualType T, SourceLocation NameLoc) {
  743. ASTContext &Context = S.Context;
  744. TypeLocBuilder Builder;
  745. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  746. T = S.getElaboratedType(ETK_None, SS, T);
  747. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  748. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  749. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  750. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  751. }
  752. Sema::NameClassification
  753. Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
  754. SourceLocation NameLoc, const Token &NextToken,
  755. bool IsAddressOfOperand,
  756. std::unique_ptr<CorrectionCandidateCallback> CCC) {
  757. DeclarationNameInfo NameInfo(Name, NameLoc);
  758. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  759. if (NextToken.is(tok::coloncolon)) {
  760. NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
  761. BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
  762. } else if (getLangOpts().CPlusPlus && SS.isSet() &&
  763. isCurrentClassName(*Name, S, &SS)) {
  764. // Per [class.qual]p2, this names the constructors of SS, not the
  765. // injected-class-name. We don't have a classification for that.
  766. // There's not much point caching this result, since the parser
  767. // will reject it later.
  768. return NameClassification::Unknown();
  769. }
  770. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  771. LookupParsedName(Result, S, &SS, !CurMethod);
  772. // For unqualified lookup in a class template in MSVC mode, look into
  773. // dependent base classes where the primary class template is known.
  774. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  775. if (ParsedType TypeInBase =
  776. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  777. return TypeInBase;
  778. }
  779. // Perform lookup for Objective-C instance variables (including automatically
  780. // synthesized instance variables), if we're in an Objective-C method.
  781. // FIXME: This lookup really, really needs to be folded in to the normal
  782. // unqualified lookup mechanism.
  783. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  784. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  785. if (E.get() || E.isInvalid())
  786. return E;
  787. }
  788. bool SecondTry = false;
  789. bool IsFilteredTemplateName = false;
  790. Corrected:
  791. switch (Result.getResultKind()) {
  792. case LookupResult::NotFound:
  793. // If an unqualified-id is followed by a '(', then we have a function
  794. // call.
  795. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  796. // In C++, this is an ADL-only call.
  797. // FIXME: Reference?
  798. if (getLangOpts().CPlusPlus)
  799. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  800. // C90 6.3.2.2:
  801. // If the expression that precedes the parenthesized argument list in a
  802. // function call consists solely of an identifier, and if no
  803. // declaration is visible for this identifier, the identifier is
  804. // implicitly declared exactly as if, in the innermost block containing
  805. // the function call, the declaration
  806. //
  807. // extern int identifier ();
  808. //
  809. // appeared.
  810. //
  811. // We also allow this in C99 as an extension.
  812. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  813. Result.addDecl(D);
  814. Result.resolveKind();
  815. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  816. }
  817. }
  818. // In C, we first see whether there is a tag type by the same name, in
  819. // which case it's likely that the user just forgot to write "enum",
  820. // "struct", or "union".
  821. if (!getLangOpts().CPlusPlus && !SecondTry &&
  822. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  823. break;
  824. }
  825. // Perform typo correction to determine if there is another name that is
  826. // close to this name.
  827. if (!SecondTry && CCC) {
  828. SecondTry = true;
  829. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  830. Result.getLookupKind(), S,
  831. &SS, std::move(CCC),
  832. CTK_ErrorRecovery)) {
  833. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  834. unsigned QualifiedDiag = diag::err_no_member_suggest;
  835. NamedDecl *FirstDecl = Corrected.getFoundDecl();
  836. NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
  837. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  838. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  839. UnqualifiedDiag = diag::err_no_template_suggest;
  840. QualifiedDiag = diag::err_no_member_template_suggest;
  841. } else if (UnderlyingFirstDecl &&
  842. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  843. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  844. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  845. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  846. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  847. }
  848. if (SS.isEmpty()) {
  849. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  850. } else {// FIXME: is this even reachable? Test it.
  851. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  852. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  853. Name->getName().equals(CorrectedStr);
  854. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  855. << Name << computeDeclContext(SS, false)
  856. << DroppedSpecifier << SS.getRange());
  857. }
  858. // Update the name, so that the caller has the new name.
  859. Name = Corrected.getCorrectionAsIdentifierInfo();
  860. // Typo correction corrected to a keyword.
  861. if (Corrected.isKeyword())
  862. return Name;
  863. // Also update the LookupResult...
  864. // FIXME: This should probably go away at some point
  865. Result.clear();
  866. Result.setLookupName(Corrected.getCorrection());
  867. if (FirstDecl)
  868. Result.addDecl(FirstDecl);
  869. // If we found an Objective-C instance variable, let
  870. // LookupInObjCMethod build the appropriate expression to
  871. // reference the ivar.
  872. // FIXME: This is a gross hack.
  873. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  874. Result.clear();
  875. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  876. return E;
  877. }
  878. goto Corrected;
  879. }
  880. }
  881. // We failed to correct; just fall through and let the parser deal with it.
  882. Result.suppressDiagnostics();
  883. return NameClassification::Unknown();
  884. case LookupResult::NotFoundInCurrentInstantiation: {
  885. // We performed name lookup into the current instantiation, and there were
  886. // dependent bases, so we treat this result the same way as any other
  887. // dependent nested-name-specifier.
  888. // C++ [temp.res]p2:
  889. // A name used in a template declaration or definition and that is
  890. // dependent on a template-parameter is assumed not to name a type
  891. // unless the applicable name lookup finds a type name or the name is
  892. // qualified by the keyword typename.
  893. //
  894. // FIXME: If the next token is '<', we might want to ask the parser to
  895. // perform some heroics to see if we actually have a
  896. // template-argument-list, which would indicate a missing 'template'
  897. // keyword here.
  898. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  899. NameInfo, IsAddressOfOperand,
  900. /*TemplateArgs=*/nullptr);
  901. }
  902. case LookupResult::Found:
  903. case LookupResult::FoundOverloaded:
  904. case LookupResult::FoundUnresolvedValue:
  905. break;
  906. case LookupResult::Ambiguous:
  907. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  908. hasAnyAcceptableTemplateNames(Result)) {
  909. // C++ [temp.local]p3:
  910. // A lookup that finds an injected-class-name (10.2) can result in an
  911. // ambiguity in certain cases (for example, if it is found in more than
  912. // one base class). If all of the injected-class-names that are found
  913. // refer to specializations of the same class template, and if the name
  914. // is followed by a template-argument-list, the reference refers to the
  915. // class template itself and not a specialization thereof, and is not
  916. // ambiguous.
  917. //
  918. // This filtering can make an ambiguous result into an unambiguous one,
  919. // so try again after filtering out template names.
  920. FilterAcceptableTemplateNames(Result);
  921. if (!Result.isAmbiguous()) {
  922. IsFilteredTemplateName = true;
  923. break;
  924. }
  925. }
  926. // Diagnose the ambiguity and return an error.
  927. return NameClassification::Error();
  928. }
  929. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  930. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  931. // C++ [temp.names]p3:
  932. // After name lookup (3.4) finds that a name is a template-name or that
  933. // an operator-function-id or a literal- operator-id refers to a set of
  934. // overloaded functions any member of which is a function template if
  935. // this is followed by a <, the < is always taken as the delimiter of a
  936. // template-argument-list and never as the less-than operator.
  937. if (!IsFilteredTemplateName)
  938. FilterAcceptableTemplateNames(Result);
  939. if (!Result.empty()) {
  940. bool IsFunctionTemplate;
  941. bool IsVarTemplate;
  942. TemplateName Template;
  943. if (Result.end() - Result.begin() > 1) {
  944. IsFunctionTemplate = true;
  945. Template = Context.getOverloadedTemplateName(Result.begin(),
  946. Result.end());
  947. } else {
  948. TemplateDecl *TD
  949. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  950. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  951. IsVarTemplate = isa<VarTemplateDecl>(TD);
  952. if (SS.isSet() && !SS.isInvalid())
  953. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  954. /*TemplateKeyword=*/false,
  955. TD);
  956. else
  957. Template = TemplateName(TD);
  958. }
  959. if (IsFunctionTemplate) {
  960. // Function templates always go through overload resolution, at which
  961. // point we'll perform the various checks (e.g., accessibility) we need
  962. // to based on which function we selected.
  963. Result.suppressDiagnostics();
  964. return NameClassification::FunctionTemplate(Template);
  965. }
  966. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  967. : NameClassification::TypeTemplate(Template);
  968. }
  969. }
  970. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  971. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  972. DiagnoseUseOfDecl(Type, NameLoc);
  973. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  974. QualType T = Context.getTypeDeclType(Type);
  975. if (SS.isNotEmpty())
  976. return buildNestedType(*this, SS, T, NameLoc);
  977. return ParsedType::make(T);
  978. }
  979. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  980. if (!Class) {
  981. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  982. if (ObjCCompatibleAliasDecl *Alias =
  983. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  984. Class = Alias->getClassInterface();
  985. }
  986. if (Class) {
  987. DiagnoseUseOfDecl(Class, NameLoc);
  988. if (NextToken.is(tok::period)) {
  989. // Interface. <something> is parsed as a property reference expression.
  990. // Just return "unknown" as a fall-through for now.
  991. Result.suppressDiagnostics();
  992. return NameClassification::Unknown();
  993. }
  994. QualType T = Context.getObjCInterfaceType(Class);
  995. return ParsedType::make(T);
  996. }
  997. // We can have a type template here if we're classifying a template argument.
  998. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
  999. !isa<VarTemplateDecl>(FirstDecl))
  1000. return NameClassification::TypeTemplate(
  1001. TemplateName(cast<TemplateDecl>(FirstDecl)));
  1002. // Check for a tag type hidden by a non-type decl in a few cases where it
  1003. // seems likely a type is wanted instead of the non-type that was found.
  1004. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  1005. if ((NextToken.is(tok::identifier) ||
  1006. (NextIsOp &&
  1007. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  1008. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  1009. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  1010. DiagnoseUseOfDecl(Type, NameLoc);
  1011. QualType T = Context.getTypeDeclType(Type);
  1012. if (SS.isNotEmpty())
  1013. return buildNestedType(*this, SS, T, NameLoc);
  1014. return ParsedType::make(T);
  1015. }
  1016. if (FirstDecl->isCXXClassMember())
  1017. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  1018. nullptr, S);
  1019. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1020. return BuildDeclarationNameExpr(SS, Result, ADL);
  1021. }
  1022. Sema::TemplateNameKindForDiagnostics
  1023. Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
  1024. auto *TD = Name.getAsTemplateDecl();
  1025. if (!TD)
  1026. return TemplateNameKindForDiagnostics::DependentTemplate;
  1027. if (isa<ClassTemplateDecl>(TD))
  1028. return TemplateNameKindForDiagnostics::ClassTemplate;
  1029. if (isa<FunctionTemplateDecl>(TD))
  1030. return TemplateNameKindForDiagnostics::FunctionTemplate;
  1031. if (isa<VarTemplateDecl>(TD))
  1032. return TemplateNameKindForDiagnostics::VarTemplate;
  1033. if (isa<TypeAliasTemplateDecl>(TD))
  1034. return TemplateNameKindForDiagnostics::AliasTemplate;
  1035. if (isa<TemplateTemplateParmDecl>(TD))
  1036. return TemplateNameKindForDiagnostics::TemplateTemplateParam;
  1037. return TemplateNameKindForDiagnostics::DependentTemplate;
  1038. }
  1039. // Determines the context to return to after temporarily entering a
  1040. // context. This depends in an unnecessarily complicated way on the
  1041. // exact ordering of callbacks from the parser.
  1042. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  1043. // Functions defined inline within classes aren't parsed until we've
  1044. // finished parsing the top-level class, so the top-level class is
  1045. // the context we'll need to return to.
  1046. // A Lambda call operator whose parent is a class must not be treated
  1047. // as an inline member function. A Lambda can be used legally
  1048. // either as an in-class member initializer or a default argument. These
  1049. // are parsed once the class has been marked complete and so the containing
  1050. // context would be the nested class (when the lambda is defined in one);
  1051. // If the class is not complete, then the lambda is being used in an
  1052. // ill-formed fashion (such as to specify the width of a bit-field, or
  1053. // in an array-bound) - in which case we still want to return the
  1054. // lexically containing DC (which could be a nested class).
  1055. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  1056. DC = DC->getLexicalParent();
  1057. // A function not defined within a class will always return to its
  1058. // lexical context.
  1059. if (!isa<CXXRecordDecl>(DC))
  1060. return DC;
  1061. // A C++ inline method/friend is parsed *after* the topmost class
  1062. // it was declared in is fully parsed ("complete"); the topmost
  1063. // class is the context we need to return to.
  1064. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  1065. DC = RD;
  1066. // Return the declaration context of the topmost class the inline method is
  1067. // declared in.
  1068. return DC;
  1069. }
  1070. return DC->getLexicalParent();
  1071. }
  1072. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  1073. assert(getContainingDC(DC) == CurContext &&
  1074. "The next DeclContext should be lexically contained in the current one.");
  1075. CurContext = DC;
  1076. S->setEntity(DC);
  1077. }
  1078. void Sema::PopDeclContext() {
  1079. assert(CurContext && "DeclContext imbalance!");
  1080. CurContext = getContainingDC(CurContext);
  1081. assert(CurContext && "Popped translation unit!");
  1082. }
  1083. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  1084. Decl *D) {
  1085. // Unlike PushDeclContext, the context to which we return is not necessarily
  1086. // the containing DC of TD, because the new context will be some pre-existing
  1087. // TagDecl definition instead of a fresh one.
  1088. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  1089. CurContext = cast<TagDecl>(D)->getDefinition();
  1090. assert(CurContext && "skipping definition of undefined tag");
  1091. // Start lookups from the parent of the current context; we don't want to look
  1092. // into the pre-existing complete definition.
  1093. S->setEntity(CurContext->getLookupParent());
  1094. return Result;
  1095. }
  1096. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  1097. CurContext = static_cast<decltype(CurContext)>(Context);
  1098. }
  1099. /// EnterDeclaratorContext - Used when we must lookup names in the context
  1100. /// of a declarator's nested name specifier.
  1101. ///
  1102. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  1103. // C++0x [basic.lookup.unqual]p13:
  1104. // A name used in the definition of a static data member of class
  1105. // X (after the qualified-id of the static member) is looked up as
  1106. // if the name was used in a member function of X.
  1107. // C++0x [basic.lookup.unqual]p14:
  1108. // If a variable member of a namespace is defined outside of the
  1109. // scope of its namespace then any name used in the definition of
  1110. // the variable member (after the declarator-id) is looked up as
  1111. // if the definition of the variable member occurred in its
  1112. // namespace.
  1113. // Both of these imply that we should push a scope whose context
  1114. // is the semantic context of the declaration. We can't use
  1115. // PushDeclContext here because that context is not necessarily
  1116. // lexically contained in the current context. Fortunately,
  1117. // the containing scope should have the appropriate information.
  1118. assert(!S->getEntity() && "scope already has entity");
  1119. #ifndef NDEBUG
  1120. Scope *Ancestor = S->getParent();
  1121. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1122. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1123. #endif
  1124. CurContext = DC;
  1125. S->setEntity(DC);
  1126. }
  1127. void Sema::ExitDeclaratorContext(Scope *S) {
  1128. assert(S->getEntity() == CurContext && "Context imbalance!");
  1129. // Switch back to the lexical context. The safety of this is
  1130. // enforced by an assert in EnterDeclaratorContext.
  1131. Scope *Ancestor = S->getParent();
  1132. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1133. CurContext = Ancestor->getEntity();
  1134. // We don't need to do anything with the scope, which is going to
  1135. // disappear.
  1136. }
  1137. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1138. // We assume that the caller has already called
  1139. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1140. FunctionDecl *FD = D->getAsFunction();
  1141. if (!FD)
  1142. return;
  1143. // Same implementation as PushDeclContext, but enters the context
  1144. // from the lexical parent, rather than the top-level class.
  1145. assert(CurContext == FD->getLexicalParent() &&
  1146. "The next DeclContext should be lexically contained in the current one.");
  1147. CurContext = FD;
  1148. S->setEntity(CurContext);
  1149. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1150. ParmVarDecl *Param = FD->getParamDecl(P);
  1151. // If the parameter has an identifier, then add it to the scope
  1152. if (Param->getIdentifier()) {
  1153. S->AddDecl(Param);
  1154. IdResolver.AddDecl(Param);
  1155. }
  1156. }
  1157. }
  1158. void Sema::ActOnExitFunctionContext() {
  1159. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1160. // rather than the top-level class.
  1161. assert(CurContext && "DeclContext imbalance!");
  1162. CurContext = CurContext->getLexicalParent();
  1163. assert(CurContext && "Popped translation unit!");
  1164. }
  1165. /// \brief Determine whether we allow overloading of the function
  1166. /// PrevDecl with another declaration.
  1167. ///
  1168. /// This routine determines whether overloading is possible, not
  1169. /// whether some new function is actually an overload. It will return
  1170. /// true in C++ (where we can always provide overloads) or, as an
  1171. /// extension, in C when the previous function is already an
  1172. /// overloaded function declaration or has the "overloadable"
  1173. /// attribute.
  1174. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1175. ASTContext &Context,
  1176. const FunctionDecl *New) {
  1177. if (Context.getLangOpts().CPlusPlus)
  1178. return true;
  1179. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1180. return true;
  1181. return Previous.getResultKind() == LookupResult::Found &&
  1182. (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
  1183. New->hasAttr<OverloadableAttr>());
  1184. }
  1185. /// Add this decl to the scope shadowed decl chains.
  1186. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1187. // Move up the scope chain until we find the nearest enclosing
  1188. // non-transparent context. The declaration will be introduced into this
  1189. // scope.
  1190. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1191. S = S->getParent();
  1192. // Add scoped declarations into their context, so that they can be
  1193. // found later. Declarations without a context won't be inserted
  1194. // into any context.
  1195. if (AddToContext)
  1196. CurContext->addDecl(D);
  1197. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1198. // are function-local declarations.
  1199. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1200. !D->getDeclContext()->getRedeclContext()->Equals(
  1201. D->getLexicalDeclContext()->getRedeclContext()) &&
  1202. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1203. return;
  1204. // Template instantiations should also not be pushed into scope.
  1205. if (isa<FunctionDecl>(D) &&
  1206. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1207. return;
  1208. // If this replaces anything in the current scope,
  1209. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1210. IEnd = IdResolver.end();
  1211. for (; I != IEnd; ++I) {
  1212. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1213. S->RemoveDecl(*I);
  1214. IdResolver.RemoveDecl(*I);
  1215. // Should only need to replace one decl.
  1216. break;
  1217. }
  1218. }
  1219. S->AddDecl(D);
  1220. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1221. // Implicitly-generated labels may end up getting generated in an order that
  1222. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1223. // the label at the appropriate place in the identifier chain.
  1224. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1225. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1226. if (IDC == CurContext) {
  1227. if (!S->isDeclScope(*I))
  1228. continue;
  1229. } else if (IDC->Encloses(CurContext))
  1230. break;
  1231. }
  1232. IdResolver.InsertDeclAfter(I, D);
  1233. } else {
  1234. IdResolver.AddDecl(D);
  1235. }
  1236. }
  1237. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  1238. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  1239. TUScope->AddDecl(D);
  1240. }
  1241. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1242. bool AllowInlineNamespace) {
  1243. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1244. }
  1245. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1246. DeclContext *TargetDC = DC->getPrimaryContext();
  1247. do {
  1248. if (DeclContext *ScopeDC = S->getEntity())
  1249. if (ScopeDC->getPrimaryContext() == TargetDC)
  1250. return S;
  1251. } while ((S = S->getParent()));
  1252. return nullptr;
  1253. }
  1254. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1255. DeclContext*,
  1256. ASTContext&);
  1257. /// Filters out lookup results that don't fall within the given scope
  1258. /// as determined by isDeclInScope.
  1259. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1260. bool ConsiderLinkage,
  1261. bool AllowInlineNamespace) {
  1262. LookupResult::Filter F = R.makeFilter();
  1263. while (F.hasNext()) {
  1264. NamedDecl *D = F.next();
  1265. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1266. continue;
  1267. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1268. continue;
  1269. F.erase();
  1270. }
  1271. F.done();
  1272. }
  1273. /// We've determined that \p New is a redeclaration of \p Old. Check that they
  1274. /// have compatible owning modules.
  1275. bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
  1276. // FIXME: The Modules TS is not clear about how friend declarations are
  1277. // to be treated. It's not meaningful to have different owning modules for
  1278. // linkage in redeclarations of the same entity, so for now allow the
  1279. // redeclaration and change the owning modules to match.
  1280. if (New->getFriendObjectKind() &&
  1281. Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
  1282. New->setLocalOwningModule(Old->getOwningModule());
  1283. makeMergedDefinitionVisible(New);
  1284. return false;
  1285. }
  1286. Module *NewM = New->getOwningModule();
  1287. Module *OldM = Old->getOwningModule();
  1288. if (NewM == OldM)
  1289. return false;
  1290. // FIXME: Check proclaimed-ownership-declarations here too.
  1291. bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
  1292. bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
  1293. if (NewIsModuleInterface || OldIsModuleInterface) {
  1294. // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
  1295. // if a declaration of D [...] appears in the purview of a module, all
  1296. // other such declarations shall appear in the purview of the same module
  1297. Diag(New->getLocation(), diag::err_mismatched_owning_module)
  1298. << New
  1299. << NewIsModuleInterface
  1300. << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
  1301. << OldIsModuleInterface
  1302. << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
  1303. Diag(Old->getLocation(), diag::note_previous_declaration);
  1304. New->setInvalidDecl();
  1305. return true;
  1306. }
  1307. return false;
  1308. }
  1309. static bool isUsingDecl(NamedDecl *D) {
  1310. return isa<UsingShadowDecl>(D) ||
  1311. isa<UnresolvedUsingTypenameDecl>(D) ||
  1312. isa<UnresolvedUsingValueDecl>(D);
  1313. }
  1314. /// Removes using shadow declarations from the lookup results.
  1315. static void RemoveUsingDecls(LookupResult &R) {
  1316. LookupResult::Filter F = R.makeFilter();
  1317. while (F.hasNext())
  1318. if (isUsingDecl(F.next()))
  1319. F.erase();
  1320. F.done();
  1321. }
  1322. /// \brief Check for this common pattern:
  1323. /// @code
  1324. /// class S {
  1325. /// S(const S&); // DO NOT IMPLEMENT
  1326. /// void operator=(const S&); // DO NOT IMPLEMENT
  1327. /// };
  1328. /// @endcode
  1329. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1330. // FIXME: Should check for private access too but access is set after we get
  1331. // the decl here.
  1332. if (D->doesThisDeclarationHaveABody())
  1333. return false;
  1334. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1335. return CD->isCopyConstructor();
  1336. return D->isCopyAssignmentOperator();
  1337. }
  1338. // We need this to handle
  1339. //
  1340. // typedef struct {
  1341. // void *foo() { return 0; }
  1342. // } A;
  1343. //
  1344. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1345. // for example. If 'A', foo will have external linkage. If we have '*A',
  1346. // foo will have no linkage. Since we can't know until we get to the end
  1347. // of the typedef, this function finds out if D might have non-external linkage.
  1348. // Callers should verify at the end of the TU if it D has external linkage or
  1349. // not.
  1350. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1351. const DeclContext *DC = D->getDeclContext();
  1352. while (!DC->isTranslationUnit()) {
  1353. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1354. if (!RD->hasNameForLinkage())
  1355. return true;
  1356. }
  1357. DC = DC->getParent();
  1358. }
  1359. return !D->isExternallyVisible();
  1360. }
  1361. // FIXME: This needs to be refactored; some other isInMainFile users want
  1362. // these semantics.
  1363. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1364. if (S.TUKind != TU_Complete)
  1365. return false;
  1366. return S.SourceMgr.isInMainFile(Loc);
  1367. }
  1368. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1369. assert(D);
  1370. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1371. return false;
  1372. // Ignore all entities declared within templates, and out-of-line definitions
  1373. // of members of class templates.
  1374. if (D->getDeclContext()->isDependentContext() ||
  1375. D->getLexicalDeclContext()->isDependentContext())
  1376. return false;
  1377. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1378. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1379. return false;
  1380. // A non-out-of-line declaration of a member specialization was implicitly
  1381. // instantiated; it's the out-of-line declaration that we're interested in.
  1382. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1383. FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
  1384. return false;
  1385. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1386. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1387. return false;
  1388. } else {
  1389. // 'static inline' functions are defined in headers; don't warn.
  1390. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1391. return false;
  1392. }
  1393. if (FD->doesThisDeclarationHaveABody() &&
  1394. Context.DeclMustBeEmitted(FD))
  1395. return false;
  1396. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1397. // Constants and utility variables are defined in headers with internal
  1398. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1399. // like "inline".)
  1400. if (!isMainFileLoc(*this, VD->getLocation()))
  1401. return false;
  1402. if (Context.DeclMustBeEmitted(VD))
  1403. return false;
  1404. if (VD->isStaticDataMember() &&
  1405. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1406. return false;
  1407. if (VD->isStaticDataMember() &&
  1408. VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1409. VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
  1410. return false;
  1411. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1412. return false;
  1413. } else {
  1414. return false;
  1415. }
  1416. // Only warn for unused decls internal to the translation unit.
  1417. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1418. // for inline functions defined in the main source file, for instance.
  1419. return mightHaveNonExternalLinkage(D);
  1420. }
  1421. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1422. if (!D)
  1423. return;
  1424. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1425. const FunctionDecl *First = FD->getFirstDecl();
  1426. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1427. return; // First should already be in the vector.
  1428. }
  1429. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1430. const VarDecl *First = VD->getFirstDecl();
  1431. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1432. return; // First should already be in the vector.
  1433. }
  1434. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1435. UnusedFileScopedDecls.push_back(D);
  1436. }
  1437. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1438. if (D->isInvalidDecl())
  1439. return false;
  1440. bool Referenced = false;
  1441. if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
  1442. // For a decomposition declaration, warn if none of the bindings are
  1443. // referenced, instead of if the variable itself is referenced (which
  1444. // it is, by the bindings' expressions).
  1445. for (auto *BD : DD->bindings()) {
  1446. if (BD->isReferenced()) {
  1447. Referenced = true;
  1448. break;
  1449. }
  1450. }
  1451. } else if (!D->getDeclName()) {
  1452. return false;
  1453. } else if (D->isReferenced() || D->isUsed()) {
  1454. Referenced = true;
  1455. }
  1456. if (Referenced || D->hasAttr<UnusedAttr>() ||
  1457. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1458. return false;
  1459. if (isa<LabelDecl>(D))
  1460. return true;
  1461. // Except for labels, we only care about unused decls that are local to
  1462. // functions.
  1463. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1464. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1465. // For dependent types, the diagnostic is deferred.
  1466. WithinFunction =
  1467. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1468. if (!WithinFunction)
  1469. return false;
  1470. if (isa<TypedefNameDecl>(D))
  1471. return true;
  1472. // White-list anything that isn't a local variable.
  1473. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1474. return false;
  1475. // Types of valid local variables should be complete, so this should succeed.
  1476. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1477. // White-list anything with an __attribute__((unused)) type.
  1478. const auto *Ty = VD->getType().getTypePtr();
  1479. // Only look at the outermost level of typedef.
  1480. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1481. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1482. return false;
  1483. }
  1484. // If we failed to complete the type for some reason, or if the type is
  1485. // dependent, don't diagnose the variable.
  1486. if (Ty->isIncompleteType() || Ty->isDependentType())
  1487. return false;
  1488. // Look at the element type to ensure that the warning behaviour is
  1489. // consistent for both scalars and arrays.
  1490. Ty = Ty->getBaseElementTypeUnsafe();
  1491. if (const TagType *TT = Ty->getAs<TagType>()) {
  1492. const TagDecl *Tag = TT->getDecl();
  1493. if (Tag->hasAttr<UnusedAttr>())
  1494. return false;
  1495. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1496. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1497. return false;
  1498. if (const Expr *Init = VD->getInit()) {
  1499. if (const ExprWithCleanups *Cleanups =
  1500. dyn_cast<ExprWithCleanups>(Init))
  1501. Init = Cleanups->getSubExpr();
  1502. const CXXConstructExpr *Construct =
  1503. dyn_cast<CXXConstructExpr>(Init);
  1504. if (Construct && !Construct->isElidable()) {
  1505. CXXConstructorDecl *CD = Construct->getConstructor();
  1506. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
  1507. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  1508. return false;
  1509. }
  1510. }
  1511. }
  1512. }
  1513. // TODO: __attribute__((unused)) templates?
  1514. }
  1515. return true;
  1516. }
  1517. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1518. FixItHint &Hint) {
  1519. if (isa<LabelDecl>(D)) {
  1520. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1521. tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
  1522. if (AfterColon.isInvalid())
  1523. return;
  1524. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1525. getCharRange(D->getLocStart(), AfterColon));
  1526. }
  1527. }
  1528. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1529. if (D->getTypeForDecl()->isDependentType())
  1530. return;
  1531. for (auto *TmpD : D->decls()) {
  1532. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1533. DiagnoseUnusedDecl(T);
  1534. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1535. DiagnoseUnusedNestedTypedefs(R);
  1536. }
  1537. }
  1538. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1539. /// unless they are marked attr(unused).
  1540. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1541. if (!ShouldDiagnoseUnusedDecl(D))
  1542. return;
  1543. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1544. // typedefs can be referenced later on, so the diagnostics are emitted
  1545. // at end-of-translation-unit.
  1546. UnusedLocalTypedefNameCandidates.insert(TD);
  1547. return;
  1548. }
  1549. FixItHint Hint;
  1550. GenerateFixForUnusedDecl(D, Context, Hint);
  1551. unsigned DiagID;
  1552. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1553. DiagID = diag::warn_unused_exception_param;
  1554. else if (isa<LabelDecl>(D))
  1555. DiagID = diag::warn_unused_label;
  1556. else
  1557. DiagID = diag::warn_unused_variable;
  1558. Diag(D->getLocation(), DiagID) << D << Hint;
  1559. }
  1560. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1561. // Verify that we have no forward references left. If so, there was a goto
  1562. // or address of a label taken, but no definition of it. Label fwd
  1563. // definitions are indicated with a null substmt which is also not a resolved
  1564. // MS inline assembly label name.
  1565. bool Diagnose = false;
  1566. if (L->isMSAsmLabel())
  1567. Diagnose = !L->isResolvedMSAsmLabel();
  1568. else
  1569. Diagnose = L->getStmt() == nullptr;
  1570. if (Diagnose)
  1571. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1572. }
  1573. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1574. S->mergeNRVOIntoParent();
  1575. if (S->decl_empty()) return;
  1576. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1577. "Scope shouldn't contain decls!");
  1578. for (auto *TmpD : S->decls()) {
  1579. assert(TmpD && "This decl didn't get pushed??");
  1580. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1581. NamedDecl *D = cast<NamedDecl>(TmpD);
  1582. // Diagnose unused variables in this scope.
  1583. if (!S->hasUnrecoverableErrorOccurred()) {
  1584. DiagnoseUnusedDecl(D);
  1585. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1586. DiagnoseUnusedNestedTypedefs(RD);
  1587. }
  1588. if (!D->getDeclName()) continue;
  1589. // If this was a forward reference to a label, verify it was defined.
  1590. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1591. CheckPoppedLabel(LD, *this);
  1592. // Remove this name from our lexical scope, and warn on it if we haven't
  1593. // already.
  1594. IdResolver.RemoveDecl(D);
  1595. auto ShadowI = ShadowingDecls.find(D);
  1596. if (ShadowI != ShadowingDecls.end()) {
  1597. if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
  1598. Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
  1599. << D << FD << FD->getParent();
  1600. Diag(FD->getLocation(), diag::note_previous_declaration);
  1601. }
  1602. ShadowingDecls.erase(ShadowI);
  1603. }
  1604. }
  1605. }
  1606. /// \brief Look for an Objective-C class in the translation unit.
  1607. ///
  1608. /// \param Id The name of the Objective-C class we're looking for. If
  1609. /// typo-correction fixes this name, the Id will be updated
  1610. /// to the fixed name.
  1611. ///
  1612. /// \param IdLoc The location of the name in the translation unit.
  1613. ///
  1614. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1615. /// if there is no class with the given name.
  1616. ///
  1617. /// \returns The declaration of the named Objective-C class, or NULL if the
  1618. /// class could not be found.
  1619. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1620. SourceLocation IdLoc,
  1621. bool DoTypoCorrection) {
  1622. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1623. // creation from this context.
  1624. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1625. if (!IDecl && DoTypoCorrection) {
  1626. // Perform typo correction at the given location, but only if we
  1627. // find an Objective-C class name.
  1628. if (TypoCorrection C = CorrectTypo(
  1629. DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
  1630. llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
  1631. CTK_ErrorRecovery)) {
  1632. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1633. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1634. Id = IDecl->getIdentifier();
  1635. }
  1636. }
  1637. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1638. // This routine must always return a class definition, if any.
  1639. if (Def && Def->getDefinition())
  1640. Def = Def->getDefinition();
  1641. return Def;
  1642. }
  1643. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1644. /// from S, where a non-field would be declared. This routine copes
  1645. /// with the difference between C and C++ scoping rules in structs and
  1646. /// unions. For example, the following code is well-formed in C but
  1647. /// ill-formed in C++:
  1648. /// @code
  1649. /// struct S6 {
  1650. /// enum { BAR } e;
  1651. /// };
  1652. ///
  1653. /// void test_S6() {
  1654. /// struct S6 a;
  1655. /// a.e = BAR;
  1656. /// }
  1657. /// @endcode
  1658. /// For the declaration of BAR, this routine will return a different
  1659. /// scope. The scope S will be the scope of the unnamed enumeration
  1660. /// within S6. In C++, this routine will return the scope associated
  1661. /// with S6, because the enumeration's scope is a transparent
  1662. /// context but structures can contain non-field names. In C, this
  1663. /// routine will return the translation unit scope, since the
  1664. /// enumeration's scope is a transparent context and structures cannot
  1665. /// contain non-field names.
  1666. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1667. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1668. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1669. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1670. S = S->getParent();
  1671. return S;
  1672. }
  1673. /// \brief Looks up the declaration of "struct objc_super" and
  1674. /// saves it for later use in building builtin declaration of
  1675. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1676. /// pre-existing declaration exists no action takes place.
  1677. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1678. IdentifierInfo *II) {
  1679. if (!II->isStr("objc_msgSendSuper"))
  1680. return;
  1681. ASTContext &Context = ThisSema.Context;
  1682. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1683. SourceLocation(), Sema::LookupTagName);
  1684. ThisSema.LookupName(Result, S);
  1685. if (Result.getResultKind() == LookupResult::Found)
  1686. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1687. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1688. }
  1689. static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
  1690. switch (Error) {
  1691. case ASTContext::GE_None:
  1692. return "";
  1693. case ASTContext::GE_Missing_stdio:
  1694. return "stdio.h";
  1695. case ASTContext::GE_Missing_setjmp:
  1696. return "setjmp.h";
  1697. case ASTContext::GE_Missing_ucontext:
  1698. return "ucontext.h";
  1699. }
  1700. llvm_unreachable("unhandled error kind");
  1701. }
  1702. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1703. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1704. /// if we're creating this built-in in anticipation of redeclaring the
  1705. /// built-in.
  1706. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1707. Scope *S, bool ForRedeclaration,
  1708. SourceLocation Loc) {
  1709. LookupPredefedObjCSuperType(*this, S, II);
  1710. ASTContext::GetBuiltinTypeError Error;
  1711. QualType R = Context.GetBuiltinType(ID, Error);
  1712. if (Error) {
  1713. if (ForRedeclaration)
  1714. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1715. << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
  1716. return nullptr;
  1717. }
  1718. if (!ForRedeclaration &&
  1719. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1720. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1721. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1722. << Context.BuiltinInfo.getName(ID) << R;
  1723. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1724. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1725. Diag(Loc, diag::note_include_header_or_declare)
  1726. << Context.BuiltinInfo.getHeaderName(ID)
  1727. << Context.BuiltinInfo.getName(ID);
  1728. }
  1729. if (R.isNull())
  1730. return nullptr;
  1731. DeclContext *Parent = Context.getTranslationUnitDecl();
  1732. if (getLangOpts().CPlusPlus) {
  1733. LinkageSpecDecl *CLinkageDecl =
  1734. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1735. LinkageSpecDecl::lang_c, false);
  1736. CLinkageDecl->setImplicit();
  1737. Parent->addDecl(CLinkageDecl);
  1738. Parent = CLinkageDecl;
  1739. }
  1740. FunctionDecl *New = FunctionDecl::Create(Context,
  1741. Parent,
  1742. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1743. SC_Extern,
  1744. false,
  1745. R->isFunctionProtoType());
  1746. New->setImplicit();
  1747. // Create Decl objects for each parameter, adding them to the
  1748. // FunctionDecl.
  1749. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1750. SmallVector<ParmVarDecl*, 16> Params;
  1751. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1752. ParmVarDecl *parm =
  1753. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1754. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1755. SC_None, nullptr);
  1756. parm->setScopeInfo(0, i);
  1757. Params.push_back(parm);
  1758. }
  1759. New->setParams(Params);
  1760. }
  1761. AddKnownFunctionAttributes(New);
  1762. RegisterLocallyScopedExternCDecl(New, S);
  1763. // TUScope is the translation-unit scope to insert this function into.
  1764. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1765. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1766. // entirely, but we're not there yet.
  1767. DeclContext *SavedContext = CurContext;
  1768. CurContext = Parent;
  1769. PushOnScopeChains(New, TUScope);
  1770. CurContext = SavedContext;
  1771. return New;
  1772. }
  1773. /// Typedef declarations don't have linkage, but they still denote the same
  1774. /// entity if their types are the same.
  1775. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1776. /// isSameEntity.
  1777. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1778. TypedefNameDecl *Decl,
  1779. LookupResult &Previous) {
  1780. // This is only interesting when modules are enabled.
  1781. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1782. return;
  1783. // Empty sets are uninteresting.
  1784. if (Previous.empty())
  1785. return;
  1786. LookupResult::Filter Filter = Previous.makeFilter();
  1787. while (Filter.hasNext()) {
  1788. NamedDecl *Old = Filter.next();
  1789. // Non-hidden declarations are never ignored.
  1790. if (S.isVisible(Old))
  1791. continue;
  1792. // Declarations of the same entity are not ignored, even if they have
  1793. // different linkages.
  1794. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1795. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1796. Decl->getUnderlyingType()))
  1797. continue;
  1798. // If both declarations give a tag declaration a typedef name for linkage
  1799. // purposes, then they declare the same entity.
  1800. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1801. Decl->getAnonDeclWithTypedefName())
  1802. continue;
  1803. }
  1804. Filter.erase();
  1805. }
  1806. Filter.done();
  1807. }
  1808. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1809. QualType OldType;
  1810. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1811. OldType = OldTypedef->getUnderlyingType();
  1812. else
  1813. OldType = Context.getTypeDeclType(Old);
  1814. QualType NewType = New->getUnderlyingType();
  1815. if (NewType->isVariablyModifiedType()) {
  1816. // Must not redefine a typedef with a variably-modified type.
  1817. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1818. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1819. << Kind << NewType;
  1820. if (Old->getLocation().isValid())
  1821. notePreviousDefinition(Old, New->getLocation());
  1822. New->setInvalidDecl();
  1823. return true;
  1824. }
  1825. if (OldType != NewType &&
  1826. !OldType->isDependentType() &&
  1827. !NewType->isDependentType() &&
  1828. !Context.hasSameType(OldType, NewType)) {
  1829. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1830. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1831. << Kind << NewType << OldType;
  1832. if (Old->getLocation().isValid())
  1833. notePreviousDefinition(Old, New->getLocation());
  1834. New->setInvalidDecl();
  1835. return true;
  1836. }
  1837. return false;
  1838. }
  1839. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1840. /// same name and scope as a previous declaration 'Old'. Figure out
  1841. /// how to resolve this situation, merging decls or emitting
  1842. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1843. ///
  1844. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  1845. LookupResult &OldDecls) {
  1846. // If the new decl is known invalid already, don't bother doing any
  1847. // merging checks.
  1848. if (New->isInvalidDecl()) return;
  1849. // Allow multiple definitions for ObjC built-in typedefs.
  1850. // FIXME: Verify the underlying types are equivalent!
  1851. if (getLangOpts().ObjC1) {
  1852. const IdentifierInfo *TypeID = New->getIdentifier();
  1853. switch (TypeID->getLength()) {
  1854. default: break;
  1855. case 2:
  1856. {
  1857. if (!TypeID->isStr("id"))
  1858. break;
  1859. QualType T = New->getUnderlyingType();
  1860. if (!T->isPointerType())
  1861. break;
  1862. if (!T->isVoidPointerType()) {
  1863. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1864. if (!PT->isStructureType())
  1865. break;
  1866. }
  1867. Context.setObjCIdRedefinitionType(T);
  1868. // Install the built-in type for 'id', ignoring the current definition.
  1869. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1870. return;
  1871. }
  1872. case 5:
  1873. if (!TypeID->isStr("Class"))
  1874. break;
  1875. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1876. // Install the built-in type for 'Class', ignoring the current definition.
  1877. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1878. return;
  1879. case 3:
  1880. if (!TypeID->isStr("SEL"))
  1881. break;
  1882. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1883. // Install the built-in type for 'SEL', ignoring the current definition.
  1884. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1885. return;
  1886. }
  1887. // Fall through - the typedef name was not a builtin type.
  1888. }
  1889. // Verify the old decl was also a type.
  1890. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1891. if (!Old) {
  1892. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1893. << New->getDeclName();
  1894. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1895. if (OldD->getLocation().isValid())
  1896. notePreviousDefinition(OldD, New->getLocation());
  1897. return New->setInvalidDecl();
  1898. }
  1899. // If the old declaration is invalid, just give up here.
  1900. if (Old->isInvalidDecl())
  1901. return New->setInvalidDecl();
  1902. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1903. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1904. auto *NewTag = New->getAnonDeclWithTypedefName();
  1905. NamedDecl *Hidden = nullptr;
  1906. if (OldTag && NewTag &&
  1907. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1908. !hasVisibleDefinition(OldTag, &Hidden)) {
  1909. // There is a definition of this tag, but it is not visible. Use it
  1910. // instead of our tag.
  1911. New->setTypeForDecl(OldTD->getTypeForDecl());
  1912. if (OldTD->isModed())
  1913. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1914. OldTD->getUnderlyingType());
  1915. else
  1916. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1917. // Make the old tag definition visible.
  1918. makeMergedDefinitionVisible(Hidden);
  1919. // If this was an unscoped enumeration, yank all of its enumerators
  1920. // out of the scope.
  1921. if (isa<EnumDecl>(NewTag)) {
  1922. Scope *EnumScope = getNonFieldDeclScope(S);
  1923. for (auto *D : NewTag->decls()) {
  1924. auto *ED = cast<EnumConstantDecl>(D);
  1925. assert(EnumScope->isDeclScope(ED));
  1926. EnumScope->RemoveDecl(ED);
  1927. IdResolver.RemoveDecl(ED);
  1928. ED->getLexicalDeclContext()->removeDecl(ED);
  1929. }
  1930. }
  1931. }
  1932. }
  1933. // If the typedef types are not identical, reject them in all languages and
  1934. // with any extensions enabled.
  1935. if (isIncompatibleTypedef(Old, New))
  1936. return;
  1937. // The types match. Link up the redeclaration chain and merge attributes if
  1938. // the old declaration was a typedef.
  1939. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1940. New->setPreviousDecl(Typedef);
  1941. mergeDeclAttributes(New, Old);
  1942. }
  1943. if (getLangOpts().MicrosoftExt)
  1944. return;
  1945. if (getLangOpts().CPlusPlus) {
  1946. // C++ [dcl.typedef]p2:
  1947. // In a given non-class scope, a typedef specifier can be used to
  1948. // redefine the name of any type declared in that scope to refer
  1949. // to the type to which it already refers.
  1950. if (!isa<CXXRecordDecl>(CurContext))
  1951. return;
  1952. // C++0x [dcl.typedef]p4:
  1953. // In a given class scope, a typedef specifier can be used to redefine
  1954. // any class-name declared in that scope that is not also a typedef-name
  1955. // to refer to the type to which it already refers.
  1956. //
  1957. // This wording came in via DR424, which was a correction to the
  1958. // wording in DR56, which accidentally banned code like:
  1959. //
  1960. // struct S {
  1961. // typedef struct A { } A;
  1962. // };
  1963. //
  1964. // in the C++03 standard. We implement the C++0x semantics, which
  1965. // allow the above but disallow
  1966. //
  1967. // struct S {
  1968. // typedef int I;
  1969. // typedef int I;
  1970. // };
  1971. //
  1972. // since that was the intent of DR56.
  1973. if (!isa<TypedefNameDecl>(Old))
  1974. return;
  1975. Diag(New->getLocation(), diag::err_redefinition)
  1976. << New->getDeclName();
  1977. notePreviousDefinition(Old, New->getLocation());
  1978. return New->setInvalidDecl();
  1979. }
  1980. // Modules always permit redefinition of typedefs, as does C11.
  1981. if (getLangOpts().Modules || getLangOpts().C11)
  1982. return;
  1983. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1984. // is normally mapped to an error, but can be controlled with
  1985. // -Wtypedef-redefinition. If either the original or the redefinition is
  1986. // in a system header, don't emit this for compatibility with GCC.
  1987. if (getDiagnostics().getSuppressSystemWarnings() &&
  1988. // Some standard types are defined implicitly in Clang (e.g. OpenCL).
  1989. (Old->isImplicit() ||
  1990. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1991. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1992. return;
  1993. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  1994. << New->getDeclName();
  1995. notePreviousDefinition(Old, New->getLocation());
  1996. }
  1997. /// DeclhasAttr - returns true if decl Declaration already has the target
  1998. /// attribute.
  1999. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  2000. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  2001. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  2002. for (const auto *i : D->attrs())
  2003. if (i->getKind() == A->getKind()) {
  2004. if (Ann) {
  2005. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  2006. return true;
  2007. continue;
  2008. }
  2009. // FIXME: Don't hardcode this check
  2010. if (OA && isa<OwnershipAttr>(i))
  2011. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  2012. return true;
  2013. }
  2014. return false;
  2015. }
  2016. static bool isAttributeTargetADefinition(Decl *D) {
  2017. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  2018. return VD->isThisDeclarationADefinition();
  2019. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  2020. return TD->isCompleteDefinition() || TD->isBeingDefined();
  2021. return true;
  2022. }
  2023. /// Merge alignment attributes from \p Old to \p New, taking into account the
  2024. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  2025. ///
  2026. /// \return \c true if any attributes were added to \p New.
  2027. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  2028. // Look for alignas attributes on Old, and pick out whichever attribute
  2029. // specifies the strictest alignment requirement.
  2030. AlignedAttr *OldAlignasAttr = nullptr;
  2031. AlignedAttr *OldStrictestAlignAttr = nullptr;
  2032. unsigned OldAlign = 0;
  2033. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  2034. // FIXME: We have no way of representing inherited dependent alignments
  2035. // in a case like:
  2036. // template<int A, int B> struct alignas(A) X;
  2037. // template<int A, int B> struct alignas(B) X {};
  2038. // For now, we just ignore any alignas attributes which are not on the
  2039. // definition in such a case.
  2040. if (I->isAlignmentDependent())
  2041. return false;
  2042. if (I->isAlignas())
  2043. OldAlignasAttr = I;
  2044. unsigned Align = I->getAlignment(S.Context);
  2045. if (Align > OldAlign) {
  2046. OldAlign = Align;
  2047. OldStrictestAlignAttr = I;
  2048. }
  2049. }
  2050. // Look for alignas attributes on New.
  2051. AlignedAttr *NewAlignasAttr = nullptr;
  2052. unsigned NewAlign = 0;
  2053. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  2054. if (I->isAlignmentDependent())
  2055. return false;
  2056. if (I->isAlignas())
  2057. NewAlignasAttr = I;
  2058. unsigned Align = I->getAlignment(S.Context);
  2059. if (Align > NewAlign)
  2060. NewAlign = Align;
  2061. }
  2062. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  2063. // Both declarations have 'alignas' attributes. We require them to match.
  2064. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  2065. // fall short. (If two declarations both have alignas, they must both match
  2066. // every definition, and so must match each other if there is a definition.)
  2067. // If either declaration only contains 'alignas(0)' specifiers, then it
  2068. // specifies the natural alignment for the type.
  2069. if (OldAlign == 0 || NewAlign == 0) {
  2070. QualType Ty;
  2071. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  2072. Ty = VD->getType();
  2073. else
  2074. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  2075. if (OldAlign == 0)
  2076. OldAlign = S.Context.getTypeAlign(Ty);
  2077. if (NewAlign == 0)
  2078. NewAlign = S.Context.getTypeAlign(Ty);
  2079. }
  2080. if (OldAlign != NewAlign) {
  2081. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  2082. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  2083. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  2084. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  2085. }
  2086. }
  2087. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  2088. // C++11 [dcl.align]p6:
  2089. // if any declaration of an entity has an alignment-specifier,
  2090. // every defining declaration of that entity shall specify an
  2091. // equivalent alignment.
  2092. // C11 6.7.5/7:
  2093. // If the definition of an object does not have an alignment
  2094. // specifier, any other declaration of that object shall also
  2095. // have no alignment specifier.
  2096. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2097. << OldAlignasAttr;
  2098. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2099. << OldAlignasAttr;
  2100. }
  2101. bool AnyAdded = false;
  2102. // Ensure we have an attribute representing the strictest alignment.
  2103. if (OldAlign > NewAlign) {
  2104. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2105. Clone->setInherited(true);
  2106. New->addAttr(Clone);
  2107. AnyAdded = true;
  2108. }
  2109. // Ensure we have an alignas attribute if the old declaration had one.
  2110. if (OldAlignasAttr && !NewAlignasAttr &&
  2111. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2112. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2113. Clone->setInherited(true);
  2114. New->addAttr(Clone);
  2115. AnyAdded = true;
  2116. }
  2117. return AnyAdded;
  2118. }
  2119. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2120. const InheritableAttr *Attr,
  2121. Sema::AvailabilityMergeKind AMK) {
  2122. // This function copies an attribute Attr from a previous declaration to the
  2123. // new declaration D if the new declaration doesn't itself have that attribute
  2124. // yet or if that attribute allows duplicates.
  2125. // If you're adding a new attribute that requires logic different from
  2126. // "use explicit attribute on decl if present, else use attribute from
  2127. // previous decl", for example if the attribute needs to be consistent
  2128. // between redeclarations, you need to call a custom merge function here.
  2129. InheritableAttr *NewAttr = nullptr;
  2130. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  2131. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2132. NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
  2133. AA->isImplicit(), AA->getIntroduced(),
  2134. AA->getDeprecated(),
  2135. AA->getObsoleted(), AA->getUnavailable(),
  2136. AA->getMessage(), AA->getStrict(),
  2137. AA->getReplacement(), AMK,
  2138. AttrSpellingListIndex);
  2139. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2140. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2141. AttrSpellingListIndex);
  2142. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2143. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2144. AttrSpellingListIndex);
  2145. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2146. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  2147. AttrSpellingListIndex);
  2148. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2149. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  2150. AttrSpellingListIndex);
  2151. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2152. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  2153. FA->getFormatIdx(), FA->getFirstArg(),
  2154. AttrSpellingListIndex);
  2155. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2156. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  2157. AttrSpellingListIndex);
  2158. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2159. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  2160. AttrSpellingListIndex,
  2161. IA->getSemanticSpelling());
  2162. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2163. NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
  2164. &S.Context.Idents.get(AA->getSpelling()),
  2165. AttrSpellingListIndex);
  2166. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2167. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2168. isa<CUDAGlobalAttr>(Attr))) {
  2169. // CUDA target attributes are part of function signature for
  2170. // overloading purposes and must not be merged.
  2171. return false;
  2172. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2173. NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
  2174. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2175. NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
  2176. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2177. NewAttr = S.mergeInternalLinkageAttr(
  2178. D, InternalLinkageA->getRange(),
  2179. &S.Context.Idents.get(InternalLinkageA->getSpelling()),
  2180. AttrSpellingListIndex);
  2181. else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
  2182. NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
  2183. &S.Context.Idents.get(CommonA->getSpelling()),
  2184. AttrSpellingListIndex);
  2185. else if (isa<AlignedAttr>(Attr))
  2186. // AlignedAttrs are handled separately, because we need to handle all
  2187. // such attributes on a declaration at the same time.
  2188. NewAttr = nullptr;
  2189. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2190. (AMK == Sema::AMK_Override ||
  2191. AMK == Sema::AMK_ProtocolImplementation))
  2192. NewAttr = nullptr;
  2193. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2194. NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
  2195. UA->getGuid());
  2196. else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
  2197. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2198. if (NewAttr) {
  2199. NewAttr->setInherited(true);
  2200. D->addAttr(NewAttr);
  2201. if (isa<MSInheritanceAttr>(NewAttr))
  2202. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2203. return true;
  2204. }
  2205. return false;
  2206. }
  2207. static const NamedDecl *getDefinition(const Decl *D) {
  2208. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2209. return TD->getDefinition();
  2210. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2211. const VarDecl *Def = VD->getDefinition();
  2212. if (Def)
  2213. return Def;
  2214. return VD->getActingDefinition();
  2215. }
  2216. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2217. return FD->getDefinition();
  2218. return nullptr;
  2219. }
  2220. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2221. for (const auto *Attribute : D->attrs())
  2222. if (Attribute->getKind() == Kind)
  2223. return true;
  2224. return false;
  2225. }
  2226. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2227. /// there are no new attributes in this declaration.
  2228. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2229. if (!New->hasAttrs())
  2230. return;
  2231. const NamedDecl *Def = getDefinition(Old);
  2232. if (!Def || Def == New)
  2233. return;
  2234. AttrVec &NewAttributes = New->getAttrs();
  2235. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2236. const Attr *NewAttribute = NewAttributes[I];
  2237. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2238. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2239. Sema::SkipBodyInfo SkipBody;
  2240. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2241. // If we're skipping this definition, drop the "alias" attribute.
  2242. if (SkipBody.ShouldSkip) {
  2243. NewAttributes.erase(NewAttributes.begin() + I);
  2244. --E;
  2245. continue;
  2246. }
  2247. } else {
  2248. VarDecl *VD = cast<VarDecl>(New);
  2249. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2250. VarDecl::TentativeDefinition
  2251. ? diag::err_alias_after_tentative
  2252. : diag::err_redefinition;
  2253. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2254. if (Diag == diag::err_redefinition)
  2255. S.notePreviousDefinition(Def, VD->getLocation());
  2256. else
  2257. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2258. VD->setInvalidDecl();
  2259. }
  2260. ++I;
  2261. continue;
  2262. }
  2263. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2264. // Tentative definitions are only interesting for the alias check above.
  2265. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2266. ++I;
  2267. continue;
  2268. }
  2269. }
  2270. if (hasAttribute(Def, NewAttribute->getKind())) {
  2271. ++I;
  2272. continue; // regular attr merging will take care of validating this.
  2273. }
  2274. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2275. // C's _Noreturn is allowed to be added to a function after it is defined.
  2276. ++I;
  2277. continue;
  2278. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2279. if (AA->isAlignas()) {
  2280. // C++11 [dcl.align]p6:
  2281. // if any declaration of an entity has an alignment-specifier,
  2282. // every defining declaration of that entity shall specify an
  2283. // equivalent alignment.
  2284. // C11 6.7.5/7:
  2285. // If the definition of an object does not have an alignment
  2286. // specifier, any other declaration of that object shall also
  2287. // have no alignment specifier.
  2288. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2289. << AA;
  2290. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2291. << AA;
  2292. NewAttributes.erase(NewAttributes.begin() + I);
  2293. --E;
  2294. continue;
  2295. }
  2296. }
  2297. S.Diag(NewAttribute->getLocation(),
  2298. diag::warn_attribute_precede_definition);
  2299. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2300. NewAttributes.erase(NewAttributes.begin() + I);
  2301. --E;
  2302. }
  2303. }
  2304. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2305. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2306. AvailabilityMergeKind AMK) {
  2307. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2308. UsedAttr *NewAttr = OldAttr->clone(Context);
  2309. NewAttr->setInherited(true);
  2310. New->addAttr(NewAttr);
  2311. }
  2312. if (!Old->hasAttrs() && !New->hasAttrs())
  2313. return;
  2314. // Attributes declared post-definition are currently ignored.
  2315. checkNewAttributesAfterDef(*this, New, Old);
  2316. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2317. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2318. if (OldA->getLabel() != NewA->getLabel()) {
  2319. // This redeclaration changes __asm__ label.
  2320. Diag(New->getLocation(), diag::err_different_asm_label);
  2321. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2322. }
  2323. } else if (Old->isUsed()) {
  2324. // This redeclaration adds an __asm__ label to a declaration that has
  2325. // already been ODR-used.
  2326. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2327. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2328. }
  2329. }
  2330. // Re-declaration cannot add abi_tag's.
  2331. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2332. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2333. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2334. if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
  2335. NewTag) == OldAbiTagAttr->tags_end()) {
  2336. Diag(NewAbiTagAttr->getLocation(),
  2337. diag::err_new_abi_tag_on_redeclaration)
  2338. << NewTag;
  2339. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2340. }
  2341. }
  2342. } else {
  2343. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2344. Diag(Old->getLocation(), diag::note_previous_declaration);
  2345. }
  2346. }
  2347. // This redeclaration adds a section attribute.
  2348. if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
  2349. if (auto *VD = dyn_cast<VarDecl>(New)) {
  2350. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
  2351. Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
  2352. Diag(Old->getLocation(), diag::note_previous_declaration);
  2353. }
  2354. }
  2355. }
  2356. if (!Old->hasAttrs())
  2357. return;
  2358. bool foundAny = New->hasAttrs();
  2359. // Ensure that any moving of objects within the allocated map is done before
  2360. // we process them.
  2361. if (!foundAny) New->setAttrs(AttrVec());
  2362. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2363. // Ignore deprecated/unavailable/availability attributes if requested.
  2364. AvailabilityMergeKind LocalAMK = AMK_None;
  2365. if (isa<DeprecatedAttr>(I) ||
  2366. isa<UnavailableAttr>(I) ||
  2367. isa<AvailabilityAttr>(I)) {
  2368. switch (AMK) {
  2369. case AMK_None:
  2370. continue;
  2371. case AMK_Redeclaration:
  2372. case AMK_Override:
  2373. case AMK_ProtocolImplementation:
  2374. LocalAMK = AMK;
  2375. break;
  2376. }
  2377. }
  2378. // Already handled.
  2379. if (isa<UsedAttr>(I))
  2380. continue;
  2381. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2382. foundAny = true;
  2383. }
  2384. if (mergeAlignedAttrs(*this, New, Old))
  2385. foundAny = true;
  2386. if (!foundAny) New->dropAttrs();
  2387. }
  2388. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2389. /// to the new one.
  2390. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2391. const ParmVarDecl *oldDecl,
  2392. Sema &S) {
  2393. // C++11 [dcl.attr.depend]p2:
  2394. // The first declaration of a function shall specify the
  2395. // carries_dependency attribute for its declarator-id if any declaration
  2396. // of the function specifies the carries_dependency attribute.
  2397. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2398. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2399. S.Diag(CDA->getLocation(),
  2400. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2401. // Find the first declaration of the parameter.
  2402. // FIXME: Should we build redeclaration chains for function parameters?
  2403. const FunctionDecl *FirstFD =
  2404. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2405. const ParmVarDecl *FirstVD =
  2406. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2407. S.Diag(FirstVD->getLocation(),
  2408. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2409. }
  2410. if (!oldDecl->hasAttrs())
  2411. return;
  2412. bool foundAny = newDecl->hasAttrs();
  2413. // Ensure that any moving of objects within the allocated map is
  2414. // done before we process them.
  2415. if (!foundAny) newDecl->setAttrs(AttrVec());
  2416. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2417. if (!DeclHasAttr(newDecl, I)) {
  2418. InheritableAttr *newAttr =
  2419. cast<InheritableParamAttr>(I->clone(S.Context));
  2420. newAttr->setInherited(true);
  2421. newDecl->addAttr(newAttr);
  2422. foundAny = true;
  2423. }
  2424. }
  2425. if (!foundAny) newDecl->dropAttrs();
  2426. }
  2427. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2428. const ParmVarDecl *OldParam,
  2429. Sema &S) {
  2430. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2431. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2432. if (*Oldnullability != *Newnullability) {
  2433. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2434. << DiagNullabilityKind(
  2435. *Newnullability,
  2436. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2437. != 0))
  2438. << DiagNullabilityKind(
  2439. *Oldnullability,
  2440. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2441. != 0));
  2442. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2443. }
  2444. } else {
  2445. QualType NewT = NewParam->getType();
  2446. NewT = S.Context.getAttributedType(
  2447. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2448. NewT, NewT);
  2449. NewParam->setType(NewT);
  2450. }
  2451. }
  2452. }
  2453. namespace {
  2454. /// Used in MergeFunctionDecl to keep track of function parameters in
  2455. /// C.
  2456. struct GNUCompatibleParamWarning {
  2457. ParmVarDecl *OldParm;
  2458. ParmVarDecl *NewParm;
  2459. QualType PromotedType;
  2460. };
  2461. } // end anonymous namespace
  2462. /// getSpecialMember - get the special member enum for a method.
  2463. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2464. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2465. if (Ctor->isDefaultConstructor())
  2466. return Sema::CXXDefaultConstructor;
  2467. if (Ctor->isCopyConstructor())
  2468. return Sema::CXXCopyConstructor;
  2469. if (Ctor->isMoveConstructor())
  2470. return Sema::CXXMoveConstructor;
  2471. } else if (isa<CXXDestructorDecl>(MD)) {
  2472. return Sema::CXXDestructor;
  2473. } else if (MD->isCopyAssignmentOperator()) {
  2474. return Sema::CXXCopyAssignment;
  2475. } else if (MD->isMoveAssignmentOperator()) {
  2476. return Sema::CXXMoveAssignment;
  2477. }
  2478. return Sema::CXXInvalid;
  2479. }
  2480. // Determine whether the previous declaration was a definition, implicit
  2481. // declaration, or a declaration.
  2482. template <typename T>
  2483. static std::pair<diag::kind, SourceLocation>
  2484. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2485. diag::kind PrevDiag;
  2486. SourceLocation OldLocation = Old->getLocation();
  2487. if (Old->isThisDeclarationADefinition())
  2488. PrevDiag = diag::note_previous_definition;
  2489. else if (Old->isImplicit()) {
  2490. PrevDiag = diag::note_previous_implicit_declaration;
  2491. if (OldLocation.isInvalid())
  2492. OldLocation = New->getLocation();
  2493. } else
  2494. PrevDiag = diag::note_previous_declaration;
  2495. return std::make_pair(PrevDiag, OldLocation);
  2496. }
  2497. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2498. /// only extern inline functions can be redefined, and even then only in
  2499. /// GNU89 mode.
  2500. static bool canRedefineFunction(const FunctionDecl *FD,
  2501. const LangOptions& LangOpts) {
  2502. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2503. !LangOpts.CPlusPlus &&
  2504. FD->isInlineSpecified() &&
  2505. FD->getStorageClass() == SC_Extern);
  2506. }
  2507. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2508. const AttributedType *AT = T->getAs<AttributedType>();
  2509. while (AT && !AT->isCallingConv())
  2510. AT = AT->getModifiedType()->getAs<AttributedType>();
  2511. return AT;
  2512. }
  2513. template <typename T>
  2514. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2515. const DeclContext *DC = Old->getDeclContext();
  2516. if (DC->isRecord())
  2517. return false;
  2518. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2519. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2520. return true;
  2521. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2522. return true;
  2523. return false;
  2524. }
  2525. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2526. static bool isExternC(VarTemplateDecl *) { return false; }
  2527. /// \brief Check whether a redeclaration of an entity introduced by a
  2528. /// using-declaration is valid, given that we know it's not an overload
  2529. /// (nor a hidden tag declaration).
  2530. template<typename ExpectedDecl>
  2531. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2532. ExpectedDecl *New) {
  2533. // C++11 [basic.scope.declarative]p4:
  2534. // Given a set of declarations in a single declarative region, each of
  2535. // which specifies the same unqualified name,
  2536. // -- they shall all refer to the same entity, or all refer to functions
  2537. // and function templates; or
  2538. // -- exactly one declaration shall declare a class name or enumeration
  2539. // name that is not a typedef name and the other declarations shall all
  2540. // refer to the same variable or enumerator, or all refer to functions
  2541. // and function templates; in this case the class name or enumeration
  2542. // name is hidden (3.3.10).
  2543. // C++11 [namespace.udecl]p14:
  2544. // If a function declaration in namespace scope or block scope has the
  2545. // same name and the same parameter-type-list as a function introduced
  2546. // by a using-declaration, and the declarations do not declare the same
  2547. // function, the program is ill-formed.
  2548. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2549. if (Old &&
  2550. !Old->getDeclContext()->getRedeclContext()->Equals(
  2551. New->getDeclContext()->getRedeclContext()) &&
  2552. !(isExternC(Old) && isExternC(New)))
  2553. Old = nullptr;
  2554. if (!Old) {
  2555. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2556. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2557. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2558. return true;
  2559. }
  2560. return false;
  2561. }
  2562. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2563. const FunctionDecl *B) {
  2564. assert(A->getNumParams() == B->getNumParams());
  2565. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2566. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2567. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2568. if (AttrA == AttrB)
  2569. return true;
  2570. return AttrA && AttrB && AttrA->getType() == AttrB->getType();
  2571. };
  2572. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2573. }
  2574. /// If necessary, adjust the semantic declaration context for a qualified
  2575. /// declaration to name the correct inline namespace within the qualifier.
  2576. static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
  2577. DeclaratorDecl *OldD) {
  2578. // The only case where we need to update the DeclContext is when
  2579. // redeclaration lookup for a qualified name finds a declaration
  2580. // in an inline namespace within the context named by the qualifier:
  2581. //
  2582. // inline namespace N { int f(); }
  2583. // int ::f(); // Sema DC needs adjusting from :: to N::.
  2584. //
  2585. // For unqualified declarations, the semantic context *can* change
  2586. // along the redeclaration chain (for local extern declarations,
  2587. // extern "C" declarations, and friend declarations in particular).
  2588. if (!NewD->getQualifier())
  2589. return;
  2590. // NewD is probably already in the right context.
  2591. auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
  2592. auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
  2593. if (NamedDC->Equals(SemaDC))
  2594. return;
  2595. assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
  2596. NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
  2597. "unexpected context for redeclaration");
  2598. auto *LexDC = NewD->getLexicalDeclContext();
  2599. auto FixSemaDC = [=](NamedDecl *D) {
  2600. if (!D)
  2601. return;
  2602. D->setDeclContext(SemaDC);
  2603. D->setLexicalDeclContext(LexDC);
  2604. };
  2605. FixSemaDC(NewD);
  2606. if (auto *FD = dyn_cast<FunctionDecl>(NewD))
  2607. FixSemaDC(FD->getDescribedFunctionTemplate());
  2608. else if (auto *VD = dyn_cast<VarDecl>(NewD))
  2609. FixSemaDC(VD->getDescribedVarTemplate());
  2610. }
  2611. /// MergeFunctionDecl - We just parsed a function 'New' from
  2612. /// declarator D which has the same name and scope as a previous
  2613. /// declaration 'Old'. Figure out how to resolve this situation,
  2614. /// merging decls or emitting diagnostics as appropriate.
  2615. ///
  2616. /// In C++, New and Old must be declarations that are not
  2617. /// overloaded. Use IsOverload to determine whether New and Old are
  2618. /// overloaded, and to select the Old declaration that New should be
  2619. /// merged with.
  2620. ///
  2621. /// Returns true if there was an error, false otherwise.
  2622. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2623. Scope *S, bool MergeTypeWithOld) {
  2624. // Verify the old decl was also a function.
  2625. FunctionDecl *Old = OldD->getAsFunction();
  2626. if (!Old) {
  2627. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2628. if (New->getFriendObjectKind()) {
  2629. Diag(New->getLocation(), diag::err_using_decl_friend);
  2630. Diag(Shadow->getTargetDecl()->getLocation(),
  2631. diag::note_using_decl_target);
  2632. Diag(Shadow->getUsingDecl()->getLocation(),
  2633. diag::note_using_decl) << 0;
  2634. return true;
  2635. }
  2636. // Check whether the two declarations might declare the same function.
  2637. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2638. return true;
  2639. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2640. } else {
  2641. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2642. << New->getDeclName();
  2643. notePreviousDefinition(OldD, New->getLocation());
  2644. return true;
  2645. }
  2646. }
  2647. // If the old declaration is invalid, just give up here.
  2648. if (Old->isInvalidDecl())
  2649. return true;
  2650. // Disallow redeclaration of some builtins.
  2651. if (!getASTContext().canBuiltinBeRedeclared(Old)) {
  2652. Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
  2653. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  2654. << Old << Old->getType();
  2655. return true;
  2656. }
  2657. diag::kind PrevDiag;
  2658. SourceLocation OldLocation;
  2659. std::tie(PrevDiag, OldLocation) =
  2660. getNoteDiagForInvalidRedeclaration(Old, New);
  2661. // Don't complain about this if we're in GNU89 mode and the old function
  2662. // is an extern inline function.
  2663. // Don't complain about specializations. They are not supposed to have
  2664. // storage classes.
  2665. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2666. New->getStorageClass() == SC_Static &&
  2667. Old->hasExternalFormalLinkage() &&
  2668. !New->getTemplateSpecializationInfo() &&
  2669. !canRedefineFunction(Old, getLangOpts())) {
  2670. if (getLangOpts().MicrosoftExt) {
  2671. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2672. Diag(OldLocation, PrevDiag);
  2673. } else {
  2674. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2675. Diag(OldLocation, PrevDiag);
  2676. return true;
  2677. }
  2678. }
  2679. if (New->hasAttr<InternalLinkageAttr>() &&
  2680. !Old->hasAttr<InternalLinkageAttr>()) {
  2681. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  2682. << New->getDeclName();
  2683. notePreviousDefinition(Old, New->getLocation());
  2684. New->dropAttr<InternalLinkageAttr>();
  2685. }
  2686. if (CheckRedeclarationModuleOwnership(New, Old))
  2687. return true;
  2688. if (!getLangOpts().CPlusPlus) {
  2689. bool OldOvl = Old->hasAttr<OverloadableAttr>();
  2690. if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
  2691. Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
  2692. << New << OldOvl;
  2693. // Try our best to find a decl that actually has the overloadable
  2694. // attribute for the note. In most cases (e.g. programs with only one
  2695. // broken declaration/definition), this won't matter.
  2696. //
  2697. // FIXME: We could do this if we juggled some extra state in
  2698. // OverloadableAttr, rather than just removing it.
  2699. const Decl *DiagOld = Old;
  2700. if (OldOvl) {
  2701. auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
  2702. const auto *A = D->getAttr<OverloadableAttr>();
  2703. return A && !A->isImplicit();
  2704. });
  2705. // If we've implicitly added *all* of the overloadable attrs to this
  2706. // chain, emitting a "previous redecl" note is pointless.
  2707. DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
  2708. }
  2709. if (DiagOld)
  2710. Diag(DiagOld->getLocation(),
  2711. diag::note_attribute_overloadable_prev_overload)
  2712. << OldOvl;
  2713. if (OldOvl)
  2714. New->addAttr(OverloadableAttr::CreateImplicit(Context));
  2715. else
  2716. New->dropAttr<OverloadableAttr>();
  2717. }
  2718. }
  2719. // If a function is first declared with a calling convention, but is later
  2720. // declared or defined without one, all following decls assume the calling
  2721. // convention of the first.
  2722. //
  2723. // It's OK if a function is first declared without a calling convention,
  2724. // but is later declared or defined with the default calling convention.
  2725. //
  2726. // To test if either decl has an explicit calling convention, we look for
  2727. // AttributedType sugar nodes on the type as written. If they are missing or
  2728. // were canonicalized away, we assume the calling convention was implicit.
  2729. //
  2730. // Note also that we DO NOT return at this point, because we still have
  2731. // other tests to run.
  2732. QualType OldQType = Context.getCanonicalType(Old->getType());
  2733. QualType NewQType = Context.getCanonicalType(New->getType());
  2734. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2735. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2736. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2737. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2738. bool RequiresAdjustment = false;
  2739. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2740. FunctionDecl *First = Old->getFirstDecl();
  2741. const FunctionType *FT =
  2742. First->getType().getCanonicalType()->castAs<FunctionType>();
  2743. FunctionType::ExtInfo FI = FT->getExtInfo();
  2744. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2745. if (!NewCCExplicit) {
  2746. // Inherit the CC from the previous declaration if it was specified
  2747. // there but not here.
  2748. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2749. RequiresAdjustment = true;
  2750. } else {
  2751. // Calling conventions aren't compatible, so complain.
  2752. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2753. Diag(New->getLocation(), diag::err_cconv_change)
  2754. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2755. << !FirstCCExplicit
  2756. << (!FirstCCExplicit ? "" :
  2757. FunctionType::getNameForCallConv(FI.getCC()));
  2758. // Put the note on the first decl, since it is the one that matters.
  2759. Diag(First->getLocation(), diag::note_previous_declaration);
  2760. return true;
  2761. }
  2762. }
  2763. // FIXME: diagnose the other way around?
  2764. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2765. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2766. RequiresAdjustment = true;
  2767. }
  2768. // Merge regparm attribute.
  2769. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2770. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2771. if (NewTypeInfo.getHasRegParm()) {
  2772. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2773. << NewType->getRegParmType()
  2774. << OldType->getRegParmType();
  2775. Diag(OldLocation, diag::note_previous_declaration);
  2776. return true;
  2777. }
  2778. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2779. RequiresAdjustment = true;
  2780. }
  2781. // Merge ns_returns_retained attribute.
  2782. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2783. if (NewTypeInfo.getProducesResult()) {
  2784. Diag(New->getLocation(), diag::err_function_attribute_mismatch)
  2785. << "'ns_returns_retained'";
  2786. Diag(OldLocation, diag::note_previous_declaration);
  2787. return true;
  2788. }
  2789. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2790. RequiresAdjustment = true;
  2791. }
  2792. if (OldTypeInfo.getNoCallerSavedRegs() !=
  2793. NewTypeInfo.getNoCallerSavedRegs()) {
  2794. if (NewTypeInfo.getNoCallerSavedRegs()) {
  2795. AnyX86NoCallerSavedRegistersAttr *Attr =
  2796. New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
  2797. Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
  2798. Diag(OldLocation, diag::note_previous_declaration);
  2799. return true;
  2800. }
  2801. NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
  2802. RequiresAdjustment = true;
  2803. }
  2804. if (RequiresAdjustment) {
  2805. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2806. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2807. New->setType(QualType(AdjustedType, 0));
  2808. NewQType = Context.getCanonicalType(New->getType());
  2809. NewType = cast<FunctionType>(NewQType);
  2810. }
  2811. // If this redeclaration makes the function inline, we may need to add it to
  2812. // UndefinedButUsed.
  2813. if (!Old->isInlined() && New->isInlined() &&
  2814. !New->hasAttr<GNUInlineAttr>() &&
  2815. !getLangOpts().GNUInline &&
  2816. Old->isUsed(false) &&
  2817. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2818. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2819. SourceLocation()));
  2820. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2821. // about it.
  2822. if (New->hasAttr<GNUInlineAttr>() &&
  2823. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2824. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2825. }
  2826. // If pass_object_size params don't match up perfectly, this isn't a valid
  2827. // redeclaration.
  2828. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  2829. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  2830. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  2831. << New->getDeclName();
  2832. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2833. return true;
  2834. }
  2835. if (getLangOpts().CPlusPlus) {
  2836. // C++1z [over.load]p2
  2837. // Certain function declarations cannot be overloaded:
  2838. // -- Function declarations that differ only in the return type,
  2839. // the exception specification, or both cannot be overloaded.
  2840. // Check the exception specifications match. This may recompute the type of
  2841. // both Old and New if it resolved exception specifications, so grab the
  2842. // types again after this. Because this updates the type, we do this before
  2843. // any of the other checks below, which may update the "de facto" NewQType
  2844. // but do not necessarily update the type of New.
  2845. if (CheckEquivalentExceptionSpec(Old, New))
  2846. return true;
  2847. OldQType = Context.getCanonicalType(Old->getType());
  2848. NewQType = Context.getCanonicalType(New->getType());
  2849. // Go back to the type source info to compare the declared return types,
  2850. // per C++1y [dcl.type.auto]p13:
  2851. // Redeclarations or specializations of a function or function template
  2852. // with a declared return type that uses a placeholder type shall also
  2853. // use that placeholder, not a deduced type.
  2854. QualType OldDeclaredReturnType =
  2855. (Old->getTypeSourceInfo()
  2856. ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2857. : OldType)->getReturnType();
  2858. QualType NewDeclaredReturnType =
  2859. (New->getTypeSourceInfo()
  2860. ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2861. : NewType)->getReturnType();
  2862. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  2863. !((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2864. New->isLocalExternDecl())) {
  2865. QualType ResQT;
  2866. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  2867. OldDeclaredReturnType->isObjCObjectPointerType())
  2868. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  2869. if (ResQT.isNull()) {
  2870. if (New->isCXXClassMember() && New->isOutOfLine())
  2871. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  2872. << New << New->getReturnTypeSourceRange();
  2873. else
  2874. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  2875. << New->getReturnTypeSourceRange();
  2876. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  2877. << Old->getReturnTypeSourceRange();
  2878. return true;
  2879. }
  2880. else
  2881. NewQType = ResQT;
  2882. }
  2883. QualType OldReturnType = OldType->getReturnType();
  2884. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  2885. if (OldReturnType != NewReturnType) {
  2886. // If this function has a deduced return type and has already been
  2887. // defined, copy the deduced value from the old declaration.
  2888. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  2889. if (OldAT && OldAT->isDeduced()) {
  2890. New->setType(
  2891. SubstAutoType(New->getType(),
  2892. OldAT->isDependentType() ? Context.DependentTy
  2893. : OldAT->getDeducedType()));
  2894. NewQType = Context.getCanonicalType(
  2895. SubstAutoType(NewQType,
  2896. OldAT->isDependentType() ? Context.DependentTy
  2897. : OldAT->getDeducedType()));
  2898. }
  2899. }
  2900. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  2901. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  2902. if (OldMethod && NewMethod) {
  2903. // Preserve triviality.
  2904. NewMethod->setTrivial(OldMethod->isTrivial());
  2905. // MSVC allows explicit template specialization at class scope:
  2906. // 2 CXXMethodDecls referring to the same function will be injected.
  2907. // We don't want a redeclaration error.
  2908. bool IsClassScopeExplicitSpecialization =
  2909. OldMethod->isFunctionTemplateSpecialization() &&
  2910. NewMethod->isFunctionTemplateSpecialization();
  2911. bool isFriend = NewMethod->getFriendObjectKind();
  2912. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  2913. !IsClassScopeExplicitSpecialization) {
  2914. // -- Member function declarations with the same name and the
  2915. // same parameter types cannot be overloaded if any of them
  2916. // is a static member function declaration.
  2917. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  2918. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  2919. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2920. return true;
  2921. }
  2922. // C++ [class.mem]p1:
  2923. // [...] A member shall not be declared twice in the
  2924. // member-specification, except that a nested class or member
  2925. // class template can be declared and then later defined.
  2926. if (!inTemplateInstantiation()) {
  2927. unsigned NewDiag;
  2928. if (isa<CXXConstructorDecl>(OldMethod))
  2929. NewDiag = diag::err_constructor_redeclared;
  2930. else if (isa<CXXDestructorDecl>(NewMethod))
  2931. NewDiag = diag::err_destructor_redeclared;
  2932. else if (isa<CXXConversionDecl>(NewMethod))
  2933. NewDiag = diag::err_conv_function_redeclared;
  2934. else
  2935. NewDiag = diag::err_member_redeclared;
  2936. Diag(New->getLocation(), NewDiag);
  2937. } else {
  2938. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2939. << New << New->getType();
  2940. }
  2941. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2942. return true;
  2943. // Complain if this is an explicit declaration of a special
  2944. // member that was initially declared implicitly.
  2945. //
  2946. // As an exception, it's okay to befriend such methods in order
  2947. // to permit the implicit constructor/destructor/operator calls.
  2948. } else if (OldMethod->isImplicit()) {
  2949. if (isFriend) {
  2950. NewMethod->setImplicit();
  2951. } else {
  2952. Diag(NewMethod->getLocation(),
  2953. diag::err_definition_of_implicitly_declared_member)
  2954. << New << getSpecialMember(OldMethod);
  2955. return true;
  2956. }
  2957. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  2958. Diag(NewMethod->getLocation(),
  2959. diag::err_definition_of_explicitly_defaulted_member)
  2960. << getSpecialMember(OldMethod);
  2961. return true;
  2962. }
  2963. }
  2964. // C++11 [dcl.attr.noreturn]p1:
  2965. // The first declaration of a function shall specify the noreturn
  2966. // attribute if any declaration of that function specifies the noreturn
  2967. // attribute.
  2968. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  2969. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  2970. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  2971. Diag(Old->getFirstDecl()->getLocation(),
  2972. diag::note_noreturn_missing_first_decl);
  2973. }
  2974. // C++11 [dcl.attr.depend]p2:
  2975. // The first declaration of a function shall specify the
  2976. // carries_dependency attribute for its declarator-id if any declaration
  2977. // of the function specifies the carries_dependency attribute.
  2978. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  2979. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  2980. Diag(CDA->getLocation(),
  2981. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  2982. Diag(Old->getFirstDecl()->getLocation(),
  2983. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  2984. }
  2985. // (C++98 8.3.5p3):
  2986. // All declarations for a function shall agree exactly in both the
  2987. // return type and the parameter-type-list.
  2988. // We also want to respect all the extended bits except noreturn.
  2989. // noreturn should now match unless the old type info didn't have it.
  2990. QualType OldQTypeForComparison = OldQType;
  2991. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  2992. auto *OldType = OldQType->castAs<FunctionProtoType>();
  2993. const FunctionType *OldTypeForComparison
  2994. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  2995. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  2996. assert(OldQTypeForComparison.isCanonical());
  2997. }
  2998. if (haveIncompatibleLanguageLinkages(Old, New)) {
  2999. // As a special case, retain the language linkage from previous
  3000. // declarations of a friend function as an extension.
  3001. //
  3002. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  3003. // and is useful because there's otherwise no way to specify language
  3004. // linkage within class scope.
  3005. //
  3006. // Check cautiously as the friend object kind isn't yet complete.
  3007. if (New->getFriendObjectKind() != Decl::FOK_None) {
  3008. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  3009. Diag(OldLocation, PrevDiag);
  3010. } else {
  3011. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3012. Diag(OldLocation, PrevDiag);
  3013. return true;
  3014. }
  3015. }
  3016. if (OldQTypeForComparison == NewQType)
  3017. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3018. if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
  3019. New->isLocalExternDecl()) {
  3020. // It's OK if we couldn't merge types for a local function declaraton
  3021. // if either the old or new type is dependent. We'll merge the types
  3022. // when we instantiate the function.
  3023. return false;
  3024. }
  3025. // Fall through for conflicting redeclarations and redefinitions.
  3026. }
  3027. // C: Function types need to be compatible, not identical. This handles
  3028. // duplicate function decls like "void f(int); void f(enum X);" properly.
  3029. if (!getLangOpts().CPlusPlus &&
  3030. Context.typesAreCompatible(OldQType, NewQType)) {
  3031. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  3032. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  3033. const FunctionProtoType *OldProto = nullptr;
  3034. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  3035. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  3036. // The old declaration provided a function prototype, but the
  3037. // new declaration does not. Merge in the prototype.
  3038. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  3039. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  3040. NewQType =
  3041. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  3042. OldProto->getExtProtoInfo());
  3043. New->setType(NewQType);
  3044. New->setHasInheritedPrototype();
  3045. // Synthesize parameters with the same types.
  3046. SmallVector<ParmVarDecl*, 16> Params;
  3047. for (const auto &ParamType : OldProto->param_types()) {
  3048. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  3049. SourceLocation(), nullptr,
  3050. ParamType, /*TInfo=*/nullptr,
  3051. SC_None, nullptr);
  3052. Param->setScopeInfo(0, Params.size());
  3053. Param->setImplicit();
  3054. Params.push_back(Param);
  3055. }
  3056. New->setParams(Params);
  3057. }
  3058. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3059. }
  3060. // GNU C permits a K&R definition to follow a prototype declaration
  3061. // if the declared types of the parameters in the K&R definition
  3062. // match the types in the prototype declaration, even when the
  3063. // promoted types of the parameters from the K&R definition differ
  3064. // from the types in the prototype. GCC then keeps the types from
  3065. // the prototype.
  3066. //
  3067. // If a variadic prototype is followed by a non-variadic K&R definition,
  3068. // the K&R definition becomes variadic. This is sort of an edge case, but
  3069. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  3070. // C99 6.9.1p8.
  3071. if (!getLangOpts().CPlusPlus &&
  3072. Old->hasPrototype() && !New->hasPrototype() &&
  3073. New->getType()->getAs<FunctionProtoType>() &&
  3074. Old->getNumParams() == New->getNumParams()) {
  3075. SmallVector<QualType, 16> ArgTypes;
  3076. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  3077. const FunctionProtoType *OldProto
  3078. = Old->getType()->getAs<FunctionProtoType>();
  3079. const FunctionProtoType *NewProto
  3080. = New->getType()->getAs<FunctionProtoType>();
  3081. // Determine whether this is the GNU C extension.
  3082. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  3083. NewProto->getReturnType());
  3084. bool LooseCompatible = !MergedReturn.isNull();
  3085. for (unsigned Idx = 0, End = Old->getNumParams();
  3086. LooseCompatible && Idx != End; ++Idx) {
  3087. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  3088. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  3089. if (Context.typesAreCompatible(OldParm->getType(),
  3090. NewProto->getParamType(Idx))) {
  3091. ArgTypes.push_back(NewParm->getType());
  3092. } else if (Context.typesAreCompatible(OldParm->getType(),
  3093. NewParm->getType(),
  3094. /*CompareUnqualified=*/true)) {
  3095. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  3096. NewProto->getParamType(Idx) };
  3097. Warnings.push_back(Warn);
  3098. ArgTypes.push_back(NewParm->getType());
  3099. } else
  3100. LooseCompatible = false;
  3101. }
  3102. if (LooseCompatible) {
  3103. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  3104. Diag(Warnings[Warn].NewParm->getLocation(),
  3105. diag::ext_param_promoted_not_compatible_with_prototype)
  3106. << Warnings[Warn].PromotedType
  3107. << Warnings[Warn].OldParm->getType();
  3108. if (Warnings[Warn].OldParm->getLocation().isValid())
  3109. Diag(Warnings[Warn].OldParm->getLocation(),
  3110. diag::note_previous_declaration);
  3111. }
  3112. if (MergeTypeWithOld)
  3113. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  3114. OldProto->getExtProtoInfo()));
  3115. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3116. }
  3117. // Fall through to diagnose conflicting types.
  3118. }
  3119. // A function that has already been declared has been redeclared or
  3120. // defined with a different type; show an appropriate diagnostic.
  3121. // If the previous declaration was an implicitly-generated builtin
  3122. // declaration, then at the very least we should use a specialized note.
  3123. unsigned BuiltinID;
  3124. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  3125. // If it's actually a library-defined builtin function like 'malloc'
  3126. // or 'printf', just warn about the incompatible redeclaration.
  3127. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  3128. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  3129. Diag(OldLocation, diag::note_previous_builtin_declaration)
  3130. << Old << Old->getType();
  3131. // If this is a global redeclaration, just forget hereafter
  3132. // about the "builtin-ness" of the function.
  3133. //
  3134. // Doing this for local extern declarations is problematic. If
  3135. // the builtin declaration remains visible, a second invalid
  3136. // local declaration will produce a hard error; if it doesn't
  3137. // remain visible, a single bogus local redeclaration (which is
  3138. // actually only a warning) could break all the downstream code.
  3139. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  3140. New->getIdentifier()->revertBuiltin();
  3141. return false;
  3142. }
  3143. PrevDiag = diag::note_previous_builtin_declaration;
  3144. }
  3145. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  3146. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3147. return true;
  3148. }
  3149. /// \brief Completes the merge of two function declarations that are
  3150. /// known to be compatible.
  3151. ///
  3152. /// This routine handles the merging of attributes and other
  3153. /// properties of function declarations from the old declaration to
  3154. /// the new declaration, once we know that New is in fact a
  3155. /// redeclaration of Old.
  3156. ///
  3157. /// \returns false
  3158. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  3159. Scope *S, bool MergeTypeWithOld) {
  3160. // Merge the attributes
  3161. mergeDeclAttributes(New, Old);
  3162. // Merge "pure" flag.
  3163. if (Old->isPure())
  3164. New->setPure();
  3165. // Merge "used" flag.
  3166. if (Old->getMostRecentDecl()->isUsed(false))
  3167. New->setIsUsed();
  3168. // Merge attributes from the parameters. These can mismatch with K&R
  3169. // declarations.
  3170. if (New->getNumParams() == Old->getNumParams())
  3171. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  3172. ParmVarDecl *NewParam = New->getParamDecl(i);
  3173. ParmVarDecl *OldParam = Old->getParamDecl(i);
  3174. mergeParamDeclAttributes(NewParam, OldParam, *this);
  3175. mergeParamDeclTypes(NewParam, OldParam, *this);
  3176. }
  3177. if (getLangOpts().CPlusPlus)
  3178. return MergeCXXFunctionDecl(New, Old, S);
  3179. // Merge the function types so the we get the composite types for the return
  3180. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  3181. // was visible.
  3182. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  3183. if (!Merged.isNull() && MergeTypeWithOld)
  3184. New->setType(Merged);
  3185. return false;
  3186. }
  3187. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  3188. ObjCMethodDecl *oldMethod) {
  3189. // Merge the attributes, including deprecated/unavailable
  3190. AvailabilityMergeKind MergeKind =
  3191. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  3192. ? AMK_ProtocolImplementation
  3193. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  3194. : AMK_Override;
  3195. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  3196. // Merge attributes from the parameters.
  3197. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3198. oe = oldMethod->param_end();
  3199. for (ObjCMethodDecl::param_iterator
  3200. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3201. ni != ne && oi != oe; ++ni, ++oi)
  3202. mergeParamDeclAttributes(*ni, *oi, *this);
  3203. CheckObjCMethodOverride(newMethod, oldMethod);
  3204. }
  3205. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3206. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3207. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3208. ? diag::err_redefinition_different_type
  3209. : diag::err_redeclaration_different_type)
  3210. << New->getDeclName() << New->getType() << Old->getType();
  3211. diag::kind PrevDiag;
  3212. SourceLocation OldLocation;
  3213. std::tie(PrevDiag, OldLocation)
  3214. = getNoteDiagForInvalidRedeclaration(Old, New);
  3215. S.Diag(OldLocation, PrevDiag);
  3216. New->setInvalidDecl();
  3217. }
  3218. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3219. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3220. /// emitting diagnostics as appropriate.
  3221. ///
  3222. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3223. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3224. /// is attached.
  3225. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3226. bool MergeTypeWithOld) {
  3227. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3228. return;
  3229. QualType MergedT;
  3230. if (getLangOpts().CPlusPlus) {
  3231. if (New->getType()->isUndeducedType()) {
  3232. // We don't know what the new type is until the initializer is attached.
  3233. return;
  3234. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3235. // These could still be something that needs exception specs checked.
  3236. return MergeVarDeclExceptionSpecs(New, Old);
  3237. }
  3238. // C++ [basic.link]p10:
  3239. // [...] the types specified by all declarations referring to a given
  3240. // object or function shall be identical, except that declarations for an
  3241. // array object can specify array types that differ by the presence or
  3242. // absence of a major array bound (8.3.4).
  3243. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3244. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3245. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3246. // We are merging a variable declaration New into Old. If it has an array
  3247. // bound, and that bound differs from Old's bound, we should diagnose the
  3248. // mismatch.
  3249. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3250. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3251. PrevVD = PrevVD->getPreviousDecl()) {
  3252. const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
  3253. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3254. continue;
  3255. if (!Context.hasSameType(NewArray, PrevVDTy))
  3256. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3257. }
  3258. }
  3259. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3260. if (Context.hasSameType(OldArray->getElementType(),
  3261. NewArray->getElementType()))
  3262. MergedT = New->getType();
  3263. }
  3264. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3265. // has no array bound, it should not inherit one from Old, if Old is not
  3266. // visible.
  3267. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3268. if (Context.hasSameType(OldArray->getElementType(),
  3269. NewArray->getElementType()))
  3270. MergedT = Old->getType();
  3271. }
  3272. }
  3273. else if (New->getType()->isObjCObjectPointerType() &&
  3274. Old->getType()->isObjCObjectPointerType()) {
  3275. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3276. Old->getType());
  3277. }
  3278. } else {
  3279. // C 6.2.7p2:
  3280. // All declarations that refer to the same object or function shall have
  3281. // compatible type.
  3282. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3283. }
  3284. if (MergedT.isNull()) {
  3285. // It's OK if we couldn't merge types if either type is dependent, for a
  3286. // block-scope variable. In other cases (static data members of class
  3287. // templates, variable templates, ...), we require the types to be
  3288. // equivalent.
  3289. // FIXME: The C++ standard doesn't say anything about this.
  3290. if ((New->getType()->isDependentType() ||
  3291. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3292. // If the old type was dependent, we can't merge with it, so the new type
  3293. // becomes dependent for now. We'll reproduce the original type when we
  3294. // instantiate the TypeSourceInfo for the variable.
  3295. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3296. New->setType(Context.DependentTy);
  3297. return;
  3298. }
  3299. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3300. }
  3301. // Don't actually update the type on the new declaration if the old
  3302. // declaration was an extern declaration in a different scope.
  3303. if (MergeTypeWithOld)
  3304. New->setType(MergedT);
  3305. }
  3306. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3307. LookupResult &Previous) {
  3308. // C11 6.2.7p4:
  3309. // For an identifier with internal or external linkage declared
  3310. // in a scope in which a prior declaration of that identifier is
  3311. // visible, if the prior declaration specifies internal or
  3312. // external linkage, the type of the identifier at the later
  3313. // declaration becomes the composite type.
  3314. //
  3315. // If the variable isn't visible, we do not merge with its type.
  3316. if (Previous.isShadowed())
  3317. return false;
  3318. if (S.getLangOpts().CPlusPlus) {
  3319. // C++11 [dcl.array]p3:
  3320. // If there is a preceding declaration of the entity in the same
  3321. // scope in which the bound was specified, an omitted array bound
  3322. // is taken to be the same as in that earlier declaration.
  3323. return NewVD->isPreviousDeclInSameBlockScope() ||
  3324. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3325. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3326. } else {
  3327. // If the old declaration was function-local, don't merge with its
  3328. // type unless we're in the same function.
  3329. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3330. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3331. }
  3332. }
  3333. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3334. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3335. /// situation, merging decls or emitting diagnostics as appropriate.
  3336. ///
  3337. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3338. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3339. /// definitions here, since the initializer hasn't been attached.
  3340. ///
  3341. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3342. // If the new decl is already invalid, don't do any other checking.
  3343. if (New->isInvalidDecl())
  3344. return;
  3345. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3346. return;
  3347. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3348. // Verify the old decl was also a variable or variable template.
  3349. VarDecl *Old = nullptr;
  3350. VarTemplateDecl *OldTemplate = nullptr;
  3351. if (Previous.isSingleResult()) {
  3352. if (NewTemplate) {
  3353. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3354. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3355. if (auto *Shadow =
  3356. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3357. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3358. return New->setInvalidDecl();
  3359. } else {
  3360. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3361. if (auto *Shadow =
  3362. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3363. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3364. return New->setInvalidDecl();
  3365. }
  3366. }
  3367. if (!Old) {
  3368. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3369. << New->getDeclName();
  3370. notePreviousDefinition(Previous.getRepresentativeDecl(),
  3371. New->getLocation());
  3372. return New->setInvalidDecl();
  3373. }
  3374. // Ensure the template parameters are compatible.
  3375. if (NewTemplate &&
  3376. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3377. OldTemplate->getTemplateParameters(),
  3378. /*Complain=*/true, TPL_TemplateMatch))
  3379. return New->setInvalidDecl();
  3380. // C++ [class.mem]p1:
  3381. // A member shall not be declared twice in the member-specification [...]
  3382. //
  3383. // Here, we need only consider static data members.
  3384. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3385. Diag(New->getLocation(), diag::err_duplicate_member)
  3386. << New->getIdentifier();
  3387. Diag(Old->getLocation(), diag::note_previous_declaration);
  3388. New->setInvalidDecl();
  3389. }
  3390. mergeDeclAttributes(New, Old);
  3391. // Warn if an already-declared variable is made a weak_import in a subsequent
  3392. // declaration
  3393. if (New->hasAttr<WeakImportAttr>() &&
  3394. Old->getStorageClass() == SC_None &&
  3395. !Old->hasAttr<WeakImportAttr>()) {
  3396. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3397. notePreviousDefinition(Old, New->getLocation());
  3398. // Remove weak_import attribute on new declaration.
  3399. New->dropAttr<WeakImportAttr>();
  3400. }
  3401. if (New->hasAttr<InternalLinkageAttr>() &&
  3402. !Old->hasAttr<InternalLinkageAttr>()) {
  3403. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  3404. << New->getDeclName();
  3405. notePreviousDefinition(Old, New->getLocation());
  3406. New->dropAttr<InternalLinkageAttr>();
  3407. }
  3408. // Merge the types.
  3409. VarDecl *MostRecent = Old->getMostRecentDecl();
  3410. if (MostRecent != Old) {
  3411. MergeVarDeclTypes(New, MostRecent,
  3412. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3413. if (New->isInvalidDecl())
  3414. return;
  3415. }
  3416. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3417. if (New->isInvalidDecl())
  3418. return;
  3419. diag::kind PrevDiag;
  3420. SourceLocation OldLocation;
  3421. std::tie(PrevDiag, OldLocation) =
  3422. getNoteDiagForInvalidRedeclaration(Old, New);
  3423. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3424. if (New->getStorageClass() == SC_Static &&
  3425. !New->isStaticDataMember() &&
  3426. Old->hasExternalFormalLinkage()) {
  3427. if (getLangOpts().MicrosoftExt) {
  3428. Diag(New->getLocation(), diag::ext_static_non_static)
  3429. << New->getDeclName();
  3430. Diag(OldLocation, PrevDiag);
  3431. } else {
  3432. Diag(New->getLocation(), diag::err_static_non_static)
  3433. << New->getDeclName();
  3434. Diag(OldLocation, PrevDiag);
  3435. return New->setInvalidDecl();
  3436. }
  3437. }
  3438. // C99 6.2.2p4:
  3439. // For an identifier declared with the storage-class specifier
  3440. // extern in a scope in which a prior declaration of that
  3441. // identifier is visible,23) if the prior declaration specifies
  3442. // internal or external linkage, the linkage of the identifier at
  3443. // the later declaration is the same as the linkage specified at
  3444. // the prior declaration. If no prior declaration is visible, or
  3445. // if the prior declaration specifies no linkage, then the
  3446. // identifier has external linkage.
  3447. if (New->hasExternalStorage() && Old->hasLinkage())
  3448. /* Okay */;
  3449. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3450. !New->isStaticDataMember() &&
  3451. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3452. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3453. Diag(OldLocation, PrevDiag);
  3454. return New->setInvalidDecl();
  3455. }
  3456. // Check if extern is followed by non-extern and vice-versa.
  3457. if (New->hasExternalStorage() &&
  3458. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3459. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3460. Diag(OldLocation, PrevDiag);
  3461. return New->setInvalidDecl();
  3462. }
  3463. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3464. !New->hasExternalStorage()) {
  3465. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3466. Diag(OldLocation, PrevDiag);
  3467. return New->setInvalidDecl();
  3468. }
  3469. if (CheckRedeclarationModuleOwnership(New, Old))
  3470. return;
  3471. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3472. // FIXME: The test for external storage here seems wrong? We still
  3473. // need to check for mismatches.
  3474. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3475. // Don't complain about out-of-line definitions of static members.
  3476. !(Old->getLexicalDeclContext()->isRecord() &&
  3477. !New->getLexicalDeclContext()->isRecord())) {
  3478. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3479. Diag(OldLocation, PrevDiag);
  3480. return New->setInvalidDecl();
  3481. }
  3482. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3483. if (VarDecl *Def = Old->getDefinition()) {
  3484. // C++1z [dcl.fcn.spec]p4:
  3485. // If the definition of a variable appears in a translation unit before
  3486. // its first declaration as inline, the program is ill-formed.
  3487. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3488. Diag(Def->getLocation(), diag::note_previous_definition);
  3489. }
  3490. }
  3491. // If this redeclaration makes the variable inline, we may need to add it to
  3492. // UndefinedButUsed.
  3493. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3494. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3495. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3496. SourceLocation()));
  3497. if (New->getTLSKind() != Old->getTLSKind()) {
  3498. if (!Old->getTLSKind()) {
  3499. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3500. Diag(OldLocation, PrevDiag);
  3501. } else if (!New->getTLSKind()) {
  3502. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3503. Diag(OldLocation, PrevDiag);
  3504. } else {
  3505. // Do not allow redeclaration to change the variable between requiring
  3506. // static and dynamic initialization.
  3507. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3508. // declaration to determine the kind. Do we need to be compatible here?
  3509. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3510. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3511. Diag(OldLocation, PrevDiag);
  3512. }
  3513. }
  3514. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3515. if (getLangOpts().CPlusPlus &&
  3516. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3517. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3518. Old->getCanonicalDecl()->isConstexpr()) {
  3519. // This definition won't be a definition any more once it's been merged.
  3520. Diag(New->getLocation(),
  3521. diag::warn_deprecated_redundant_constexpr_static_def);
  3522. } else if (VarDecl *Def = Old->getDefinition()) {
  3523. if (checkVarDeclRedefinition(Def, New))
  3524. return;
  3525. }
  3526. }
  3527. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3528. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3529. Diag(OldLocation, PrevDiag);
  3530. New->setInvalidDecl();
  3531. return;
  3532. }
  3533. // Merge "used" flag.
  3534. if (Old->getMostRecentDecl()->isUsed(false))
  3535. New->setIsUsed();
  3536. // Keep a chain of previous declarations.
  3537. New->setPreviousDecl(Old);
  3538. if (NewTemplate)
  3539. NewTemplate->setPreviousDecl(OldTemplate);
  3540. adjustDeclContextForDeclaratorDecl(New, Old);
  3541. // Inherit access appropriately.
  3542. New->setAccess(Old->getAccess());
  3543. if (NewTemplate)
  3544. NewTemplate->setAccess(New->getAccess());
  3545. if (Old->isInline())
  3546. New->setImplicitlyInline();
  3547. }
  3548. void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
  3549. SourceManager &SrcMgr = getSourceManager();
  3550. auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
  3551. auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
  3552. auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
  3553. auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
  3554. auto &HSI = PP.getHeaderSearchInfo();
  3555. StringRef HdrFilename =
  3556. SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
  3557. auto noteFromModuleOrInclude = [&](Module *Mod,
  3558. SourceLocation IncLoc) -> bool {
  3559. // Redefinition errors with modules are common with non modular mapped
  3560. // headers, example: a non-modular header H in module A that also gets
  3561. // included directly in a TU. Pointing twice to the same header/definition
  3562. // is confusing, try to get better diagnostics when modules is on.
  3563. if (IncLoc.isValid()) {
  3564. if (Mod) {
  3565. Diag(IncLoc, diag::note_redefinition_modules_same_file)
  3566. << HdrFilename.str() << Mod->getFullModuleName();
  3567. if (!Mod->DefinitionLoc.isInvalid())
  3568. Diag(Mod->DefinitionLoc, diag::note_defined_here)
  3569. << Mod->getFullModuleName();
  3570. } else {
  3571. Diag(IncLoc, diag::note_redefinition_include_same_file)
  3572. << HdrFilename.str();
  3573. }
  3574. return true;
  3575. }
  3576. return false;
  3577. };
  3578. // Is it the same file and same offset? Provide more information on why
  3579. // this leads to a redefinition error.
  3580. bool EmittedDiag = false;
  3581. if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
  3582. SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
  3583. SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
  3584. EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
  3585. EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
  3586. // If the header has no guards, emit a note suggesting one.
  3587. if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
  3588. Diag(Old->getLocation(), diag::note_use_ifdef_guards);
  3589. if (EmittedDiag)
  3590. return;
  3591. }
  3592. // Redefinition coming from different files or couldn't do better above.
  3593. if (Old->getLocation().isValid())
  3594. Diag(Old->getLocation(), diag::note_previous_definition);
  3595. }
  3596. /// We've just determined that \p Old and \p New both appear to be definitions
  3597. /// of the same variable. Either diagnose or fix the problem.
  3598. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3599. if (!hasVisibleDefinition(Old) &&
  3600. (New->getFormalLinkage() == InternalLinkage ||
  3601. New->isInline() ||
  3602. New->getDescribedVarTemplate() ||
  3603. New->getNumTemplateParameterLists() ||
  3604. New->getDeclContext()->isDependentContext())) {
  3605. // The previous definition is hidden, and multiple definitions are
  3606. // permitted (in separate TUs). Demote this to a declaration.
  3607. New->demoteThisDefinitionToDeclaration();
  3608. // Make the canonical definition visible.
  3609. if (auto *OldTD = Old->getDescribedVarTemplate())
  3610. makeMergedDefinitionVisible(OldTD);
  3611. makeMergedDefinitionVisible(Old);
  3612. return false;
  3613. } else {
  3614. Diag(New->getLocation(), diag::err_redefinition) << New;
  3615. notePreviousDefinition(Old, New->getLocation());
  3616. New->setInvalidDecl();
  3617. return true;
  3618. }
  3619. }
  3620. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3621. /// no declarator (e.g. "struct foo;") is parsed.
  3622. Decl *
  3623. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3624. RecordDecl *&AnonRecord) {
  3625. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3626. AnonRecord);
  3627. }
  3628. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3629. // disambiguate entities defined in different scopes.
  3630. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3631. // compatibility.
  3632. // We will pick our mangling number depending on which version of MSVC is being
  3633. // targeted.
  3634. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3635. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3636. ? S->getMSCurManglingNumber()
  3637. : S->getMSLastManglingNumber();
  3638. }
  3639. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3640. if (!Context.getLangOpts().CPlusPlus)
  3641. return;
  3642. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3643. // If this tag is the direct child of a class, number it if
  3644. // it is anonymous.
  3645. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3646. return;
  3647. MangleNumberingContext &MCtx =
  3648. Context.getManglingNumberContext(Tag->getParent());
  3649. Context.setManglingNumber(
  3650. Tag, MCtx.getManglingNumber(
  3651. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3652. return;
  3653. }
  3654. // If this tag isn't a direct child of a class, number it if it is local.
  3655. Decl *ManglingContextDecl;
  3656. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3657. Tag->getDeclContext(), ManglingContextDecl)) {
  3658. Context.setManglingNumber(
  3659. Tag, MCtx->getManglingNumber(
  3660. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3661. }
  3662. }
  3663. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3664. TypedefNameDecl *NewTD) {
  3665. if (TagFromDeclSpec->isInvalidDecl())
  3666. return;
  3667. // Do nothing if the tag already has a name for linkage purposes.
  3668. if (TagFromDeclSpec->hasNameForLinkage())
  3669. return;
  3670. // A well-formed anonymous tag must always be a TUK_Definition.
  3671. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3672. // The type must match the tag exactly; no qualifiers allowed.
  3673. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3674. Context.getTagDeclType(TagFromDeclSpec))) {
  3675. if (getLangOpts().CPlusPlus)
  3676. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3677. return;
  3678. }
  3679. // If we've already computed linkage for the anonymous tag, then
  3680. // adding a typedef name for the anonymous decl can change that
  3681. // linkage, which might be a serious problem. Diagnose this as
  3682. // unsupported and ignore the typedef name. TODO: we should
  3683. // pursue this as a language defect and establish a formal rule
  3684. // for how to handle it.
  3685. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3686. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3687. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3688. tagLoc = getLocForEndOfToken(tagLoc);
  3689. llvm::SmallString<40> textToInsert;
  3690. textToInsert += ' ';
  3691. textToInsert += NewTD->getIdentifier()->getName();
  3692. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3693. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3694. return;
  3695. }
  3696. // Otherwise, set this is the anon-decl typedef for the tag.
  3697. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3698. }
  3699. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3700. switch (T) {
  3701. case DeclSpec::TST_class:
  3702. return 0;
  3703. case DeclSpec::TST_struct:
  3704. return 1;
  3705. case DeclSpec::TST_interface:
  3706. return 2;
  3707. case DeclSpec::TST_union:
  3708. return 3;
  3709. case DeclSpec::TST_enum:
  3710. return 4;
  3711. default:
  3712. llvm_unreachable("unexpected type specifier");
  3713. }
  3714. }
  3715. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3716. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3717. /// parameters to cope with template friend declarations.
  3718. Decl *
  3719. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3720. MultiTemplateParamsArg TemplateParams,
  3721. bool IsExplicitInstantiation,
  3722. RecordDecl *&AnonRecord) {
  3723. Decl *TagD = nullptr;
  3724. TagDecl *Tag = nullptr;
  3725. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3726. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3727. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3728. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3729. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3730. TagD = DS.getRepAsDecl();
  3731. if (!TagD) // We probably had an error
  3732. return nullptr;
  3733. // Note that the above type specs guarantee that the
  3734. // type rep is a Decl, whereas in many of the others
  3735. // it's a Type.
  3736. if (isa<TagDecl>(TagD))
  3737. Tag = cast<TagDecl>(TagD);
  3738. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3739. Tag = CTD->getTemplatedDecl();
  3740. }
  3741. if (Tag) {
  3742. handleTagNumbering(Tag, S);
  3743. Tag->setFreeStanding();
  3744. if (Tag->isInvalidDecl())
  3745. return Tag;
  3746. }
  3747. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3748. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3749. // or incomplete types shall not be restrict-qualified."
  3750. if (TypeQuals & DeclSpec::TQ_restrict)
  3751. Diag(DS.getRestrictSpecLoc(),
  3752. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3753. << DS.getSourceRange();
  3754. }
  3755. if (DS.isInlineSpecified())
  3756. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  3757. << getLangOpts().CPlusPlus17;
  3758. if (DS.isConstexprSpecified()) {
  3759. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3760. // and definitions of functions and variables.
  3761. if (Tag)
  3762. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3763. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
  3764. else
  3765. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  3766. // Don't emit warnings after this error.
  3767. return TagD;
  3768. }
  3769. DiagnoseFunctionSpecifiers(DS);
  3770. if (DS.isFriendSpecified()) {
  3771. // If we're dealing with a decl but not a TagDecl, assume that
  3772. // whatever routines created it handled the friendship aspect.
  3773. if (TagD && !Tag)
  3774. return nullptr;
  3775. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3776. }
  3777. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3778. bool IsExplicitSpecialization =
  3779. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3780. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3781. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  3782. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  3783. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3784. // nested-name-specifier unless it is an explicit instantiation
  3785. // or an explicit specialization.
  3786. //
  3787. // FIXME: We allow class template partial specializations here too, per the
  3788. // obvious intent of DR1819.
  3789. //
  3790. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3791. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3792. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3793. return nullptr;
  3794. }
  3795. // Track whether this decl-specifier declares anything.
  3796. bool DeclaresAnything = true;
  3797. // Handle anonymous struct definitions.
  3798. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3799. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3800. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3801. if (getLangOpts().CPlusPlus ||
  3802. Record->getDeclContext()->isRecord()) {
  3803. // If CurContext is a DeclContext that can contain statements,
  3804. // RecursiveASTVisitor won't visit the decls that
  3805. // BuildAnonymousStructOrUnion() will put into CurContext.
  3806. // Also store them here so that they can be part of the
  3807. // DeclStmt that gets created in this case.
  3808. // FIXME: Also return the IndirectFieldDecls created by
  3809. // BuildAnonymousStructOr union, for the same reason?
  3810. if (CurContext->isFunctionOrMethod())
  3811. AnonRecord = Record;
  3812. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3813. Context.getPrintingPolicy());
  3814. }
  3815. DeclaresAnything = false;
  3816. }
  3817. }
  3818. // C11 6.7.2.1p2:
  3819. // A struct-declaration that does not declare an anonymous structure or
  3820. // anonymous union shall contain a struct-declarator-list.
  3821. //
  3822. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3823. // did not permit a struct-declaration without a struct-declarator-list.
  3824. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3825. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3826. // Check for Microsoft C extension: anonymous struct/union member.
  3827. // Handle 2 kinds of anonymous struct/union:
  3828. // struct STRUCT;
  3829. // union UNION;
  3830. // and
  3831. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3832. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3833. if ((Tag && Tag->getDeclName()) ||
  3834. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3835. RecordDecl *Record = nullptr;
  3836. if (Tag)
  3837. Record = dyn_cast<RecordDecl>(Tag);
  3838. else if (const RecordType *RT =
  3839. DS.getRepAsType().get()->getAsStructureType())
  3840. Record = RT->getDecl();
  3841. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3842. Record = UT->getDecl();
  3843. if (Record && getLangOpts().MicrosoftExt) {
  3844. Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
  3845. << Record->isUnion() << DS.getSourceRange();
  3846. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3847. }
  3848. DeclaresAnything = false;
  3849. }
  3850. }
  3851. // Skip all the checks below if we have a type error.
  3852. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3853. (TagD && TagD->isInvalidDecl()))
  3854. return TagD;
  3855. if (getLangOpts().CPlusPlus &&
  3856. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3857. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  3858. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  3859. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  3860. DeclaresAnything = false;
  3861. if (!DS.isMissingDeclaratorOk()) {
  3862. // Customize diagnostic for a typedef missing a name.
  3863. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  3864. Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
  3865. << DS.getSourceRange();
  3866. else
  3867. DeclaresAnything = false;
  3868. }
  3869. if (DS.isModulePrivateSpecified() &&
  3870. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  3871. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  3872. << Tag->getTagKind()
  3873. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  3874. ActOnDocumentableDecl(TagD);
  3875. // C 6.7/2:
  3876. // A declaration [...] shall declare at least a declarator [...], a tag,
  3877. // or the members of an enumeration.
  3878. // C++ [dcl.dcl]p3:
  3879. // [If there are no declarators], and except for the declaration of an
  3880. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  3881. // names into the program, or shall redeclare a name introduced by a
  3882. // previous declaration.
  3883. if (!DeclaresAnything) {
  3884. // In C, we allow this as a (popular) extension / bug. Don't bother
  3885. // producing further diagnostics for redundant qualifiers after this.
  3886. Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
  3887. return TagD;
  3888. }
  3889. // C++ [dcl.stc]p1:
  3890. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  3891. // init-declarator-list of the declaration shall not be empty.
  3892. // C++ [dcl.fct.spec]p1:
  3893. // If a cv-qualifier appears in a decl-specifier-seq, the
  3894. // init-declarator-list of the declaration shall not be empty.
  3895. //
  3896. // Spurious qualifiers here appear to be valid in C.
  3897. unsigned DiagID = diag::warn_standalone_specifier;
  3898. if (getLangOpts().CPlusPlus)
  3899. DiagID = diag::ext_standalone_specifier;
  3900. // Note that a linkage-specification sets a storage class, but
  3901. // 'extern "C" struct foo;' is actually valid and not theoretically
  3902. // useless.
  3903. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3904. if (SCS == DeclSpec::SCS_mutable)
  3905. // Since mutable is not a viable storage class specifier in C, there is
  3906. // no reason to treat it as an extension. Instead, diagnose as an error.
  3907. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  3908. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  3909. Diag(DS.getStorageClassSpecLoc(), DiagID)
  3910. << DeclSpec::getSpecifierName(SCS);
  3911. }
  3912. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  3913. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  3914. << DeclSpec::getSpecifierName(TSCS);
  3915. if (DS.getTypeQualifiers()) {
  3916. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3917. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  3918. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3919. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  3920. // Restrict is covered above.
  3921. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3922. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  3923. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  3924. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  3925. }
  3926. // Warn about ignored type attributes, for example:
  3927. // __attribute__((aligned)) struct A;
  3928. // Attributes should be placed after tag to apply to type declaration.
  3929. if (!DS.getAttributes().empty()) {
  3930. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  3931. if (TypeSpecType == DeclSpec::TST_class ||
  3932. TypeSpecType == DeclSpec::TST_struct ||
  3933. TypeSpecType == DeclSpec::TST_interface ||
  3934. TypeSpecType == DeclSpec::TST_union ||
  3935. TypeSpecType == DeclSpec::TST_enum) {
  3936. for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
  3937. attrs = attrs->getNext())
  3938. Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
  3939. << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  3940. }
  3941. }
  3942. return TagD;
  3943. }
  3944. /// We are trying to inject an anonymous member into the given scope;
  3945. /// check if there's an existing declaration that can't be overloaded.
  3946. ///
  3947. /// \return true if this is a forbidden redeclaration
  3948. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  3949. Scope *S,
  3950. DeclContext *Owner,
  3951. DeclarationName Name,
  3952. SourceLocation NameLoc,
  3953. bool IsUnion) {
  3954. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  3955. Sema::ForVisibleRedeclaration);
  3956. if (!SemaRef.LookupName(R, S)) return false;
  3957. // Pick a representative declaration.
  3958. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  3959. assert(PrevDecl && "Expected a non-null Decl");
  3960. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  3961. return false;
  3962. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  3963. << IsUnion << Name;
  3964. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  3965. return true;
  3966. }
  3967. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  3968. /// anonymous struct or union AnonRecord into the owning context Owner
  3969. /// and scope S. This routine will be invoked just after we realize
  3970. /// that an unnamed union or struct is actually an anonymous union or
  3971. /// struct, e.g.,
  3972. ///
  3973. /// @code
  3974. /// union {
  3975. /// int i;
  3976. /// float f;
  3977. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  3978. /// // f into the surrounding scope.x
  3979. /// @endcode
  3980. ///
  3981. /// This routine is recursive, injecting the names of nested anonymous
  3982. /// structs/unions into the owning context and scope as well.
  3983. static bool
  3984. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  3985. RecordDecl *AnonRecord, AccessSpecifier AS,
  3986. SmallVectorImpl<NamedDecl *> &Chaining) {
  3987. bool Invalid = false;
  3988. // Look every FieldDecl and IndirectFieldDecl with a name.
  3989. for (auto *D : AnonRecord->decls()) {
  3990. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  3991. cast<NamedDecl>(D)->getDeclName()) {
  3992. ValueDecl *VD = cast<ValueDecl>(D);
  3993. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  3994. VD->getLocation(),
  3995. AnonRecord->isUnion())) {
  3996. // C++ [class.union]p2:
  3997. // The names of the members of an anonymous union shall be
  3998. // distinct from the names of any other entity in the
  3999. // scope in which the anonymous union is declared.
  4000. Invalid = true;
  4001. } else {
  4002. // C++ [class.union]p2:
  4003. // For the purpose of name lookup, after the anonymous union
  4004. // definition, the members of the anonymous union are
  4005. // considered to have been defined in the scope in which the
  4006. // anonymous union is declared.
  4007. unsigned OldChainingSize = Chaining.size();
  4008. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  4009. Chaining.append(IF->chain_begin(), IF->chain_end());
  4010. else
  4011. Chaining.push_back(VD);
  4012. assert(Chaining.size() >= 2);
  4013. NamedDecl **NamedChain =
  4014. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  4015. for (unsigned i = 0; i < Chaining.size(); i++)
  4016. NamedChain[i] = Chaining[i];
  4017. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  4018. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  4019. VD->getType(), {NamedChain, Chaining.size()});
  4020. for (const auto *Attr : VD->attrs())
  4021. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  4022. IndirectField->setAccess(AS);
  4023. IndirectField->setImplicit();
  4024. SemaRef.PushOnScopeChains(IndirectField, S);
  4025. // That includes picking up the appropriate access specifier.
  4026. if (AS != AS_none) IndirectField->setAccess(AS);
  4027. Chaining.resize(OldChainingSize);
  4028. }
  4029. }
  4030. }
  4031. return Invalid;
  4032. }
  4033. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  4034. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  4035. /// illegal input values are mapped to SC_None.
  4036. static StorageClass
  4037. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  4038. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  4039. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  4040. "Parser allowed 'typedef' as storage class VarDecl.");
  4041. switch (StorageClassSpec) {
  4042. case DeclSpec::SCS_unspecified: return SC_None;
  4043. case DeclSpec::SCS_extern:
  4044. if (DS.isExternInLinkageSpec())
  4045. return SC_None;
  4046. return SC_Extern;
  4047. case DeclSpec::SCS_static: return SC_Static;
  4048. case DeclSpec::SCS_auto: return SC_Auto;
  4049. case DeclSpec::SCS_register: return SC_Register;
  4050. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4051. // Illegal SCSs map to None: error reporting is up to the caller.
  4052. case DeclSpec::SCS_mutable: // Fall through.
  4053. case DeclSpec::SCS_typedef: return SC_None;
  4054. }
  4055. llvm_unreachable("unknown storage class specifier");
  4056. }
  4057. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  4058. assert(Record->hasInClassInitializer());
  4059. for (const auto *I : Record->decls()) {
  4060. const auto *FD = dyn_cast<FieldDecl>(I);
  4061. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  4062. FD = IFD->getAnonField();
  4063. if (FD && FD->hasInClassInitializer())
  4064. return FD->getLocation();
  4065. }
  4066. llvm_unreachable("couldn't find in-class initializer");
  4067. }
  4068. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4069. SourceLocation DefaultInitLoc) {
  4070. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4071. return;
  4072. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  4073. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  4074. }
  4075. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4076. CXXRecordDecl *AnonUnion) {
  4077. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4078. return;
  4079. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  4080. }
  4081. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  4082. /// anonymous structure or union. Anonymous unions are a C++ feature
  4083. /// (C++ [class.union]) and a C11 feature; anonymous structures
  4084. /// are a C11 feature and GNU C++ extension.
  4085. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  4086. AccessSpecifier AS,
  4087. RecordDecl *Record,
  4088. const PrintingPolicy &Policy) {
  4089. DeclContext *Owner = Record->getDeclContext();
  4090. // Diagnose whether this anonymous struct/union is an extension.
  4091. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  4092. Diag(Record->getLocation(), diag::ext_anonymous_union);
  4093. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  4094. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  4095. else if (!Record->isUnion() && !getLangOpts().C11)
  4096. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  4097. // C and C++ require different kinds of checks for anonymous
  4098. // structs/unions.
  4099. bool Invalid = false;
  4100. if (getLangOpts().CPlusPlus) {
  4101. const char *PrevSpec = nullptr;
  4102. unsigned DiagID;
  4103. if (Record->isUnion()) {
  4104. // C++ [class.union]p6:
  4105. // Anonymous unions declared in a named namespace or in the
  4106. // global namespace shall be declared static.
  4107. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  4108. (isa<TranslationUnitDecl>(Owner) ||
  4109. (isa<NamespaceDecl>(Owner) &&
  4110. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  4111. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  4112. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  4113. // Recover by adding 'static'.
  4114. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  4115. PrevSpec, DiagID, Policy);
  4116. }
  4117. // C++ [class.union]p6:
  4118. // A storage class is not allowed in a declaration of an
  4119. // anonymous union in a class scope.
  4120. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  4121. isa<RecordDecl>(Owner)) {
  4122. Diag(DS.getStorageClassSpecLoc(),
  4123. diag::err_anonymous_union_with_storage_spec)
  4124. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  4125. // Recover by removing the storage specifier.
  4126. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  4127. SourceLocation(),
  4128. PrevSpec, DiagID, Context.getPrintingPolicy());
  4129. }
  4130. }
  4131. // Ignore const/volatile/restrict qualifiers.
  4132. if (DS.getTypeQualifiers()) {
  4133. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4134. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  4135. << Record->isUnion() << "const"
  4136. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  4137. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4138. Diag(DS.getVolatileSpecLoc(),
  4139. diag::ext_anonymous_struct_union_qualified)
  4140. << Record->isUnion() << "volatile"
  4141. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  4142. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  4143. Diag(DS.getRestrictSpecLoc(),
  4144. diag::ext_anonymous_struct_union_qualified)
  4145. << Record->isUnion() << "restrict"
  4146. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  4147. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4148. Diag(DS.getAtomicSpecLoc(),
  4149. diag::ext_anonymous_struct_union_qualified)
  4150. << Record->isUnion() << "_Atomic"
  4151. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  4152. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4153. Diag(DS.getUnalignedSpecLoc(),
  4154. diag::ext_anonymous_struct_union_qualified)
  4155. << Record->isUnion() << "__unaligned"
  4156. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  4157. DS.ClearTypeQualifiers();
  4158. }
  4159. // C++ [class.union]p2:
  4160. // The member-specification of an anonymous union shall only
  4161. // define non-static data members. [Note: nested types and
  4162. // functions cannot be declared within an anonymous union. ]
  4163. for (auto *Mem : Record->decls()) {
  4164. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  4165. // C++ [class.union]p3:
  4166. // An anonymous union shall not have private or protected
  4167. // members (clause 11).
  4168. assert(FD->getAccess() != AS_none);
  4169. if (FD->getAccess() != AS_public) {
  4170. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  4171. << Record->isUnion() << (FD->getAccess() == AS_protected);
  4172. Invalid = true;
  4173. }
  4174. // C++ [class.union]p1
  4175. // An object of a class with a non-trivial constructor, a non-trivial
  4176. // copy constructor, a non-trivial destructor, or a non-trivial copy
  4177. // assignment operator cannot be a member of a union, nor can an
  4178. // array of such objects.
  4179. if (CheckNontrivialField(FD))
  4180. Invalid = true;
  4181. } else if (Mem->isImplicit()) {
  4182. // Any implicit members are fine.
  4183. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  4184. // This is a type that showed up in an
  4185. // elaborated-type-specifier inside the anonymous struct or
  4186. // union, but which actually declares a type outside of the
  4187. // anonymous struct or union. It's okay.
  4188. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  4189. if (!MemRecord->isAnonymousStructOrUnion() &&
  4190. MemRecord->getDeclName()) {
  4191. // Visual C++ allows type definition in anonymous struct or union.
  4192. if (getLangOpts().MicrosoftExt)
  4193. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  4194. << Record->isUnion();
  4195. else {
  4196. // This is a nested type declaration.
  4197. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  4198. << Record->isUnion();
  4199. Invalid = true;
  4200. }
  4201. } else {
  4202. // This is an anonymous type definition within another anonymous type.
  4203. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  4204. // not part of standard C++.
  4205. Diag(MemRecord->getLocation(),
  4206. diag::ext_anonymous_record_with_anonymous_type)
  4207. << Record->isUnion();
  4208. }
  4209. } else if (isa<AccessSpecDecl>(Mem)) {
  4210. // Any access specifier is fine.
  4211. } else if (isa<StaticAssertDecl>(Mem)) {
  4212. // In C++1z, static_assert declarations are also fine.
  4213. } else {
  4214. // We have something that isn't a non-static data
  4215. // member. Complain about it.
  4216. unsigned DK = diag::err_anonymous_record_bad_member;
  4217. if (isa<TypeDecl>(Mem))
  4218. DK = diag::err_anonymous_record_with_type;
  4219. else if (isa<FunctionDecl>(Mem))
  4220. DK = diag::err_anonymous_record_with_function;
  4221. else if (isa<VarDecl>(Mem))
  4222. DK = diag::err_anonymous_record_with_static;
  4223. // Visual C++ allows type definition in anonymous struct or union.
  4224. if (getLangOpts().MicrosoftExt &&
  4225. DK == diag::err_anonymous_record_with_type)
  4226. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  4227. << Record->isUnion();
  4228. else {
  4229. Diag(Mem->getLocation(), DK) << Record->isUnion();
  4230. Invalid = true;
  4231. }
  4232. }
  4233. }
  4234. // C++11 [class.union]p8 (DR1460):
  4235. // At most one variant member of a union may have a
  4236. // brace-or-equal-initializer.
  4237. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  4238. Owner->isRecord())
  4239. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  4240. cast<CXXRecordDecl>(Record));
  4241. }
  4242. if (!Record->isUnion() && !Owner->isRecord()) {
  4243. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  4244. << getLangOpts().CPlusPlus;
  4245. Invalid = true;
  4246. }
  4247. // Mock up a declarator.
  4248. Declarator Dc(DS, DeclaratorContext::MemberContext);
  4249. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4250. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  4251. // Create a declaration for this anonymous struct/union.
  4252. NamedDecl *Anon = nullptr;
  4253. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  4254. Anon = FieldDecl::Create(Context, OwningClass,
  4255. DS.getLocStart(),
  4256. Record->getLocation(),
  4257. /*IdentifierInfo=*/nullptr,
  4258. Context.getTypeDeclType(Record),
  4259. TInfo,
  4260. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4261. /*InitStyle=*/ICIS_NoInit);
  4262. Anon->setAccess(AS);
  4263. if (getLangOpts().CPlusPlus)
  4264. FieldCollector->Add(cast<FieldDecl>(Anon));
  4265. } else {
  4266. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  4267. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  4268. if (SCSpec == DeclSpec::SCS_mutable) {
  4269. // mutable can only appear on non-static class members, so it's always
  4270. // an error here
  4271. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  4272. Invalid = true;
  4273. SC = SC_None;
  4274. }
  4275. Anon = VarDecl::Create(Context, Owner,
  4276. DS.getLocStart(),
  4277. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  4278. Context.getTypeDeclType(Record),
  4279. TInfo, SC);
  4280. // Default-initialize the implicit variable. This initialization will be
  4281. // trivial in almost all cases, except if a union member has an in-class
  4282. // initializer:
  4283. // union { int n = 0; };
  4284. ActOnUninitializedDecl(Anon);
  4285. }
  4286. Anon->setImplicit();
  4287. // Mark this as an anonymous struct/union type.
  4288. Record->setAnonymousStructOrUnion(true);
  4289. // Add the anonymous struct/union object to the current
  4290. // context. We'll be referencing this object when we refer to one of
  4291. // its members.
  4292. Owner->addDecl(Anon);
  4293. // Inject the members of the anonymous struct/union into the owning
  4294. // context and into the identifier resolver chain for name lookup
  4295. // purposes.
  4296. SmallVector<NamedDecl*, 2> Chain;
  4297. Chain.push_back(Anon);
  4298. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4299. Invalid = true;
  4300. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4301. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4302. Decl *ManglingContextDecl;
  4303. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  4304. NewVD->getDeclContext(), ManglingContextDecl)) {
  4305. Context.setManglingNumber(
  4306. NewVD, MCtx->getManglingNumber(
  4307. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4308. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4309. }
  4310. }
  4311. }
  4312. if (Invalid)
  4313. Anon->setInvalidDecl();
  4314. return Anon;
  4315. }
  4316. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4317. /// Microsoft C anonymous structure.
  4318. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4319. /// Example:
  4320. ///
  4321. /// struct A { int a; };
  4322. /// struct B { struct A; int b; };
  4323. ///
  4324. /// void foo() {
  4325. /// B var;
  4326. /// var.a = 3;
  4327. /// }
  4328. ///
  4329. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4330. RecordDecl *Record) {
  4331. assert(Record && "expected a record!");
  4332. // Mock up a declarator.
  4333. Declarator Dc(DS, DeclaratorContext::TypeNameContext);
  4334. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4335. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4336. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4337. QualType RecTy = Context.getTypeDeclType(Record);
  4338. // Create a declaration for this anonymous struct.
  4339. NamedDecl *Anon = FieldDecl::Create(Context,
  4340. ParentDecl,
  4341. DS.getLocStart(),
  4342. DS.getLocStart(),
  4343. /*IdentifierInfo=*/nullptr,
  4344. RecTy,
  4345. TInfo,
  4346. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4347. /*InitStyle=*/ICIS_NoInit);
  4348. Anon->setImplicit();
  4349. // Add the anonymous struct object to the current context.
  4350. CurContext->addDecl(Anon);
  4351. // Inject the members of the anonymous struct into the current
  4352. // context and into the identifier resolver chain for name lookup
  4353. // purposes.
  4354. SmallVector<NamedDecl*, 2> Chain;
  4355. Chain.push_back(Anon);
  4356. RecordDecl *RecordDef = Record->getDefinition();
  4357. if (RequireCompleteType(Anon->getLocation(), RecTy,
  4358. diag::err_field_incomplete) ||
  4359. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4360. AS_none, Chain)) {
  4361. Anon->setInvalidDecl();
  4362. ParentDecl->setInvalidDecl();
  4363. }
  4364. return Anon;
  4365. }
  4366. /// GetNameForDeclarator - Determine the full declaration name for the
  4367. /// given Declarator.
  4368. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4369. return GetNameFromUnqualifiedId(D.getName());
  4370. }
  4371. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  4372. DeclarationNameInfo
  4373. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4374. DeclarationNameInfo NameInfo;
  4375. NameInfo.setLoc(Name.StartLocation);
  4376. switch (Name.getKind()) {
  4377. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  4378. case UnqualifiedIdKind::IK_Identifier:
  4379. NameInfo.setName(Name.Identifier);
  4380. NameInfo.setLoc(Name.StartLocation);
  4381. return NameInfo;
  4382. case UnqualifiedIdKind::IK_DeductionGuideName: {
  4383. // C++ [temp.deduct.guide]p3:
  4384. // The simple-template-id shall name a class template specialization.
  4385. // The template-name shall be the same identifier as the template-name
  4386. // of the simple-template-id.
  4387. // These together intend to imply that the template-name shall name a
  4388. // class template.
  4389. // FIXME: template<typename T> struct X {};
  4390. // template<typename T> using Y = X<T>;
  4391. // Y(int) -> Y<int>;
  4392. // satisfies these rules but does not name a class template.
  4393. TemplateName TN = Name.TemplateName.get().get();
  4394. auto *Template = TN.getAsTemplateDecl();
  4395. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  4396. Diag(Name.StartLocation,
  4397. diag::err_deduction_guide_name_not_class_template)
  4398. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  4399. if (Template)
  4400. Diag(Template->getLocation(), diag::note_template_decl_here);
  4401. return DeclarationNameInfo();
  4402. }
  4403. NameInfo.setName(
  4404. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  4405. NameInfo.setLoc(Name.StartLocation);
  4406. return NameInfo;
  4407. }
  4408. case UnqualifiedIdKind::IK_OperatorFunctionId:
  4409. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4410. Name.OperatorFunctionId.Operator));
  4411. NameInfo.setLoc(Name.StartLocation);
  4412. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  4413. = Name.OperatorFunctionId.SymbolLocations[0];
  4414. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  4415. = Name.EndLocation.getRawEncoding();
  4416. return NameInfo;
  4417. case UnqualifiedIdKind::IK_LiteralOperatorId:
  4418. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4419. Name.Identifier));
  4420. NameInfo.setLoc(Name.StartLocation);
  4421. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4422. return NameInfo;
  4423. case UnqualifiedIdKind::IK_ConversionFunctionId: {
  4424. TypeSourceInfo *TInfo;
  4425. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4426. if (Ty.isNull())
  4427. return DeclarationNameInfo();
  4428. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4429. Context.getCanonicalType(Ty)));
  4430. NameInfo.setLoc(Name.StartLocation);
  4431. NameInfo.setNamedTypeInfo(TInfo);
  4432. return NameInfo;
  4433. }
  4434. case UnqualifiedIdKind::IK_ConstructorName: {
  4435. TypeSourceInfo *TInfo;
  4436. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4437. if (Ty.isNull())
  4438. return DeclarationNameInfo();
  4439. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4440. Context.getCanonicalType(Ty)));
  4441. NameInfo.setLoc(Name.StartLocation);
  4442. NameInfo.setNamedTypeInfo(TInfo);
  4443. return NameInfo;
  4444. }
  4445. case UnqualifiedIdKind::IK_ConstructorTemplateId: {
  4446. // In well-formed code, we can only have a constructor
  4447. // template-id that refers to the current context, so go there
  4448. // to find the actual type being constructed.
  4449. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4450. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4451. return DeclarationNameInfo();
  4452. // Determine the type of the class being constructed.
  4453. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4454. // FIXME: Check two things: that the template-id names the same type as
  4455. // CurClassType, and that the template-id does not occur when the name
  4456. // was qualified.
  4457. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4458. Context.getCanonicalType(CurClassType)));
  4459. NameInfo.setLoc(Name.StartLocation);
  4460. // FIXME: should we retrieve TypeSourceInfo?
  4461. NameInfo.setNamedTypeInfo(nullptr);
  4462. return NameInfo;
  4463. }
  4464. case UnqualifiedIdKind::IK_DestructorName: {
  4465. TypeSourceInfo *TInfo;
  4466. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4467. if (Ty.isNull())
  4468. return DeclarationNameInfo();
  4469. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4470. Context.getCanonicalType(Ty)));
  4471. NameInfo.setLoc(Name.StartLocation);
  4472. NameInfo.setNamedTypeInfo(TInfo);
  4473. return NameInfo;
  4474. }
  4475. case UnqualifiedIdKind::IK_TemplateId: {
  4476. TemplateName TName = Name.TemplateId->Template.get();
  4477. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4478. return Context.getNameForTemplate(TName, TNameLoc);
  4479. }
  4480. } // switch (Name.getKind())
  4481. llvm_unreachable("Unknown name kind");
  4482. }
  4483. static QualType getCoreType(QualType Ty) {
  4484. do {
  4485. if (Ty->isPointerType() || Ty->isReferenceType())
  4486. Ty = Ty->getPointeeType();
  4487. else if (Ty->isArrayType())
  4488. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4489. else
  4490. return Ty.withoutLocalFastQualifiers();
  4491. } while (true);
  4492. }
  4493. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4494. /// and Definition have "nearly" matching parameters. This heuristic is
  4495. /// used to improve diagnostics in the case where an out-of-line function
  4496. /// definition doesn't match any declaration within the class or namespace.
  4497. /// Also sets Params to the list of indices to the parameters that differ
  4498. /// between the declaration and the definition. If hasSimilarParameters
  4499. /// returns true and Params is empty, then all of the parameters match.
  4500. static bool hasSimilarParameters(ASTContext &Context,
  4501. FunctionDecl *Declaration,
  4502. FunctionDecl *Definition,
  4503. SmallVectorImpl<unsigned> &Params) {
  4504. Params.clear();
  4505. if (Declaration->param_size() != Definition->param_size())
  4506. return false;
  4507. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4508. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4509. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4510. // The parameter types are identical
  4511. if (Context.hasSameType(DefParamTy, DeclParamTy))
  4512. continue;
  4513. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4514. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4515. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4516. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4517. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4518. (DeclTyName && DeclTyName == DefTyName))
  4519. Params.push_back(Idx);
  4520. else // The two parameters aren't even close
  4521. return false;
  4522. }
  4523. return true;
  4524. }
  4525. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4526. /// declarator needs to be rebuilt in the current instantiation.
  4527. /// Any bits of declarator which appear before the name are valid for
  4528. /// consideration here. That's specifically the type in the decl spec
  4529. /// and the base type in any member-pointer chunks.
  4530. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4531. DeclarationName Name) {
  4532. // The types we specifically need to rebuild are:
  4533. // - typenames, typeofs, and decltypes
  4534. // - types which will become injected class names
  4535. // Of course, we also need to rebuild any type referencing such a
  4536. // type. It's safest to just say "dependent", but we call out a
  4537. // few cases here.
  4538. DeclSpec &DS = D.getMutableDeclSpec();
  4539. switch (DS.getTypeSpecType()) {
  4540. case DeclSpec::TST_typename:
  4541. case DeclSpec::TST_typeofType:
  4542. case DeclSpec::TST_underlyingType:
  4543. case DeclSpec::TST_atomic: {
  4544. // Grab the type from the parser.
  4545. TypeSourceInfo *TSI = nullptr;
  4546. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4547. if (T.isNull() || !T->isDependentType()) break;
  4548. // Make sure there's a type source info. This isn't really much
  4549. // of a waste; most dependent types should have type source info
  4550. // attached already.
  4551. if (!TSI)
  4552. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4553. // Rebuild the type in the current instantiation.
  4554. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4555. if (!TSI) return true;
  4556. // Store the new type back in the decl spec.
  4557. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4558. DS.UpdateTypeRep(LocType);
  4559. break;
  4560. }
  4561. case DeclSpec::TST_decltype:
  4562. case DeclSpec::TST_typeofExpr: {
  4563. Expr *E = DS.getRepAsExpr();
  4564. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4565. if (Result.isInvalid()) return true;
  4566. DS.UpdateExprRep(Result.get());
  4567. break;
  4568. }
  4569. default:
  4570. // Nothing to do for these decl specs.
  4571. break;
  4572. }
  4573. // It doesn't matter what order we do this in.
  4574. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4575. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4576. // The only type information in the declarator which can come
  4577. // before the declaration name is the base type of a member
  4578. // pointer.
  4579. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4580. continue;
  4581. // Rebuild the scope specifier in-place.
  4582. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4583. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4584. return true;
  4585. }
  4586. return false;
  4587. }
  4588. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4589. D.setFunctionDefinitionKind(FDK_Declaration);
  4590. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4591. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4592. Dcl && Dcl->getDeclContext()->isFileContext())
  4593. Dcl->setTopLevelDeclInObjCContainer();
  4594. if (getLangOpts().OpenCL)
  4595. setCurrentOpenCLExtensionForDecl(Dcl);
  4596. return Dcl;
  4597. }
  4598. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4599. /// If T is the name of a class, then each of the following shall have a
  4600. /// name different from T:
  4601. /// - every static data member of class T;
  4602. /// - every member function of class T
  4603. /// - every member of class T that is itself a type;
  4604. /// \returns true if the declaration name violates these rules.
  4605. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4606. DeclarationNameInfo NameInfo) {
  4607. DeclarationName Name = NameInfo.getName();
  4608. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  4609. while (Record && Record->isAnonymousStructOrUnion())
  4610. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  4611. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  4612. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4613. return true;
  4614. }
  4615. return false;
  4616. }
  4617. /// \brief Diagnose a declaration whose declarator-id has the given
  4618. /// nested-name-specifier.
  4619. ///
  4620. /// \param SS The nested-name-specifier of the declarator-id.
  4621. ///
  4622. /// \param DC The declaration context to which the nested-name-specifier
  4623. /// resolves.
  4624. ///
  4625. /// \param Name The name of the entity being declared.
  4626. ///
  4627. /// \param Loc The location of the name of the entity being declared.
  4628. ///
  4629. /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
  4630. /// we're declaring an explicit / partial specialization / instantiation.
  4631. ///
  4632. /// \returns true if we cannot safely recover from this error, false otherwise.
  4633. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4634. DeclarationName Name,
  4635. SourceLocation Loc, bool IsTemplateId) {
  4636. DeclContext *Cur = CurContext;
  4637. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4638. Cur = Cur->getParent();
  4639. // If the user provided a superfluous scope specifier that refers back to the
  4640. // class in which the entity is already declared, diagnose and ignore it.
  4641. //
  4642. // class X {
  4643. // void X::f();
  4644. // };
  4645. //
  4646. // Note, it was once ill-formed to give redundant qualification in all
  4647. // contexts, but that rule was removed by DR482.
  4648. if (Cur->Equals(DC)) {
  4649. if (Cur->isRecord()) {
  4650. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4651. : diag::err_member_extra_qualification)
  4652. << Name << FixItHint::CreateRemoval(SS.getRange());
  4653. SS.clear();
  4654. } else {
  4655. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4656. }
  4657. return false;
  4658. }
  4659. // Check whether the qualifying scope encloses the scope of the original
  4660. // declaration. For a template-id, we perform the checks in
  4661. // CheckTemplateSpecializationScope.
  4662. if (!Cur->Encloses(DC) && !IsTemplateId) {
  4663. if (Cur->isRecord())
  4664. Diag(Loc, diag::err_member_qualification)
  4665. << Name << SS.getRange();
  4666. else if (isa<TranslationUnitDecl>(DC))
  4667. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4668. << Name << SS.getRange();
  4669. else if (isa<FunctionDecl>(Cur))
  4670. Diag(Loc, diag::err_invalid_declarator_in_function)
  4671. << Name << SS.getRange();
  4672. else if (isa<BlockDecl>(Cur))
  4673. Diag(Loc, diag::err_invalid_declarator_in_block)
  4674. << Name << SS.getRange();
  4675. else
  4676. Diag(Loc, diag::err_invalid_declarator_scope)
  4677. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4678. return true;
  4679. }
  4680. if (Cur->isRecord()) {
  4681. // Cannot qualify members within a class.
  4682. Diag(Loc, diag::err_member_qualification)
  4683. << Name << SS.getRange();
  4684. SS.clear();
  4685. // C++ constructors and destructors with incorrect scopes can break
  4686. // our AST invariants by having the wrong underlying types. If
  4687. // that's the case, then drop this declaration entirely.
  4688. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4689. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4690. !Context.hasSameType(Name.getCXXNameType(),
  4691. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4692. return true;
  4693. return false;
  4694. }
  4695. // C++11 [dcl.meaning]p1:
  4696. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4697. // not begin with a decltype-specifer"
  4698. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4699. while (SpecLoc.getPrefix())
  4700. SpecLoc = SpecLoc.getPrefix();
  4701. if (dyn_cast_or_null<DecltypeType>(
  4702. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4703. Diag(Loc, diag::err_decltype_in_declarator)
  4704. << SpecLoc.getTypeLoc().getSourceRange();
  4705. return false;
  4706. }
  4707. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4708. MultiTemplateParamsArg TemplateParamLists) {
  4709. // TODO: consider using NameInfo for diagnostic.
  4710. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4711. DeclarationName Name = NameInfo.getName();
  4712. // All of these full declarators require an identifier. If it doesn't have
  4713. // one, the ParsedFreeStandingDeclSpec action should be used.
  4714. if (D.isDecompositionDeclarator()) {
  4715. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  4716. } else if (!Name) {
  4717. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4718. Diag(D.getDeclSpec().getLocStart(),
  4719. diag::err_declarator_need_ident)
  4720. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4721. return nullptr;
  4722. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4723. return nullptr;
  4724. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4725. // we find one that is.
  4726. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4727. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4728. S = S->getParent();
  4729. DeclContext *DC = CurContext;
  4730. if (D.getCXXScopeSpec().isInvalid())
  4731. D.setInvalidType();
  4732. else if (D.getCXXScopeSpec().isSet()) {
  4733. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4734. UPPC_DeclarationQualifier))
  4735. return nullptr;
  4736. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4737. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4738. if (!DC || isa<EnumDecl>(DC)) {
  4739. // If we could not compute the declaration context, it's because the
  4740. // declaration context is dependent but does not refer to a class,
  4741. // class template, or class template partial specialization. Complain
  4742. // and return early, to avoid the coming semantic disaster.
  4743. Diag(D.getIdentifierLoc(),
  4744. diag::err_template_qualified_declarator_no_match)
  4745. << D.getCXXScopeSpec().getScopeRep()
  4746. << D.getCXXScopeSpec().getRange();
  4747. return nullptr;
  4748. }
  4749. bool IsDependentContext = DC->isDependentContext();
  4750. if (!IsDependentContext &&
  4751. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4752. return nullptr;
  4753. // If a class is incomplete, do not parse entities inside it.
  4754. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4755. Diag(D.getIdentifierLoc(),
  4756. diag::err_member_def_undefined_record)
  4757. << Name << DC << D.getCXXScopeSpec().getRange();
  4758. return nullptr;
  4759. }
  4760. if (!D.getDeclSpec().isFriendSpecified()) {
  4761. if (diagnoseQualifiedDeclaration(
  4762. D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
  4763. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
  4764. if (DC->isRecord())
  4765. return nullptr;
  4766. D.setInvalidType();
  4767. }
  4768. }
  4769. // Check whether we need to rebuild the type of the given
  4770. // declaration in the current instantiation.
  4771. if (EnteringContext && IsDependentContext &&
  4772. TemplateParamLists.size() != 0) {
  4773. ContextRAII SavedContext(*this, DC);
  4774. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4775. D.setInvalidType();
  4776. }
  4777. }
  4778. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4779. QualType R = TInfo->getType();
  4780. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4781. UPPC_DeclarationType))
  4782. D.setInvalidType();
  4783. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4784. forRedeclarationInCurContext());
  4785. // See if this is a redefinition of a variable in the same scope.
  4786. if (!D.getCXXScopeSpec().isSet()) {
  4787. bool IsLinkageLookup = false;
  4788. bool CreateBuiltins = false;
  4789. // If the declaration we're planning to build will be a function
  4790. // or object with linkage, then look for another declaration with
  4791. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4792. //
  4793. // If the declaration we're planning to build will be declared with
  4794. // external linkage in the translation unit, create any builtin with
  4795. // the same name.
  4796. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4797. /* Do nothing*/;
  4798. else if (CurContext->isFunctionOrMethod() &&
  4799. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4800. R->isFunctionType())) {
  4801. IsLinkageLookup = true;
  4802. CreateBuiltins =
  4803. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4804. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4805. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4806. CreateBuiltins = true;
  4807. if (IsLinkageLookup) {
  4808. Previous.clear(LookupRedeclarationWithLinkage);
  4809. Previous.setRedeclarationKind(ForExternalRedeclaration);
  4810. }
  4811. LookupName(Previous, S, CreateBuiltins);
  4812. } else { // Something like "int foo::x;"
  4813. LookupQualifiedName(Previous, DC);
  4814. // C++ [dcl.meaning]p1:
  4815. // When the declarator-id is qualified, the declaration shall refer to a
  4816. // previously declared member of the class or namespace to which the
  4817. // qualifier refers (or, in the case of a namespace, of an element of the
  4818. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4819. // thereof; [...]
  4820. //
  4821. // Note that we already checked the context above, and that we do not have
  4822. // enough information to make sure that Previous contains the declaration
  4823. // we want to match. For example, given:
  4824. //
  4825. // class X {
  4826. // void f();
  4827. // void f(float);
  4828. // };
  4829. //
  4830. // void X::f(int) { } // ill-formed
  4831. //
  4832. // In this case, Previous will point to the overload set
  4833. // containing the two f's declared in X, but neither of them
  4834. // matches.
  4835. // C++ [dcl.meaning]p1:
  4836. // [...] the member shall not merely have been introduced by a
  4837. // using-declaration in the scope of the class or namespace nominated by
  4838. // the nested-name-specifier of the declarator-id.
  4839. RemoveUsingDecls(Previous);
  4840. }
  4841. if (Previous.isSingleResult() &&
  4842. Previous.getFoundDecl()->isTemplateParameter()) {
  4843. // Maybe we will complain about the shadowed template parameter.
  4844. if (!D.isInvalidType())
  4845. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4846. Previous.getFoundDecl());
  4847. // Just pretend that we didn't see the previous declaration.
  4848. Previous.clear();
  4849. }
  4850. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4851. // Forget that the previous declaration is the injected-class-name.
  4852. Previous.clear();
  4853. // In C++, the previous declaration we find might be a tag type
  4854. // (class or enum). In this case, the new declaration will hide the
  4855. // tag type. Note that this applies to functions, function templates, and
  4856. // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
  4857. if (Previous.isSingleTagDecl() &&
  4858. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  4859. (TemplateParamLists.size() == 0 || R->isFunctionType()))
  4860. Previous.clear();
  4861. // Check that there are no default arguments other than in the parameters
  4862. // of a function declaration (C++ only).
  4863. if (getLangOpts().CPlusPlus)
  4864. CheckExtraCXXDefaultArguments(D);
  4865. NamedDecl *New;
  4866. bool AddToScope = true;
  4867. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  4868. if (TemplateParamLists.size()) {
  4869. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  4870. return nullptr;
  4871. }
  4872. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  4873. } else if (R->isFunctionType()) {
  4874. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  4875. TemplateParamLists,
  4876. AddToScope);
  4877. } else {
  4878. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  4879. AddToScope);
  4880. }
  4881. if (!New)
  4882. return nullptr;
  4883. // If this has an identifier and is not a function template specialization,
  4884. // add it to the scope stack.
  4885. if (New->getDeclName() && AddToScope) {
  4886. // Only make a locally-scoped extern declaration visible if it is the first
  4887. // declaration of this entity. Qualified lookup for such an entity should
  4888. // only find this declaration if there is no visible declaration of it.
  4889. bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
  4890. PushOnScopeChains(New, S, AddToContext);
  4891. if (!AddToContext)
  4892. CurContext->addHiddenDecl(New);
  4893. }
  4894. if (isInOpenMPDeclareTargetContext())
  4895. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  4896. return New;
  4897. }
  4898. /// Helper method to turn variable array types into constant array
  4899. /// types in certain situations which would otherwise be errors (for
  4900. /// GCC compatibility).
  4901. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  4902. ASTContext &Context,
  4903. bool &SizeIsNegative,
  4904. llvm::APSInt &Oversized) {
  4905. // This method tries to turn a variable array into a constant
  4906. // array even when the size isn't an ICE. This is necessary
  4907. // for compatibility with code that depends on gcc's buggy
  4908. // constant expression folding, like struct {char x[(int)(char*)2];}
  4909. SizeIsNegative = false;
  4910. Oversized = 0;
  4911. if (T->isDependentType())
  4912. return QualType();
  4913. QualifierCollector Qs;
  4914. const Type *Ty = Qs.strip(T);
  4915. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  4916. QualType Pointee = PTy->getPointeeType();
  4917. QualType FixedType =
  4918. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  4919. Oversized);
  4920. if (FixedType.isNull()) return FixedType;
  4921. FixedType = Context.getPointerType(FixedType);
  4922. return Qs.apply(Context, FixedType);
  4923. }
  4924. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  4925. QualType Inner = PTy->getInnerType();
  4926. QualType FixedType =
  4927. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  4928. Oversized);
  4929. if (FixedType.isNull()) return FixedType;
  4930. FixedType = Context.getParenType(FixedType);
  4931. return Qs.apply(Context, FixedType);
  4932. }
  4933. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  4934. if (!VLATy)
  4935. return QualType();
  4936. // FIXME: We should probably handle this case
  4937. if (VLATy->getElementType()->isVariablyModifiedType())
  4938. return QualType();
  4939. llvm::APSInt Res;
  4940. if (!VLATy->getSizeExpr() ||
  4941. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  4942. return QualType();
  4943. // Check whether the array size is negative.
  4944. if (Res.isSigned() && Res.isNegative()) {
  4945. SizeIsNegative = true;
  4946. return QualType();
  4947. }
  4948. // Check whether the array is too large to be addressed.
  4949. unsigned ActiveSizeBits
  4950. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  4951. Res);
  4952. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  4953. Oversized = Res;
  4954. return QualType();
  4955. }
  4956. return Context.getConstantArrayType(VLATy->getElementType(),
  4957. Res, ArrayType::Normal, 0);
  4958. }
  4959. static void
  4960. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  4961. SrcTL = SrcTL.getUnqualifiedLoc();
  4962. DstTL = DstTL.getUnqualifiedLoc();
  4963. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  4964. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  4965. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  4966. DstPTL.getPointeeLoc());
  4967. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  4968. return;
  4969. }
  4970. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  4971. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  4972. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  4973. DstPTL.getInnerLoc());
  4974. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  4975. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  4976. return;
  4977. }
  4978. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  4979. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  4980. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  4981. TypeLoc DstElemTL = DstATL.getElementLoc();
  4982. DstElemTL.initializeFullCopy(SrcElemTL);
  4983. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  4984. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  4985. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  4986. }
  4987. /// Helper method to turn variable array types into constant array
  4988. /// types in certain situations which would otherwise be errors (for
  4989. /// GCC compatibility).
  4990. static TypeSourceInfo*
  4991. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  4992. ASTContext &Context,
  4993. bool &SizeIsNegative,
  4994. llvm::APSInt &Oversized) {
  4995. QualType FixedTy
  4996. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  4997. SizeIsNegative, Oversized);
  4998. if (FixedTy.isNull())
  4999. return nullptr;
  5000. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  5001. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  5002. FixedTInfo->getTypeLoc());
  5003. return FixedTInfo;
  5004. }
  5005. /// \brief Register the given locally-scoped extern "C" declaration so
  5006. /// that it can be found later for redeclarations. We include any extern "C"
  5007. /// declaration that is not visible in the translation unit here, not just
  5008. /// function-scope declarations.
  5009. void
  5010. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  5011. if (!getLangOpts().CPlusPlus &&
  5012. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  5013. // Don't need to track declarations in the TU in C.
  5014. return;
  5015. // Note that we have a locally-scoped external with this name.
  5016. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  5017. }
  5018. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  5019. // FIXME: We can have multiple results via __attribute__((overloadable)).
  5020. auto Result = Context.getExternCContextDecl()->lookup(Name);
  5021. return Result.empty() ? nullptr : *Result.begin();
  5022. }
  5023. /// \brief Diagnose function specifiers on a declaration of an identifier that
  5024. /// does not identify a function.
  5025. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  5026. // FIXME: We should probably indicate the identifier in question to avoid
  5027. // confusion for constructs like "virtual int a(), b;"
  5028. if (DS.isVirtualSpecified())
  5029. Diag(DS.getVirtualSpecLoc(),
  5030. diag::err_virtual_non_function);
  5031. if (DS.isExplicitSpecified())
  5032. Diag(DS.getExplicitSpecLoc(),
  5033. diag::err_explicit_non_function);
  5034. if (DS.isNoreturnSpecified())
  5035. Diag(DS.getNoreturnSpecLoc(),
  5036. diag::err_noreturn_non_function);
  5037. }
  5038. NamedDecl*
  5039. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  5040. TypeSourceInfo *TInfo, LookupResult &Previous) {
  5041. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  5042. if (D.getCXXScopeSpec().isSet()) {
  5043. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  5044. << D.getCXXScopeSpec().getRange();
  5045. D.setInvalidType();
  5046. // Pretend we didn't see the scope specifier.
  5047. DC = CurContext;
  5048. Previous.clear();
  5049. }
  5050. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5051. if (D.getDeclSpec().isInlineSpecified())
  5052. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5053. << getLangOpts().CPlusPlus17;
  5054. if (D.getDeclSpec().isConstexprSpecified())
  5055. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5056. << 1;
  5057. if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
  5058. if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
  5059. Diag(D.getName().StartLocation,
  5060. diag::err_deduction_guide_invalid_specifier)
  5061. << "typedef";
  5062. else
  5063. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  5064. << D.getName().getSourceRange();
  5065. return nullptr;
  5066. }
  5067. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  5068. if (!NewTD) return nullptr;
  5069. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5070. ProcessDeclAttributes(S, NewTD, D);
  5071. CheckTypedefForVariablyModifiedType(S, NewTD);
  5072. bool Redeclaration = D.isRedeclaration();
  5073. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  5074. D.setRedeclaration(Redeclaration);
  5075. return ND;
  5076. }
  5077. void
  5078. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  5079. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  5080. // then it shall have block scope.
  5081. // Note that variably modified types must be fixed before merging the decl so
  5082. // that redeclarations will match.
  5083. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  5084. QualType T = TInfo->getType();
  5085. if (T->isVariablyModifiedType()) {
  5086. setFunctionHasBranchProtectedScope();
  5087. if (S->getFnParent() == nullptr) {
  5088. bool SizeIsNegative;
  5089. llvm::APSInt Oversized;
  5090. TypeSourceInfo *FixedTInfo =
  5091. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5092. SizeIsNegative,
  5093. Oversized);
  5094. if (FixedTInfo) {
  5095. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  5096. NewTD->setTypeSourceInfo(FixedTInfo);
  5097. } else {
  5098. if (SizeIsNegative)
  5099. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  5100. else if (T->isVariableArrayType())
  5101. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  5102. else if (Oversized.getBoolValue())
  5103. Diag(NewTD->getLocation(), diag::err_array_too_large)
  5104. << Oversized.toString(10);
  5105. else
  5106. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  5107. NewTD->setInvalidDecl();
  5108. }
  5109. }
  5110. }
  5111. }
  5112. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  5113. /// declares a typedef-name, either using the 'typedef' type specifier or via
  5114. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  5115. NamedDecl*
  5116. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  5117. LookupResult &Previous, bool &Redeclaration) {
  5118. // Find the shadowed declaration before filtering for scope.
  5119. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
  5120. // Merge the decl with the existing one if appropriate. If the decl is
  5121. // in an outer scope, it isn't the same thing.
  5122. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  5123. /*AllowInlineNamespace*/false);
  5124. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  5125. if (!Previous.empty()) {
  5126. Redeclaration = true;
  5127. MergeTypedefNameDecl(S, NewTD, Previous);
  5128. }
  5129. if (ShadowedDecl && !Redeclaration)
  5130. CheckShadow(NewTD, ShadowedDecl, Previous);
  5131. // If this is the C FILE type, notify the AST context.
  5132. if (IdentifierInfo *II = NewTD->getIdentifier())
  5133. if (!NewTD->isInvalidDecl() &&
  5134. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5135. if (II->isStr("FILE"))
  5136. Context.setFILEDecl(NewTD);
  5137. else if (II->isStr("jmp_buf"))
  5138. Context.setjmp_bufDecl(NewTD);
  5139. else if (II->isStr("sigjmp_buf"))
  5140. Context.setsigjmp_bufDecl(NewTD);
  5141. else if (II->isStr("ucontext_t"))
  5142. Context.setucontext_tDecl(NewTD);
  5143. }
  5144. return NewTD;
  5145. }
  5146. /// \brief Determines whether the given declaration is an out-of-scope
  5147. /// previous declaration.
  5148. ///
  5149. /// This routine should be invoked when name lookup has found a
  5150. /// previous declaration (PrevDecl) that is not in the scope where a
  5151. /// new declaration by the same name is being introduced. If the new
  5152. /// declaration occurs in a local scope, previous declarations with
  5153. /// linkage may still be considered previous declarations (C99
  5154. /// 6.2.2p4-5, C++ [basic.link]p6).
  5155. ///
  5156. /// \param PrevDecl the previous declaration found by name
  5157. /// lookup
  5158. ///
  5159. /// \param DC the context in which the new declaration is being
  5160. /// declared.
  5161. ///
  5162. /// \returns true if PrevDecl is an out-of-scope previous declaration
  5163. /// for a new delcaration with the same name.
  5164. static bool
  5165. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  5166. ASTContext &Context) {
  5167. if (!PrevDecl)
  5168. return false;
  5169. if (!PrevDecl->hasLinkage())
  5170. return false;
  5171. if (Context.getLangOpts().CPlusPlus) {
  5172. // C++ [basic.link]p6:
  5173. // If there is a visible declaration of an entity with linkage
  5174. // having the same name and type, ignoring entities declared
  5175. // outside the innermost enclosing namespace scope, the block
  5176. // scope declaration declares that same entity and receives the
  5177. // linkage of the previous declaration.
  5178. DeclContext *OuterContext = DC->getRedeclContext();
  5179. if (!OuterContext->isFunctionOrMethod())
  5180. // This rule only applies to block-scope declarations.
  5181. return false;
  5182. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  5183. if (PrevOuterContext->isRecord())
  5184. // We found a member function: ignore it.
  5185. return false;
  5186. // Find the innermost enclosing namespace for the new and
  5187. // previous declarations.
  5188. OuterContext = OuterContext->getEnclosingNamespaceContext();
  5189. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  5190. // The previous declaration is in a different namespace, so it
  5191. // isn't the same function.
  5192. if (!OuterContext->Equals(PrevOuterContext))
  5193. return false;
  5194. }
  5195. return true;
  5196. }
  5197. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  5198. CXXScopeSpec &SS = D.getCXXScopeSpec();
  5199. if (!SS.isSet()) return;
  5200. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  5201. }
  5202. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  5203. QualType type = decl->getType();
  5204. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  5205. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  5206. // Various kinds of declaration aren't allowed to be __autoreleasing.
  5207. unsigned kind = -1U;
  5208. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5209. if (var->hasAttr<BlocksAttr>())
  5210. kind = 0; // __block
  5211. else if (!var->hasLocalStorage())
  5212. kind = 1; // global
  5213. } else if (isa<ObjCIvarDecl>(decl)) {
  5214. kind = 3; // ivar
  5215. } else if (isa<FieldDecl>(decl)) {
  5216. kind = 2; // field
  5217. }
  5218. if (kind != -1U) {
  5219. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  5220. << kind;
  5221. }
  5222. } else if (lifetime == Qualifiers::OCL_None) {
  5223. // Try to infer lifetime.
  5224. if (!type->isObjCLifetimeType())
  5225. return false;
  5226. lifetime = type->getObjCARCImplicitLifetime();
  5227. type = Context.getLifetimeQualifiedType(type, lifetime);
  5228. decl->setType(type);
  5229. }
  5230. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5231. // Thread-local variables cannot have lifetime.
  5232. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  5233. var->getTLSKind()) {
  5234. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  5235. << var->getType();
  5236. return true;
  5237. }
  5238. }
  5239. return false;
  5240. }
  5241. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  5242. // Ensure that an auto decl is deduced otherwise the checks below might cache
  5243. // the wrong linkage.
  5244. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  5245. // 'weak' only applies to declarations with external linkage.
  5246. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  5247. if (!ND.isExternallyVisible()) {
  5248. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  5249. ND.dropAttr<WeakAttr>();
  5250. }
  5251. }
  5252. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  5253. if (ND.isExternallyVisible()) {
  5254. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  5255. ND.dropAttr<WeakRefAttr>();
  5256. ND.dropAttr<AliasAttr>();
  5257. }
  5258. }
  5259. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  5260. if (VD->hasInit()) {
  5261. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  5262. assert(VD->isThisDeclarationADefinition() &&
  5263. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  5264. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  5265. VD->dropAttr<AliasAttr>();
  5266. }
  5267. }
  5268. }
  5269. // 'selectany' only applies to externally visible variable declarations.
  5270. // It does not apply to functions.
  5271. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  5272. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  5273. S.Diag(Attr->getLocation(),
  5274. diag::err_attribute_selectany_non_extern_data);
  5275. ND.dropAttr<SelectAnyAttr>();
  5276. }
  5277. }
  5278. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  5279. // dll attributes require external linkage. Static locals may have external
  5280. // linkage but still cannot be explicitly imported or exported.
  5281. auto *VD = dyn_cast<VarDecl>(&ND);
  5282. if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
  5283. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  5284. << &ND << Attr;
  5285. ND.setInvalidDecl();
  5286. }
  5287. }
  5288. // Virtual functions cannot be marked as 'notail'.
  5289. if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
  5290. if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
  5291. if (MD->isVirtual()) {
  5292. S.Diag(ND.getLocation(),
  5293. diag::err_invalid_attribute_on_virtual_function)
  5294. << Attr;
  5295. ND.dropAttr<NotTailCalledAttr>();
  5296. }
  5297. }
  5298. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  5299. NamedDecl *NewDecl,
  5300. bool IsSpecialization,
  5301. bool IsDefinition) {
  5302. if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
  5303. return;
  5304. bool IsTemplate = false;
  5305. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  5306. OldDecl = OldTD->getTemplatedDecl();
  5307. IsTemplate = true;
  5308. if (!IsSpecialization)
  5309. IsDefinition = false;
  5310. }
  5311. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  5312. NewDecl = NewTD->getTemplatedDecl();
  5313. IsTemplate = true;
  5314. }
  5315. if (!OldDecl || !NewDecl)
  5316. return;
  5317. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  5318. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5319. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5320. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5321. // dllimport and dllexport are inheritable attributes so we have to exclude
  5322. // inherited attribute instances.
  5323. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5324. (NewExportAttr && !NewExportAttr->isInherited());
  5325. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5326. // the only exception being explicit specializations.
  5327. // Implicitly generated declarations are also excluded for now because there
  5328. // is no other way to switch these to use dllimport or dllexport.
  5329. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5330. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5331. // Allow with a warning for free functions and global variables.
  5332. bool JustWarn = false;
  5333. if (!OldDecl->isCXXClassMember()) {
  5334. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5335. if (VD && !VD->getDescribedVarTemplate())
  5336. JustWarn = true;
  5337. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5338. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5339. JustWarn = true;
  5340. }
  5341. // We cannot change a declaration that's been used because IR has already
  5342. // been emitted. Dllimported functions will still work though (modulo
  5343. // address equality) as they can use the thunk.
  5344. if (OldDecl->isUsed())
  5345. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5346. JustWarn = false;
  5347. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5348. : diag::err_attribute_dll_redeclaration;
  5349. S.Diag(NewDecl->getLocation(), DiagID)
  5350. << NewDecl
  5351. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5352. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5353. if (!JustWarn) {
  5354. NewDecl->setInvalidDecl();
  5355. return;
  5356. }
  5357. }
  5358. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5359. // exceptions being inline function definitions (except for function
  5360. // templates), local extern declarations, qualified friend declarations or
  5361. // special MSVC extension: in the last case, the declaration is treated as if
  5362. // it were marked dllexport.
  5363. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5364. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5365. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5366. // Ignore static data because out-of-line definitions are diagnosed
  5367. // separately.
  5368. IsStaticDataMember = VD->isStaticDataMember();
  5369. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5370. VarDecl::DeclarationOnly;
  5371. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5372. IsInline = FD->isInlined();
  5373. IsQualifiedFriend = FD->getQualifier() &&
  5374. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5375. }
  5376. if (OldImportAttr && !HasNewAttr &&
  5377. (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
  5378. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5379. if (IsMicrosoft && IsDefinition) {
  5380. S.Diag(NewDecl->getLocation(),
  5381. diag::warn_redeclaration_without_import_attribute)
  5382. << NewDecl;
  5383. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5384. NewDecl->dropAttr<DLLImportAttr>();
  5385. NewDecl->addAttr(::new (S.Context) DLLExportAttr(
  5386. NewImportAttr->getRange(), S.Context,
  5387. NewImportAttr->getSpellingListIndex()));
  5388. } else {
  5389. S.Diag(NewDecl->getLocation(),
  5390. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5391. << NewDecl << OldImportAttr;
  5392. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5393. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5394. OldDecl->dropAttr<DLLImportAttr>();
  5395. NewDecl->dropAttr<DLLImportAttr>();
  5396. }
  5397. } else if (IsInline && OldImportAttr && !IsMicrosoft) {
  5398. // In MinGW, seeing a function declared inline drops the dllimport
  5399. // attribute.
  5400. OldDecl->dropAttr<DLLImportAttr>();
  5401. NewDecl->dropAttr<DLLImportAttr>();
  5402. S.Diag(NewDecl->getLocation(),
  5403. diag::warn_dllimport_dropped_from_inline_function)
  5404. << NewDecl << OldImportAttr;
  5405. }
  5406. // A specialization of a class template member function is processed here
  5407. // since it's a redeclaration. If the parent class is dllexport, the
  5408. // specialization inherits that attribute. This doesn't happen automatically
  5409. // since the parent class isn't instantiated until later.
  5410. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
  5411. if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
  5412. !NewImportAttr && !NewExportAttr) {
  5413. if (const DLLExportAttr *ParentExportAttr =
  5414. MD->getParent()->getAttr<DLLExportAttr>()) {
  5415. DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
  5416. NewAttr->setInherited(true);
  5417. NewDecl->addAttr(NewAttr);
  5418. }
  5419. }
  5420. }
  5421. }
  5422. /// Given that we are within the definition of the given function,
  5423. /// will that definition behave like C99's 'inline', where the
  5424. /// definition is discarded except for optimization purposes?
  5425. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  5426. // Try to avoid calling GetGVALinkageForFunction.
  5427. // All cases of this require the 'inline' keyword.
  5428. if (!FD->isInlined()) return false;
  5429. // This is only possible in C++ with the gnu_inline attribute.
  5430. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  5431. return false;
  5432. // Okay, go ahead and call the relatively-more-expensive function.
  5433. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  5434. }
  5435. /// Determine whether a variable is extern "C" prior to attaching
  5436. /// an initializer. We can't just call isExternC() here, because that
  5437. /// will also compute and cache whether the declaration is externally
  5438. /// visible, which might change when we attach the initializer.
  5439. ///
  5440. /// This can only be used if the declaration is known to not be a
  5441. /// redeclaration of an internal linkage declaration.
  5442. ///
  5443. /// For instance:
  5444. ///
  5445. /// auto x = []{};
  5446. ///
  5447. /// Attaching the initializer here makes this declaration not externally
  5448. /// visible, because its type has internal linkage.
  5449. ///
  5450. /// FIXME: This is a hack.
  5451. template<typename T>
  5452. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  5453. if (S.getLangOpts().CPlusPlus) {
  5454. // In C++, the overloadable attribute negates the effects of extern "C".
  5455. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  5456. return false;
  5457. // So do CUDA's host/device attributes.
  5458. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  5459. D->template hasAttr<CUDAHostAttr>()))
  5460. return false;
  5461. }
  5462. return D->isExternC();
  5463. }
  5464. static bool shouldConsiderLinkage(const VarDecl *VD) {
  5465. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  5466. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
  5467. return VD->hasExternalStorage();
  5468. if (DC->isFileContext())
  5469. return true;
  5470. if (DC->isRecord())
  5471. return false;
  5472. llvm_unreachable("Unexpected context");
  5473. }
  5474. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  5475. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  5476. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  5477. isa<OMPDeclareReductionDecl>(DC))
  5478. return true;
  5479. if (DC->isRecord())
  5480. return false;
  5481. llvm_unreachable("Unexpected context");
  5482. }
  5483. static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
  5484. AttributeList::Kind Kind) {
  5485. for (const AttributeList *L = AttrList; L; L = L->getNext())
  5486. if (L->getKind() == Kind)
  5487. return true;
  5488. return false;
  5489. }
  5490. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  5491. AttributeList::Kind Kind) {
  5492. // Check decl attributes on the DeclSpec.
  5493. if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
  5494. return true;
  5495. // Walk the declarator structure, checking decl attributes that were in a type
  5496. // position to the decl itself.
  5497. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  5498. if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
  5499. return true;
  5500. }
  5501. // Finally, check attributes on the decl itself.
  5502. return hasParsedAttr(S, PD.getAttributes(), Kind);
  5503. }
  5504. /// Adjust the \c DeclContext for a function or variable that might be a
  5505. /// function-local external declaration.
  5506. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  5507. if (!DC->isFunctionOrMethod())
  5508. return false;
  5509. // If this is a local extern function or variable declared within a function
  5510. // template, don't add it into the enclosing namespace scope until it is
  5511. // instantiated; it might have a dependent type right now.
  5512. if (DC->isDependentContext())
  5513. return true;
  5514. // C++11 [basic.link]p7:
  5515. // When a block scope declaration of an entity with linkage is not found to
  5516. // refer to some other declaration, then that entity is a member of the
  5517. // innermost enclosing namespace.
  5518. //
  5519. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  5520. // semantically-enclosing namespace, not a lexically-enclosing one.
  5521. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  5522. DC = DC->getParent();
  5523. return true;
  5524. }
  5525. /// \brief Returns true if given declaration has external C language linkage.
  5526. static bool isDeclExternC(const Decl *D) {
  5527. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  5528. return FD->isExternC();
  5529. if (const auto *VD = dyn_cast<VarDecl>(D))
  5530. return VD->isExternC();
  5531. llvm_unreachable("Unknown type of decl!");
  5532. }
  5533. NamedDecl *Sema::ActOnVariableDeclarator(
  5534. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  5535. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  5536. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  5537. QualType R = TInfo->getType();
  5538. DeclarationName Name = GetNameForDeclarator(D).getName();
  5539. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5540. if (D.isDecompositionDeclarator()) {
  5541. // Take the name of the first declarator as our name for diagnostic
  5542. // purposes.
  5543. auto &Decomp = D.getDecompositionDeclarator();
  5544. if (!Decomp.bindings().empty()) {
  5545. II = Decomp.bindings()[0].Name;
  5546. Name = II;
  5547. }
  5548. } else if (!II) {
  5549. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
  5550. return nullptr;
  5551. }
  5552. if (getLangOpts().OpenCL) {
  5553. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  5554. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  5555. // argument.
  5556. if (R->isImageType() || R->isPipeType()) {
  5557. Diag(D.getIdentifierLoc(),
  5558. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  5559. << R;
  5560. D.setInvalidType();
  5561. return nullptr;
  5562. }
  5563. // OpenCL v1.2 s6.9.r:
  5564. // The event type cannot be used to declare a program scope variable.
  5565. // OpenCL v2.0 s6.9.q:
  5566. // The clk_event_t and reserve_id_t types cannot be declared in program scope.
  5567. if (NULL == S->getParent()) {
  5568. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  5569. Diag(D.getIdentifierLoc(),
  5570. diag::err_invalid_type_for_program_scope_var) << R;
  5571. D.setInvalidType();
  5572. return nullptr;
  5573. }
  5574. }
  5575. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  5576. QualType NR = R;
  5577. while (NR->isPointerType()) {
  5578. if (NR->isFunctionPointerType()) {
  5579. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
  5580. D.setInvalidType();
  5581. break;
  5582. }
  5583. NR = NR->getPointeeType();
  5584. }
  5585. if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  5586. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5587. // half array type (unless the cl_khr_fp16 extension is enabled).
  5588. if (Context.getBaseElementType(R)->isHalfType()) {
  5589. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5590. D.setInvalidType();
  5591. }
  5592. }
  5593. if (R->isSamplerT()) {
  5594. // OpenCL v1.2 s6.9.b p4:
  5595. // The sampler type cannot be used with the __local and __global address
  5596. // space qualifiers.
  5597. if (R.getAddressSpace() == LangAS::opencl_local ||
  5598. R.getAddressSpace() == LangAS::opencl_global) {
  5599. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5600. }
  5601. // OpenCL v1.2 s6.12.14.1:
  5602. // A global sampler must be declared with either the constant address
  5603. // space qualifier or with the const qualifier.
  5604. if (DC->isTranslationUnit() &&
  5605. !(R.getAddressSpace() == LangAS::opencl_constant ||
  5606. R.isConstQualified())) {
  5607. Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
  5608. D.setInvalidType();
  5609. }
  5610. }
  5611. // OpenCL v1.2 s6.9.r:
  5612. // The event type cannot be used with the __local, __constant and __global
  5613. // address space qualifiers.
  5614. if (R->isEventT()) {
  5615. if (R.getAddressSpace() != LangAS::opencl_private) {
  5616. Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
  5617. D.setInvalidType();
  5618. }
  5619. }
  5620. }
  5621. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  5622. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  5623. // dllimport globals without explicit storage class are treated as extern. We
  5624. // have to change the storage class this early to get the right DeclContext.
  5625. if (SC == SC_None && !DC->isRecord() &&
  5626. hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
  5627. !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
  5628. SC = SC_Extern;
  5629. DeclContext *OriginalDC = DC;
  5630. bool IsLocalExternDecl = SC == SC_Extern &&
  5631. adjustContextForLocalExternDecl(DC);
  5632. if (SCSpec == DeclSpec::SCS_mutable) {
  5633. // mutable can only appear on non-static class members, so it's always
  5634. // an error here
  5635. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5636. D.setInvalidType();
  5637. SC = SC_None;
  5638. }
  5639. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5640. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5641. D.getDeclSpec().getStorageClassSpecLoc())) {
  5642. // In C++11, the 'register' storage class specifier is deprecated.
  5643. // Suppress the warning in system macros, it's used in macros in some
  5644. // popular C system headers, such as in glibc's htonl() macro.
  5645. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5646. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  5647. : diag::warn_deprecated_register)
  5648. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5649. }
  5650. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5651. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5652. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5653. // appear in the declaration specifiers in an external declaration.
  5654. // Global Register+Asm is a GNU extension we support.
  5655. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5656. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5657. D.setInvalidType();
  5658. }
  5659. }
  5660. bool IsMemberSpecialization = false;
  5661. bool IsVariableTemplateSpecialization = false;
  5662. bool IsPartialSpecialization = false;
  5663. bool IsVariableTemplate = false;
  5664. VarDecl *NewVD = nullptr;
  5665. VarTemplateDecl *NewTemplate = nullptr;
  5666. TemplateParameterList *TemplateParams = nullptr;
  5667. if (!getLangOpts().CPlusPlus) {
  5668. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5669. D.getIdentifierLoc(), II,
  5670. R, TInfo, SC);
  5671. if (R->getContainedDeducedType())
  5672. ParsingInitForAutoVars.insert(NewVD);
  5673. if (D.isInvalidType())
  5674. NewVD->setInvalidDecl();
  5675. } else {
  5676. bool Invalid = false;
  5677. if (DC->isRecord() && !CurContext->isRecord()) {
  5678. // This is an out-of-line definition of a static data member.
  5679. switch (SC) {
  5680. case SC_None:
  5681. break;
  5682. case SC_Static:
  5683. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5684. diag::err_static_out_of_line)
  5685. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5686. break;
  5687. case SC_Auto:
  5688. case SC_Register:
  5689. case SC_Extern:
  5690. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5691. // to names of variables declared in a block or to function parameters.
  5692. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5693. // of class members
  5694. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5695. diag::err_storage_class_for_static_member)
  5696. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5697. break;
  5698. case SC_PrivateExtern:
  5699. llvm_unreachable("C storage class in c++!");
  5700. }
  5701. }
  5702. if (SC == SC_Static && CurContext->isRecord()) {
  5703. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5704. if (RD->isLocalClass())
  5705. Diag(D.getIdentifierLoc(),
  5706. diag::err_static_data_member_not_allowed_in_local_class)
  5707. << Name << RD->getDeclName();
  5708. // C++98 [class.union]p1: If a union contains a static data member,
  5709. // the program is ill-formed. C++11 drops this restriction.
  5710. if (RD->isUnion())
  5711. Diag(D.getIdentifierLoc(),
  5712. getLangOpts().CPlusPlus11
  5713. ? diag::warn_cxx98_compat_static_data_member_in_union
  5714. : diag::ext_static_data_member_in_union) << Name;
  5715. // We conservatively disallow static data members in anonymous structs.
  5716. else if (!RD->getDeclName())
  5717. Diag(D.getIdentifierLoc(),
  5718. diag::err_static_data_member_not_allowed_in_anon_struct)
  5719. << Name << RD->isUnion();
  5720. }
  5721. }
  5722. // Match up the template parameter lists with the scope specifier, then
  5723. // determine whether we have a template or a template specialization.
  5724. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5725. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  5726. D.getCXXScopeSpec(),
  5727. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  5728. ? D.getName().TemplateId
  5729. : nullptr,
  5730. TemplateParamLists,
  5731. /*never a friend*/ false, IsMemberSpecialization, Invalid);
  5732. if (TemplateParams) {
  5733. if (!TemplateParams->size() &&
  5734. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  5735. // There is an extraneous 'template<>' for this variable. Complain
  5736. // about it, but allow the declaration of the variable.
  5737. Diag(TemplateParams->getTemplateLoc(),
  5738. diag::err_template_variable_noparams)
  5739. << II
  5740. << SourceRange(TemplateParams->getTemplateLoc(),
  5741. TemplateParams->getRAngleLoc());
  5742. TemplateParams = nullptr;
  5743. } else {
  5744. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  5745. // This is an explicit specialization or a partial specialization.
  5746. // FIXME: Check that we can declare a specialization here.
  5747. IsVariableTemplateSpecialization = true;
  5748. IsPartialSpecialization = TemplateParams->size() > 0;
  5749. } else { // if (TemplateParams->size() > 0)
  5750. // This is a template declaration.
  5751. IsVariableTemplate = true;
  5752. // Check that we can declare a template here.
  5753. if (CheckTemplateDeclScope(S, TemplateParams))
  5754. return nullptr;
  5755. // Only C++1y supports variable templates (N3651).
  5756. Diag(D.getIdentifierLoc(),
  5757. getLangOpts().CPlusPlus14
  5758. ? diag::warn_cxx11_compat_variable_template
  5759. : diag::ext_variable_template);
  5760. }
  5761. }
  5762. } else {
  5763. assert((Invalid ||
  5764. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
  5765. "should have a 'template<>' for this decl");
  5766. }
  5767. if (IsVariableTemplateSpecialization) {
  5768. SourceLocation TemplateKWLoc =
  5769. TemplateParamLists.size() > 0
  5770. ? TemplateParamLists[0]->getTemplateLoc()
  5771. : SourceLocation();
  5772. DeclResult Res = ActOnVarTemplateSpecialization(
  5773. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5774. IsPartialSpecialization);
  5775. if (Res.isInvalid())
  5776. return nullptr;
  5777. NewVD = cast<VarDecl>(Res.get());
  5778. AddToScope = false;
  5779. } else if (D.isDecompositionDeclarator()) {
  5780. NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
  5781. D.getIdentifierLoc(), R, TInfo, SC,
  5782. Bindings);
  5783. } else
  5784. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5785. D.getIdentifierLoc(), II, R, TInfo, SC);
  5786. // If this is supposed to be a variable template, create it as such.
  5787. if (IsVariableTemplate) {
  5788. NewTemplate =
  5789. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5790. TemplateParams, NewVD);
  5791. NewVD->setDescribedVarTemplate(NewTemplate);
  5792. }
  5793. // If this decl has an auto type in need of deduction, make a note of the
  5794. // Decl so we can diagnose uses of it in its own initializer.
  5795. if (R->getContainedDeducedType())
  5796. ParsingInitForAutoVars.insert(NewVD);
  5797. if (D.isInvalidType() || Invalid) {
  5798. NewVD->setInvalidDecl();
  5799. if (NewTemplate)
  5800. NewTemplate->setInvalidDecl();
  5801. }
  5802. SetNestedNameSpecifier(NewVD, D);
  5803. // If we have any template parameter lists that don't directly belong to
  5804. // the variable (matching the scope specifier), store them.
  5805. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5806. if (TemplateParamLists.size() > VDTemplateParamLists)
  5807. NewVD->setTemplateParameterListsInfo(
  5808. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  5809. if (D.getDeclSpec().isConstexprSpecified()) {
  5810. NewVD->setConstexpr(true);
  5811. // C++1z [dcl.spec.constexpr]p1:
  5812. // A static data member declared with the constexpr specifier is
  5813. // implicitly an inline variable.
  5814. if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
  5815. NewVD->setImplicitlyInline();
  5816. }
  5817. }
  5818. if (D.getDeclSpec().isInlineSpecified()) {
  5819. if (!getLangOpts().CPlusPlus) {
  5820. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5821. << 0;
  5822. } else if (CurContext->isFunctionOrMethod()) {
  5823. // 'inline' is not allowed on block scope variable declaration.
  5824. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5825. diag::err_inline_declaration_block_scope) << Name
  5826. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  5827. } else {
  5828. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5829. getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
  5830. : diag::ext_inline_variable);
  5831. NewVD->setInlineSpecified();
  5832. }
  5833. }
  5834. // Set the lexical context. If the declarator has a C++ scope specifier, the
  5835. // lexical context will be different from the semantic context.
  5836. NewVD->setLexicalDeclContext(CurContext);
  5837. if (NewTemplate)
  5838. NewTemplate->setLexicalDeclContext(CurContext);
  5839. if (IsLocalExternDecl) {
  5840. if (D.isDecompositionDeclarator())
  5841. for (auto *B : Bindings)
  5842. B->setLocalExternDecl();
  5843. else
  5844. NewVD->setLocalExternDecl();
  5845. }
  5846. bool EmitTLSUnsupportedError = false;
  5847. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  5848. // C++11 [dcl.stc]p4:
  5849. // When thread_local is applied to a variable of block scope the
  5850. // storage-class-specifier static is implied if it does not appear
  5851. // explicitly.
  5852. // Core issue: 'static' is not implied if the variable is declared
  5853. // 'extern'.
  5854. if (NewVD->hasLocalStorage() &&
  5855. (SCSpec != DeclSpec::SCS_unspecified ||
  5856. TSCS != DeclSpec::TSCS_thread_local ||
  5857. !DC->isFunctionOrMethod()))
  5858. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5859. diag::err_thread_non_global)
  5860. << DeclSpec::getSpecifierName(TSCS);
  5861. else if (!Context.getTargetInfo().isTLSSupported()) {
  5862. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  5863. // Postpone error emission until we've collected attributes required to
  5864. // figure out whether it's a host or device variable and whether the
  5865. // error should be ignored.
  5866. EmitTLSUnsupportedError = true;
  5867. // We still need to mark the variable as TLS so it shows up in AST with
  5868. // proper storage class for other tools to use even if we're not going
  5869. // to emit any code for it.
  5870. NewVD->setTSCSpec(TSCS);
  5871. } else
  5872. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5873. diag::err_thread_unsupported);
  5874. } else
  5875. NewVD->setTSCSpec(TSCS);
  5876. }
  5877. // C99 6.7.4p3
  5878. // An inline definition of a function with external linkage shall
  5879. // not contain a definition of a modifiable object with static or
  5880. // thread storage duration...
  5881. // We only apply this when the function is required to be defined
  5882. // elsewhere, i.e. when the function is not 'extern inline'. Note
  5883. // that a local variable with thread storage duration still has to
  5884. // be marked 'static'. Also note that it's possible to get these
  5885. // semantics in C++ using __attribute__((gnu_inline)).
  5886. if (SC == SC_Static && S->getFnParent() != nullptr &&
  5887. !NewVD->getType().isConstQualified()) {
  5888. FunctionDecl *CurFD = getCurFunctionDecl();
  5889. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  5890. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5891. diag::warn_static_local_in_extern_inline);
  5892. MaybeSuggestAddingStaticToDecl(CurFD);
  5893. }
  5894. }
  5895. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5896. if (IsVariableTemplateSpecialization)
  5897. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5898. << (IsPartialSpecialization ? 1 : 0)
  5899. << FixItHint::CreateRemoval(
  5900. D.getDeclSpec().getModulePrivateSpecLoc());
  5901. else if (IsMemberSpecialization)
  5902. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5903. << 2
  5904. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5905. else if (NewVD->hasLocalStorage())
  5906. Diag(NewVD->getLocation(), diag::err_module_private_local)
  5907. << 0 << NewVD->getDeclName()
  5908. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5909. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5910. else {
  5911. NewVD->setModulePrivate();
  5912. if (NewTemplate)
  5913. NewTemplate->setModulePrivate();
  5914. for (auto *B : Bindings)
  5915. B->setModulePrivate();
  5916. }
  5917. }
  5918. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5919. ProcessDeclAttributes(S, NewVD, D);
  5920. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  5921. if (EmitTLSUnsupportedError &&
  5922. ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
  5923. (getLangOpts().OpenMPIsDevice &&
  5924. NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
  5925. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5926. diag::err_thread_unsupported);
  5927. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  5928. // storage [duration]."
  5929. if (SC == SC_None && S->getFnParent() != nullptr &&
  5930. (NewVD->hasAttr<CUDASharedAttr>() ||
  5931. NewVD->hasAttr<CUDAConstantAttr>())) {
  5932. NewVD->setStorageClass(SC_Static);
  5933. }
  5934. }
  5935. // Ensure that dllimport globals without explicit storage class are treated as
  5936. // extern. The storage class is set above using parsed attributes. Now we can
  5937. // check the VarDecl itself.
  5938. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  5939. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  5940. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  5941. // In auto-retain/release, infer strong retension for variables of
  5942. // retainable type.
  5943. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  5944. NewVD->setInvalidDecl();
  5945. // Handle GNU asm-label extension (encoded as an attribute).
  5946. if (Expr *E = (Expr*)D.getAsmLabel()) {
  5947. // The parser guarantees this is a string.
  5948. StringLiteral *SE = cast<StringLiteral>(E);
  5949. StringRef Label = SE->getString();
  5950. if (S->getFnParent() != nullptr) {
  5951. switch (SC) {
  5952. case SC_None:
  5953. case SC_Auto:
  5954. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  5955. break;
  5956. case SC_Register:
  5957. // Local Named register
  5958. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  5959. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  5960. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5961. break;
  5962. case SC_Static:
  5963. case SC_Extern:
  5964. case SC_PrivateExtern:
  5965. break;
  5966. }
  5967. } else if (SC == SC_Register) {
  5968. // Global Named register
  5969. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  5970. const auto &TI = Context.getTargetInfo();
  5971. bool HasSizeMismatch;
  5972. if (!TI.isValidGCCRegisterName(Label))
  5973. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5974. else if (!TI.validateGlobalRegisterVariable(Label,
  5975. Context.getTypeSize(R),
  5976. HasSizeMismatch))
  5977. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  5978. else if (HasSizeMismatch)
  5979. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  5980. }
  5981. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  5982. Diag(D.getLocStart(), diag::err_asm_bad_register_type);
  5983. NewVD->setInvalidDecl(true);
  5984. }
  5985. }
  5986. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  5987. Context, Label, 0));
  5988. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  5989. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  5990. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  5991. if (I != ExtnameUndeclaredIdentifiers.end()) {
  5992. if (isDeclExternC(NewVD)) {
  5993. NewVD->addAttr(I->second);
  5994. ExtnameUndeclaredIdentifiers.erase(I);
  5995. } else
  5996. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  5997. << /*Variable*/1 << NewVD;
  5998. }
  5999. }
  6000. // Find the shadowed declaration before filtering for scope.
  6001. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  6002. ? getShadowedDeclaration(NewVD, Previous)
  6003. : nullptr;
  6004. // Don't consider existing declarations that are in a different
  6005. // scope and are out-of-semantic-context declarations (if the new
  6006. // declaration has linkage).
  6007. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  6008. D.getCXXScopeSpec().isNotEmpty() ||
  6009. IsMemberSpecialization ||
  6010. IsVariableTemplateSpecialization);
  6011. // Check whether the previous declaration is in the same block scope. This
  6012. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  6013. if (getLangOpts().CPlusPlus &&
  6014. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  6015. NewVD->setPreviousDeclInSameBlockScope(
  6016. Previous.isSingleResult() && !Previous.isShadowed() &&
  6017. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  6018. if (!getLangOpts().CPlusPlus) {
  6019. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6020. } else {
  6021. // If this is an explicit specialization of a static data member, check it.
  6022. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  6023. CheckMemberSpecialization(NewVD, Previous))
  6024. NewVD->setInvalidDecl();
  6025. // Merge the decl with the existing one if appropriate.
  6026. if (!Previous.empty()) {
  6027. if (Previous.isSingleResult() &&
  6028. isa<FieldDecl>(Previous.getFoundDecl()) &&
  6029. D.getCXXScopeSpec().isSet()) {
  6030. // The user tried to define a non-static data member
  6031. // out-of-line (C++ [dcl.meaning]p1).
  6032. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  6033. << D.getCXXScopeSpec().getRange();
  6034. Previous.clear();
  6035. NewVD->setInvalidDecl();
  6036. }
  6037. } else if (D.getCXXScopeSpec().isSet()) {
  6038. // No previous declaration in the qualifying scope.
  6039. Diag(D.getIdentifierLoc(), diag::err_no_member)
  6040. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  6041. << D.getCXXScopeSpec().getRange();
  6042. NewVD->setInvalidDecl();
  6043. }
  6044. if (!IsVariableTemplateSpecialization)
  6045. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6046. if (NewTemplate) {
  6047. VarTemplateDecl *PrevVarTemplate =
  6048. NewVD->getPreviousDecl()
  6049. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  6050. : nullptr;
  6051. // Check the template parameter list of this declaration, possibly
  6052. // merging in the template parameter list from the previous variable
  6053. // template declaration.
  6054. if (CheckTemplateParameterList(
  6055. TemplateParams,
  6056. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  6057. : nullptr,
  6058. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  6059. DC->isDependentContext())
  6060. ? TPC_ClassTemplateMember
  6061. : TPC_VarTemplate))
  6062. NewVD->setInvalidDecl();
  6063. // If we are providing an explicit specialization of a static variable
  6064. // template, make a note of that.
  6065. if (PrevVarTemplate &&
  6066. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  6067. PrevVarTemplate->setMemberSpecialization();
  6068. }
  6069. }
  6070. // Diagnose shadowed variables iff this isn't a redeclaration.
  6071. if (ShadowedDecl && !D.isRedeclaration())
  6072. CheckShadow(NewVD, ShadowedDecl, Previous);
  6073. ProcessPragmaWeak(S, NewVD);
  6074. // If this is the first declaration of an extern C variable, update
  6075. // the map of such variables.
  6076. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  6077. isIncompleteDeclExternC(*this, NewVD))
  6078. RegisterLocallyScopedExternCDecl(NewVD, S);
  6079. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  6080. Decl *ManglingContextDecl;
  6081. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  6082. NewVD->getDeclContext(), ManglingContextDecl)) {
  6083. Context.setManglingNumber(
  6084. NewVD, MCtx->getManglingNumber(
  6085. NewVD, getMSManglingNumber(getLangOpts(), S)));
  6086. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  6087. }
  6088. }
  6089. // Special handling of variable named 'main'.
  6090. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  6091. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  6092. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  6093. // C++ [basic.start.main]p3
  6094. // A program that declares a variable main at global scope is ill-formed.
  6095. if (getLangOpts().CPlusPlus)
  6096. Diag(D.getLocStart(), diag::err_main_global_variable);
  6097. // In C, and external-linkage variable named main results in undefined
  6098. // behavior.
  6099. else if (NewVD->hasExternalFormalLinkage())
  6100. Diag(D.getLocStart(), diag::warn_main_redefined);
  6101. }
  6102. if (D.isRedeclaration() && !Previous.empty()) {
  6103. NamedDecl *Prev = Previous.getRepresentativeDecl();
  6104. checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
  6105. D.isFunctionDefinition());
  6106. }
  6107. if (NewTemplate) {
  6108. if (NewVD->isInvalidDecl())
  6109. NewTemplate->setInvalidDecl();
  6110. ActOnDocumentableDecl(NewTemplate);
  6111. return NewTemplate;
  6112. }
  6113. if (IsMemberSpecialization && !NewVD->isInvalidDecl())
  6114. CompleteMemberSpecialization(NewVD, Previous);
  6115. return NewVD;
  6116. }
  6117. /// Enum describing the %select options in diag::warn_decl_shadow.
  6118. enum ShadowedDeclKind {
  6119. SDK_Local,
  6120. SDK_Global,
  6121. SDK_StaticMember,
  6122. SDK_Field,
  6123. SDK_Typedef,
  6124. SDK_Using
  6125. };
  6126. /// Determine what kind of declaration we're shadowing.
  6127. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  6128. const DeclContext *OldDC) {
  6129. if (isa<TypeAliasDecl>(ShadowedDecl))
  6130. return SDK_Using;
  6131. else if (isa<TypedefDecl>(ShadowedDecl))
  6132. return SDK_Typedef;
  6133. else if (isa<RecordDecl>(OldDC))
  6134. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  6135. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  6136. }
  6137. /// Return the location of the capture if the given lambda captures the given
  6138. /// variable \p VD, or an invalid source location otherwise.
  6139. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  6140. const VarDecl *VD) {
  6141. for (const Capture &Capture : LSI->Captures) {
  6142. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  6143. return Capture.getLocation();
  6144. }
  6145. return SourceLocation();
  6146. }
  6147. static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
  6148. const LookupResult &R) {
  6149. // Only diagnose if we're shadowing an unambiguous field or variable.
  6150. if (R.getResultKind() != LookupResult::Found)
  6151. return false;
  6152. // Return false if warning is ignored.
  6153. return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
  6154. }
  6155. /// \brief Return the declaration shadowed by the given variable \p D, or null
  6156. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6157. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  6158. const LookupResult &R) {
  6159. if (!shouldWarnIfShadowedDecl(Diags, R))
  6160. return nullptr;
  6161. // Don't diagnose declarations at file scope.
  6162. if (D->hasGlobalStorage())
  6163. return nullptr;
  6164. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6165. return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
  6166. ? ShadowedDecl
  6167. : nullptr;
  6168. }
  6169. /// \brief Return the declaration shadowed by the given typedef \p D, or null
  6170. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6171. NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
  6172. const LookupResult &R) {
  6173. // Don't warn if typedef declaration is part of a class
  6174. if (D->getDeclContext()->isRecord())
  6175. return nullptr;
  6176. if (!shouldWarnIfShadowedDecl(Diags, R))
  6177. return nullptr;
  6178. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6179. return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
  6180. }
  6181. /// \brief Diagnose variable or built-in function shadowing. Implements
  6182. /// -Wshadow.
  6183. ///
  6184. /// This method is called whenever a VarDecl is added to a "useful"
  6185. /// scope.
  6186. ///
  6187. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  6188. /// \param R the lookup of the name
  6189. ///
  6190. void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
  6191. const LookupResult &R) {
  6192. DeclContext *NewDC = D->getDeclContext();
  6193. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  6194. // Fields are not shadowed by variables in C++ static methods.
  6195. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  6196. if (MD->isStatic())
  6197. return;
  6198. // Fields shadowed by constructor parameters are a special case. Usually
  6199. // the constructor initializes the field with the parameter.
  6200. if (isa<CXXConstructorDecl>(NewDC))
  6201. if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
  6202. // Remember that this was shadowed so we can either warn about its
  6203. // modification or its existence depending on warning settings.
  6204. ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
  6205. return;
  6206. }
  6207. }
  6208. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  6209. if (shadowedVar->isExternC()) {
  6210. // For shadowing external vars, make sure that we point to the global
  6211. // declaration, not a locally scoped extern declaration.
  6212. for (auto I : shadowedVar->redecls())
  6213. if (I->isFileVarDecl()) {
  6214. ShadowedDecl = I;
  6215. break;
  6216. }
  6217. }
  6218. DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
  6219. unsigned WarningDiag = diag::warn_decl_shadow;
  6220. SourceLocation CaptureLoc;
  6221. if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
  6222. isa<CXXMethodDecl>(NewDC)) {
  6223. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  6224. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  6225. if (RD->getLambdaCaptureDefault() == LCD_None) {
  6226. // Try to avoid warnings for lambdas with an explicit capture list.
  6227. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  6228. // Warn only when the lambda captures the shadowed decl explicitly.
  6229. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  6230. if (CaptureLoc.isInvalid())
  6231. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  6232. } else {
  6233. // Remember that this was shadowed so we can avoid the warning if the
  6234. // shadowed decl isn't captured and the warning settings allow it.
  6235. cast<LambdaScopeInfo>(getCurFunction())
  6236. ->ShadowingDecls.push_back(
  6237. {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
  6238. return;
  6239. }
  6240. }
  6241. if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
  6242. // A variable can't shadow a local variable in an enclosing scope, if
  6243. // they are separated by a non-capturing declaration context.
  6244. for (DeclContext *ParentDC = NewDC;
  6245. ParentDC && !ParentDC->Equals(OldDC);
  6246. ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
  6247. // Only block literals, captured statements, and lambda expressions
  6248. // can capture; other scopes don't.
  6249. if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
  6250. !isLambdaCallOperator(ParentDC)) {
  6251. return;
  6252. }
  6253. }
  6254. }
  6255. }
  6256. }
  6257. // Only warn about certain kinds of shadowing for class members.
  6258. if (NewDC && NewDC->isRecord()) {
  6259. // In particular, don't warn about shadowing non-class members.
  6260. if (!OldDC->isRecord())
  6261. return;
  6262. // TODO: should we warn about static data members shadowing
  6263. // static data members from base classes?
  6264. // TODO: don't diagnose for inaccessible shadowed members.
  6265. // This is hard to do perfectly because we might friend the
  6266. // shadowing context, but that's just a false negative.
  6267. }
  6268. DeclarationName Name = R.getLookupName();
  6269. // Emit warning and note.
  6270. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  6271. return;
  6272. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  6273. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  6274. if (!CaptureLoc.isInvalid())
  6275. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6276. << Name << /*explicitly*/ 1;
  6277. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6278. }
  6279. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  6280. /// when these variables are captured by the lambda.
  6281. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  6282. for (const auto &Shadow : LSI->ShadowingDecls) {
  6283. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  6284. // Try to avoid the warning when the shadowed decl isn't captured.
  6285. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  6286. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6287. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  6288. ? diag::warn_decl_shadow_uncaptured_local
  6289. : diag::warn_decl_shadow)
  6290. << Shadow.VD->getDeclName()
  6291. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  6292. if (!CaptureLoc.isInvalid())
  6293. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6294. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  6295. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6296. }
  6297. }
  6298. /// \brief Check -Wshadow without the advantage of a previous lookup.
  6299. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  6300. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  6301. return;
  6302. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  6303. Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  6304. LookupName(R, S);
  6305. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  6306. CheckShadow(D, ShadowedDecl, R);
  6307. }
  6308. /// Check if 'E', which is an expression that is about to be modified, refers
  6309. /// to a constructor parameter that shadows a field.
  6310. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  6311. // Quickly ignore expressions that can't be shadowing ctor parameters.
  6312. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  6313. return;
  6314. E = E->IgnoreParenImpCasts();
  6315. auto *DRE = dyn_cast<DeclRefExpr>(E);
  6316. if (!DRE)
  6317. return;
  6318. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  6319. auto I = ShadowingDecls.find(D);
  6320. if (I == ShadowingDecls.end())
  6321. return;
  6322. const NamedDecl *ShadowedDecl = I->second;
  6323. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6324. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  6325. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  6326. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6327. // Avoid issuing multiple warnings about the same decl.
  6328. ShadowingDecls.erase(I);
  6329. }
  6330. /// Check for conflict between this global or extern "C" declaration and
  6331. /// previous global or extern "C" declarations. This is only used in C++.
  6332. template<typename T>
  6333. static bool checkGlobalOrExternCConflict(
  6334. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  6335. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  6336. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  6337. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  6338. // The common case: this global doesn't conflict with any extern "C"
  6339. // declaration.
  6340. return false;
  6341. }
  6342. if (Prev) {
  6343. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  6344. // Both the old and new declarations have C language linkage. This is a
  6345. // redeclaration.
  6346. Previous.clear();
  6347. Previous.addDecl(Prev);
  6348. return true;
  6349. }
  6350. // This is a global, non-extern "C" declaration, and there is a previous
  6351. // non-global extern "C" declaration. Diagnose if this is a variable
  6352. // declaration.
  6353. if (!isa<VarDecl>(ND))
  6354. return false;
  6355. } else {
  6356. // The declaration is extern "C". Check for any declaration in the
  6357. // translation unit which might conflict.
  6358. if (IsGlobal) {
  6359. // We have already performed the lookup into the translation unit.
  6360. IsGlobal = false;
  6361. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6362. I != E; ++I) {
  6363. if (isa<VarDecl>(*I)) {
  6364. Prev = *I;
  6365. break;
  6366. }
  6367. }
  6368. } else {
  6369. DeclContext::lookup_result R =
  6370. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  6371. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  6372. I != E; ++I) {
  6373. if (isa<VarDecl>(*I)) {
  6374. Prev = *I;
  6375. break;
  6376. }
  6377. // FIXME: If we have any other entity with this name in global scope,
  6378. // the declaration is ill-formed, but that is a defect: it breaks the
  6379. // 'stat' hack, for instance. Only variables can have mangled name
  6380. // clashes with extern "C" declarations, so only they deserve a
  6381. // diagnostic.
  6382. }
  6383. }
  6384. if (!Prev)
  6385. return false;
  6386. }
  6387. // Use the first declaration's location to ensure we point at something which
  6388. // is lexically inside an extern "C" linkage-spec.
  6389. assert(Prev && "should have found a previous declaration to diagnose");
  6390. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  6391. Prev = FD->getFirstDecl();
  6392. else
  6393. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  6394. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  6395. << IsGlobal << ND;
  6396. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  6397. << IsGlobal;
  6398. return false;
  6399. }
  6400. /// Apply special rules for handling extern "C" declarations. Returns \c true
  6401. /// if we have found that this is a redeclaration of some prior entity.
  6402. ///
  6403. /// Per C++ [dcl.link]p6:
  6404. /// Two declarations [for a function or variable] with C language linkage
  6405. /// with the same name that appear in different scopes refer to the same
  6406. /// [entity]. An entity with C language linkage shall not be declared with
  6407. /// the same name as an entity in global scope.
  6408. template<typename T>
  6409. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  6410. LookupResult &Previous) {
  6411. if (!S.getLangOpts().CPlusPlus) {
  6412. // In C, when declaring a global variable, look for a corresponding 'extern'
  6413. // variable declared in function scope. We don't need this in C++, because
  6414. // we find local extern decls in the surrounding file-scope DeclContext.
  6415. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6416. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  6417. Previous.clear();
  6418. Previous.addDecl(Prev);
  6419. return true;
  6420. }
  6421. }
  6422. return false;
  6423. }
  6424. // A declaration in the translation unit can conflict with an extern "C"
  6425. // declaration.
  6426. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  6427. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  6428. // An extern "C" declaration can conflict with a declaration in the
  6429. // translation unit or can be a redeclaration of an extern "C" declaration
  6430. // in another scope.
  6431. if (isIncompleteDeclExternC(S,ND))
  6432. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  6433. // Neither global nor extern "C": nothing to do.
  6434. return false;
  6435. }
  6436. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  6437. // If the decl is already known invalid, don't check it.
  6438. if (NewVD->isInvalidDecl())
  6439. return;
  6440. TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
  6441. QualType T = TInfo->getType();
  6442. // Defer checking an 'auto' type until its initializer is attached.
  6443. if (T->isUndeducedType())
  6444. return;
  6445. if (NewVD->hasAttrs())
  6446. CheckAlignasUnderalignment(NewVD);
  6447. if (T->isObjCObjectType()) {
  6448. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  6449. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  6450. T = Context.getObjCObjectPointerType(T);
  6451. NewVD->setType(T);
  6452. }
  6453. // Emit an error if an address space was applied to decl with local storage.
  6454. // This includes arrays of objects with address space qualifiers, but not
  6455. // automatic variables that point to other address spaces.
  6456. // ISO/IEC TR 18037 S5.1.2
  6457. if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
  6458. T.getAddressSpace() != LangAS::Default) {
  6459. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
  6460. NewVD->setInvalidDecl();
  6461. return;
  6462. }
  6463. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  6464. // scope.
  6465. if (getLangOpts().OpenCLVersion == 120 &&
  6466. !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
  6467. NewVD->isStaticLocal()) {
  6468. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  6469. NewVD->setInvalidDecl();
  6470. return;
  6471. }
  6472. if (getLangOpts().OpenCL) {
  6473. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  6474. if (NewVD->hasAttr<BlocksAttr>()) {
  6475. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  6476. return;
  6477. }
  6478. if (T->isBlockPointerType()) {
  6479. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  6480. // can't use 'extern' storage class.
  6481. if (!T.isConstQualified()) {
  6482. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  6483. << 0 /*const*/;
  6484. NewVD->setInvalidDecl();
  6485. return;
  6486. }
  6487. if (NewVD->hasExternalStorage()) {
  6488. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  6489. NewVD->setInvalidDecl();
  6490. return;
  6491. }
  6492. }
  6493. // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
  6494. // __constant address space.
  6495. // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
  6496. // variables inside a function can also be declared in the global
  6497. // address space.
  6498. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  6499. NewVD->hasExternalStorage()) {
  6500. if (!T->isSamplerT() &&
  6501. !(T.getAddressSpace() == LangAS::opencl_constant ||
  6502. (T.getAddressSpace() == LangAS::opencl_global &&
  6503. getLangOpts().OpenCLVersion == 200))) {
  6504. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  6505. if (getLangOpts().OpenCLVersion == 200)
  6506. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6507. << Scope << "global or constant";
  6508. else
  6509. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6510. << Scope << "constant";
  6511. NewVD->setInvalidDecl();
  6512. return;
  6513. }
  6514. } else {
  6515. if (T.getAddressSpace() == LangAS::opencl_global) {
  6516. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6517. << 1 /*is any function*/ << "global";
  6518. NewVD->setInvalidDecl();
  6519. return;
  6520. }
  6521. if (T.getAddressSpace() == LangAS::opencl_constant ||
  6522. T.getAddressSpace() == LangAS::opencl_local) {
  6523. FunctionDecl *FD = getCurFunctionDecl();
  6524. // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
  6525. // in functions.
  6526. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  6527. if (T.getAddressSpace() == LangAS::opencl_constant)
  6528. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6529. << 0 /*non-kernel only*/ << "constant";
  6530. else
  6531. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6532. << 0 /*non-kernel only*/ << "local";
  6533. NewVD->setInvalidDecl();
  6534. return;
  6535. }
  6536. // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
  6537. // in the outermost scope of a kernel function.
  6538. if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
  6539. if (!getCurScope()->isFunctionScope()) {
  6540. if (T.getAddressSpace() == LangAS::opencl_constant)
  6541. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6542. << "constant";
  6543. else
  6544. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6545. << "local";
  6546. NewVD->setInvalidDecl();
  6547. return;
  6548. }
  6549. }
  6550. } else if (T.getAddressSpace() != LangAS::opencl_private) {
  6551. // Do not allow other address spaces on automatic variable.
  6552. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
  6553. NewVD->setInvalidDecl();
  6554. return;
  6555. }
  6556. }
  6557. }
  6558. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  6559. && !NewVD->hasAttr<BlocksAttr>()) {
  6560. if (getLangOpts().getGC() != LangOptions::NonGC)
  6561. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  6562. else {
  6563. assert(!getLangOpts().ObjCAutoRefCount);
  6564. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  6565. }
  6566. }
  6567. bool isVM = T->isVariablyModifiedType();
  6568. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  6569. NewVD->hasAttr<BlocksAttr>())
  6570. setFunctionHasBranchProtectedScope();
  6571. if ((isVM && NewVD->hasLinkage()) ||
  6572. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  6573. bool SizeIsNegative;
  6574. llvm::APSInt Oversized;
  6575. TypeSourceInfo *FixedTInfo =
  6576. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  6577. SizeIsNegative, Oversized);
  6578. if (!FixedTInfo && T->isVariableArrayType()) {
  6579. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  6580. // FIXME: This won't give the correct result for
  6581. // int a[10][n];
  6582. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  6583. if (NewVD->isFileVarDecl())
  6584. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  6585. << SizeRange;
  6586. else if (NewVD->isStaticLocal())
  6587. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  6588. << SizeRange;
  6589. else
  6590. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  6591. << SizeRange;
  6592. NewVD->setInvalidDecl();
  6593. return;
  6594. }
  6595. if (!FixedTInfo) {
  6596. if (NewVD->isFileVarDecl())
  6597. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  6598. else
  6599. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  6600. NewVD->setInvalidDecl();
  6601. return;
  6602. }
  6603. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  6604. NewVD->setType(FixedTInfo->getType());
  6605. NewVD->setTypeSourceInfo(FixedTInfo);
  6606. }
  6607. if (T->isVoidType()) {
  6608. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  6609. // of objects and functions.
  6610. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  6611. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  6612. << T;
  6613. NewVD->setInvalidDecl();
  6614. return;
  6615. }
  6616. }
  6617. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  6618. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  6619. NewVD->setInvalidDecl();
  6620. return;
  6621. }
  6622. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  6623. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  6624. NewVD->setInvalidDecl();
  6625. return;
  6626. }
  6627. if (NewVD->isConstexpr() && !T->isDependentType() &&
  6628. RequireLiteralType(NewVD->getLocation(), T,
  6629. diag::err_constexpr_var_non_literal)) {
  6630. NewVD->setInvalidDecl();
  6631. return;
  6632. }
  6633. }
  6634. /// \brief Perform semantic checking on a newly-created variable
  6635. /// declaration.
  6636. ///
  6637. /// This routine performs all of the type-checking required for a
  6638. /// variable declaration once it has been built. It is used both to
  6639. /// check variables after they have been parsed and their declarators
  6640. /// have been translated into a declaration, and to check variables
  6641. /// that have been instantiated from a template.
  6642. ///
  6643. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  6644. ///
  6645. /// Returns true if the variable declaration is a redeclaration.
  6646. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  6647. CheckVariableDeclarationType(NewVD);
  6648. // If the decl is already known invalid, don't check it.
  6649. if (NewVD->isInvalidDecl())
  6650. return false;
  6651. // If we did not find anything by this name, look for a non-visible
  6652. // extern "C" declaration with the same name.
  6653. if (Previous.empty() &&
  6654. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  6655. Previous.setShadowed();
  6656. if (!Previous.empty()) {
  6657. MergeVarDecl(NewVD, Previous);
  6658. return true;
  6659. }
  6660. return false;
  6661. }
  6662. namespace {
  6663. struct FindOverriddenMethod {
  6664. Sema *S;
  6665. CXXMethodDecl *Method;
  6666. /// Member lookup function that determines whether a given C++
  6667. /// method overrides a method in a base class, to be used with
  6668. /// CXXRecordDecl::lookupInBases().
  6669. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6670. RecordDecl *BaseRecord =
  6671. Specifier->getType()->getAs<RecordType>()->getDecl();
  6672. DeclarationName Name = Method->getDeclName();
  6673. // FIXME: Do we care about other names here too?
  6674. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6675. // We really want to find the base class destructor here.
  6676. QualType T = S->Context.getTypeDeclType(BaseRecord);
  6677. CanQualType CT = S->Context.getCanonicalType(T);
  6678. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  6679. }
  6680. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6681. Path.Decls = Path.Decls.slice(1)) {
  6682. NamedDecl *D = Path.Decls.front();
  6683. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6684. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  6685. return true;
  6686. }
  6687. }
  6688. return false;
  6689. }
  6690. };
  6691. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  6692. } // end anonymous namespace
  6693. /// \brief Report an error regarding overriding, along with any relevant
  6694. /// overridden methods.
  6695. ///
  6696. /// \param DiagID the primary error to report.
  6697. /// \param MD the overriding method.
  6698. /// \param OEK which overrides to include as notes.
  6699. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  6700. OverrideErrorKind OEK = OEK_All) {
  6701. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  6702. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  6703. // This check (& the OEK parameter) could be replaced by a predicate, but
  6704. // without lambdas that would be overkill. This is still nicer than writing
  6705. // out the diag loop 3 times.
  6706. if ((OEK == OEK_All) ||
  6707. (OEK == OEK_NonDeleted && !O->isDeleted()) ||
  6708. (OEK == OEK_Deleted && O->isDeleted()))
  6709. S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
  6710. }
  6711. }
  6712. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  6713. /// and if so, check that it's a valid override and remember it.
  6714. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  6715. // Look for methods in base classes that this method might override.
  6716. CXXBasePaths Paths;
  6717. FindOverriddenMethod FOM;
  6718. FOM.Method = MD;
  6719. FOM.S = this;
  6720. bool hasDeletedOverridenMethods = false;
  6721. bool hasNonDeletedOverridenMethods = false;
  6722. bool AddedAny = false;
  6723. if (DC->lookupInBases(FOM, Paths)) {
  6724. for (auto *I : Paths.found_decls()) {
  6725. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  6726. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  6727. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  6728. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  6729. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  6730. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  6731. hasDeletedOverridenMethods |= OldMD->isDeleted();
  6732. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  6733. AddedAny = true;
  6734. }
  6735. }
  6736. }
  6737. }
  6738. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  6739. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  6740. }
  6741. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  6742. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  6743. }
  6744. return AddedAny;
  6745. }
  6746. namespace {
  6747. // Struct for holding all of the extra arguments needed by
  6748. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  6749. struct ActOnFDArgs {
  6750. Scope *S;
  6751. Declarator &D;
  6752. MultiTemplateParamsArg TemplateParamLists;
  6753. bool AddToScope;
  6754. };
  6755. } // end anonymous namespace
  6756. namespace {
  6757. // Callback to only accept typo corrections that have a non-zero edit distance.
  6758. // Also only accept corrections that have the same parent decl.
  6759. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  6760. public:
  6761. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  6762. CXXRecordDecl *Parent)
  6763. : Context(Context), OriginalFD(TypoFD),
  6764. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  6765. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6766. if (candidate.getEditDistance() == 0)
  6767. return false;
  6768. SmallVector<unsigned, 1> MismatchedParams;
  6769. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  6770. CDeclEnd = candidate.end();
  6771. CDecl != CDeclEnd; ++CDecl) {
  6772. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6773. if (FD && !FD->hasBody() &&
  6774. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  6775. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  6776. CXXRecordDecl *Parent = MD->getParent();
  6777. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  6778. return true;
  6779. } else if (!ExpectedParent) {
  6780. return true;
  6781. }
  6782. }
  6783. }
  6784. return false;
  6785. }
  6786. private:
  6787. ASTContext &Context;
  6788. FunctionDecl *OriginalFD;
  6789. CXXRecordDecl *ExpectedParent;
  6790. };
  6791. } // end anonymous namespace
  6792. void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
  6793. TypoCorrectedFunctionDefinitions.insert(F);
  6794. }
  6795. /// \brief Generate diagnostics for an invalid function redeclaration.
  6796. ///
  6797. /// This routine handles generating the diagnostic messages for an invalid
  6798. /// function redeclaration, including finding possible similar declarations
  6799. /// or performing typo correction if there are no previous declarations with
  6800. /// the same name.
  6801. ///
  6802. /// Returns a NamedDecl iff typo correction was performed and substituting in
  6803. /// the new declaration name does not cause new errors.
  6804. static NamedDecl *DiagnoseInvalidRedeclaration(
  6805. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  6806. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  6807. DeclarationName Name = NewFD->getDeclName();
  6808. DeclContext *NewDC = NewFD->getDeclContext();
  6809. SmallVector<unsigned, 1> MismatchedParams;
  6810. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  6811. TypoCorrection Correction;
  6812. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  6813. unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
  6814. : diag::err_member_decl_does_not_match;
  6815. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  6816. IsLocalFriend ? Sema::LookupLocalFriendName
  6817. : Sema::LookupOrdinaryName,
  6818. Sema::ForVisibleRedeclaration);
  6819. NewFD->setInvalidDecl();
  6820. if (IsLocalFriend)
  6821. SemaRef.LookupName(Prev, S);
  6822. else
  6823. SemaRef.LookupQualifiedName(Prev, NewDC);
  6824. assert(!Prev.isAmbiguous() &&
  6825. "Cannot have an ambiguity in previous-declaration lookup");
  6826. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  6827. if (!Prev.empty()) {
  6828. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  6829. Func != FuncEnd; ++Func) {
  6830. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  6831. if (FD &&
  6832. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6833. // Add 1 to the index so that 0 can mean the mismatch didn't
  6834. // involve a parameter
  6835. unsigned ParamNum =
  6836. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  6837. NearMatches.push_back(std::make_pair(FD, ParamNum));
  6838. }
  6839. }
  6840. // If the qualified name lookup yielded nothing, try typo correction
  6841. } else if ((Correction = SemaRef.CorrectTypo(
  6842. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  6843. &ExtraArgs.D.getCXXScopeSpec(),
  6844. llvm::make_unique<DifferentNameValidatorCCC>(
  6845. SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
  6846. Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
  6847. // Set up everything for the call to ActOnFunctionDeclarator
  6848. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  6849. ExtraArgs.D.getIdentifierLoc());
  6850. Previous.clear();
  6851. Previous.setLookupName(Correction.getCorrection());
  6852. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  6853. CDeclEnd = Correction.end();
  6854. CDecl != CDeclEnd; ++CDecl) {
  6855. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6856. if (FD && !FD->hasBody() &&
  6857. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6858. Previous.addDecl(FD);
  6859. }
  6860. }
  6861. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  6862. NamedDecl *Result;
  6863. // Retry building the function declaration with the new previous
  6864. // declarations, and with errors suppressed.
  6865. {
  6866. // Trap errors.
  6867. Sema::SFINAETrap Trap(SemaRef);
  6868. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  6869. // pieces need to verify the typo-corrected C++ declaration and hopefully
  6870. // eliminate the need for the parameter pack ExtraArgs.
  6871. Result = SemaRef.ActOnFunctionDeclarator(
  6872. ExtraArgs.S, ExtraArgs.D,
  6873. Correction.getCorrectionDecl()->getDeclContext(),
  6874. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  6875. ExtraArgs.AddToScope);
  6876. if (Trap.hasErrorOccurred())
  6877. Result = nullptr;
  6878. }
  6879. if (Result) {
  6880. // Determine which correction we picked.
  6881. Decl *Canonical = Result->getCanonicalDecl();
  6882. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6883. I != E; ++I)
  6884. if ((*I)->getCanonicalDecl() == Canonical)
  6885. Correction.setCorrectionDecl(*I);
  6886. // Let Sema know about the correction.
  6887. SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
  6888. SemaRef.diagnoseTypo(
  6889. Correction,
  6890. SemaRef.PDiag(IsLocalFriend
  6891. ? diag::err_no_matching_local_friend_suggest
  6892. : diag::err_member_decl_does_not_match_suggest)
  6893. << Name << NewDC << IsDefinition);
  6894. return Result;
  6895. }
  6896. // Pretend the typo correction never occurred
  6897. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  6898. ExtraArgs.D.getIdentifierLoc());
  6899. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  6900. Previous.clear();
  6901. Previous.setLookupName(Name);
  6902. }
  6903. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  6904. << Name << NewDC << IsDefinition << NewFD->getLocation();
  6905. bool NewFDisConst = false;
  6906. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  6907. NewFDisConst = NewMD->isConst();
  6908. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  6909. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  6910. NearMatch != NearMatchEnd; ++NearMatch) {
  6911. FunctionDecl *FD = NearMatch->first;
  6912. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6913. bool FDisConst = MD && MD->isConst();
  6914. bool IsMember = MD || !IsLocalFriend;
  6915. // FIXME: These notes are poorly worded for the local friend case.
  6916. if (unsigned Idx = NearMatch->second) {
  6917. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  6918. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  6919. if (Loc.isInvalid()) Loc = FD->getLocation();
  6920. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  6921. : diag::note_local_decl_close_param_match)
  6922. << Idx << FDParam->getType()
  6923. << NewFD->getParamDecl(Idx - 1)->getType();
  6924. } else if (FDisConst != NewFDisConst) {
  6925. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  6926. << NewFDisConst << FD->getSourceRange().getEnd();
  6927. } else
  6928. SemaRef.Diag(FD->getLocation(),
  6929. IsMember ? diag::note_member_def_close_match
  6930. : diag::note_local_decl_close_match);
  6931. }
  6932. return nullptr;
  6933. }
  6934. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  6935. switch (D.getDeclSpec().getStorageClassSpec()) {
  6936. default: llvm_unreachable("Unknown storage class!");
  6937. case DeclSpec::SCS_auto:
  6938. case DeclSpec::SCS_register:
  6939. case DeclSpec::SCS_mutable:
  6940. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6941. diag::err_typecheck_sclass_func);
  6942. D.getMutableDeclSpec().ClearStorageClassSpecs();
  6943. D.setInvalidType();
  6944. break;
  6945. case DeclSpec::SCS_unspecified: break;
  6946. case DeclSpec::SCS_extern:
  6947. if (D.getDeclSpec().isExternInLinkageSpec())
  6948. return SC_None;
  6949. return SC_Extern;
  6950. case DeclSpec::SCS_static: {
  6951. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  6952. // C99 6.7.1p5:
  6953. // The declaration of an identifier for a function that has
  6954. // block scope shall have no explicit storage-class specifier
  6955. // other than extern
  6956. // See also (C++ [dcl.stc]p4).
  6957. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6958. diag::err_static_block_func);
  6959. break;
  6960. } else
  6961. return SC_Static;
  6962. }
  6963. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  6964. }
  6965. // No explicit storage class has already been returned
  6966. return SC_None;
  6967. }
  6968. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  6969. DeclContext *DC, QualType &R,
  6970. TypeSourceInfo *TInfo,
  6971. StorageClass SC,
  6972. bool &IsVirtualOkay) {
  6973. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  6974. DeclarationName Name = NameInfo.getName();
  6975. FunctionDecl *NewFD = nullptr;
  6976. bool isInline = D.getDeclSpec().isInlineSpecified();
  6977. if (!SemaRef.getLangOpts().CPlusPlus) {
  6978. // Determine whether the function was written with a
  6979. // prototype. This true when:
  6980. // - there is a prototype in the declarator, or
  6981. // - the type R of the function is some kind of typedef or other non-
  6982. // attributed reference to a type name (which eventually refers to a
  6983. // function type).
  6984. bool HasPrototype =
  6985. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  6986. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  6987. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  6988. D.getLocStart(), NameInfo, R,
  6989. TInfo, SC, isInline,
  6990. HasPrototype, false);
  6991. if (D.isInvalidType())
  6992. NewFD->setInvalidDecl();
  6993. return NewFD;
  6994. }
  6995. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  6996. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  6997. // Check that the return type is not an abstract class type.
  6998. // For record types, this is done by the AbstractClassUsageDiagnoser once
  6999. // the class has been completely parsed.
  7000. if (!DC->isRecord() &&
  7001. SemaRef.RequireNonAbstractType(
  7002. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  7003. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  7004. D.setInvalidType();
  7005. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  7006. // This is a C++ constructor declaration.
  7007. assert(DC->isRecord() &&
  7008. "Constructors can only be declared in a member context");
  7009. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  7010. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  7011. D.getLocStart(), NameInfo,
  7012. R, TInfo, isExplicit, isInline,
  7013. /*isImplicitlyDeclared=*/false,
  7014. isConstexpr);
  7015. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7016. // This is a C++ destructor declaration.
  7017. if (DC->isRecord()) {
  7018. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  7019. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  7020. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  7021. SemaRef.Context, Record,
  7022. D.getLocStart(),
  7023. NameInfo, R, TInfo, isInline,
  7024. /*isImplicitlyDeclared=*/false);
  7025. // If the class is complete, then we now create the implicit exception
  7026. // specification. If the class is incomplete or dependent, we can't do
  7027. // it yet.
  7028. if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
  7029. Record->getDefinition() && !Record->isBeingDefined() &&
  7030. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  7031. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  7032. }
  7033. IsVirtualOkay = true;
  7034. return NewDD;
  7035. } else {
  7036. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  7037. D.setInvalidType();
  7038. // Create a FunctionDecl to satisfy the function definition parsing
  7039. // code path.
  7040. return FunctionDecl::Create(SemaRef.Context, DC,
  7041. D.getLocStart(),
  7042. D.getIdentifierLoc(), Name, R, TInfo,
  7043. SC, isInline,
  7044. /*hasPrototype=*/true, isConstexpr);
  7045. }
  7046. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  7047. if (!DC->isRecord()) {
  7048. SemaRef.Diag(D.getIdentifierLoc(),
  7049. diag::err_conv_function_not_member);
  7050. return nullptr;
  7051. }
  7052. SemaRef.CheckConversionDeclarator(D, R, SC);
  7053. IsVirtualOkay = true;
  7054. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  7055. D.getLocStart(), NameInfo,
  7056. R, TInfo, isInline, isExplicit,
  7057. isConstexpr, SourceLocation());
  7058. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  7059. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  7060. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
  7061. isExplicit, NameInfo, R, TInfo,
  7062. D.getLocEnd());
  7063. } else if (DC->isRecord()) {
  7064. // If the name of the function is the same as the name of the record,
  7065. // then this must be an invalid constructor that has a return type.
  7066. // (The parser checks for a return type and makes the declarator a
  7067. // constructor if it has no return type).
  7068. if (Name.getAsIdentifierInfo() &&
  7069. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  7070. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  7071. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7072. << SourceRange(D.getIdentifierLoc());
  7073. return nullptr;
  7074. }
  7075. // This is a C++ method declaration.
  7076. CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
  7077. cast<CXXRecordDecl>(DC),
  7078. D.getLocStart(), NameInfo, R,
  7079. TInfo, SC, isInline,
  7080. isConstexpr, SourceLocation());
  7081. IsVirtualOkay = !Ret->isStatic();
  7082. return Ret;
  7083. } else {
  7084. bool isFriend =
  7085. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  7086. if (!isFriend && SemaRef.CurContext->isRecord())
  7087. return nullptr;
  7088. // Determine whether the function was written with a
  7089. // prototype. This true when:
  7090. // - we're in C++ (where every function has a prototype),
  7091. return FunctionDecl::Create(SemaRef.Context, DC,
  7092. D.getLocStart(),
  7093. NameInfo, R, TInfo, SC, isInline,
  7094. true/*HasPrototype*/, isConstexpr);
  7095. }
  7096. }
  7097. enum OpenCLParamType {
  7098. ValidKernelParam,
  7099. PtrPtrKernelParam,
  7100. PtrKernelParam,
  7101. InvalidAddrSpacePtrKernelParam,
  7102. InvalidKernelParam,
  7103. RecordKernelParam
  7104. };
  7105. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  7106. if (PT->isPointerType()) {
  7107. QualType PointeeType = PT->getPointeeType();
  7108. if (PointeeType->isPointerType())
  7109. return PtrPtrKernelParam;
  7110. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  7111. PointeeType.getAddressSpace() == LangAS::opencl_private ||
  7112. PointeeType.getAddressSpace() == LangAS::Default)
  7113. return InvalidAddrSpacePtrKernelParam;
  7114. return PtrKernelParam;
  7115. }
  7116. // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
  7117. // be used as builtin types.
  7118. if (PT->isImageType())
  7119. return PtrKernelParam;
  7120. if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
  7121. return InvalidKernelParam;
  7122. // OpenCL extension spec v1.2 s9.5:
  7123. // This extension adds support for half scalar and vector types as built-in
  7124. // types that can be used for arithmetic operations, conversions etc.
  7125. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
  7126. return InvalidKernelParam;
  7127. if (PT->isRecordType())
  7128. return RecordKernelParam;
  7129. return ValidKernelParam;
  7130. }
  7131. static void checkIsValidOpenCLKernelParameter(
  7132. Sema &S,
  7133. Declarator &D,
  7134. ParmVarDecl *Param,
  7135. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  7136. QualType PT = Param->getType();
  7137. // Cache the valid types we encounter to avoid rechecking structs that are
  7138. // used again
  7139. if (ValidTypes.count(PT.getTypePtr()))
  7140. return;
  7141. switch (getOpenCLKernelParameterType(S, PT)) {
  7142. case PtrPtrKernelParam:
  7143. // OpenCL v1.2 s6.9.a:
  7144. // A kernel function argument cannot be declared as a
  7145. // pointer to a pointer type.
  7146. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  7147. D.setInvalidType();
  7148. return;
  7149. case InvalidAddrSpacePtrKernelParam:
  7150. // OpenCL v1.0 s6.5:
  7151. // __kernel function arguments declared to be a pointer of a type can point
  7152. // to one of the following address spaces only : __global, __local or
  7153. // __constant.
  7154. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  7155. D.setInvalidType();
  7156. return;
  7157. // OpenCL v1.2 s6.9.k:
  7158. // Arguments to kernel functions in a program cannot be declared with the
  7159. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7160. // uintptr_t or a struct and/or union that contain fields declared to be
  7161. // one of these built-in scalar types.
  7162. case InvalidKernelParam:
  7163. // OpenCL v1.2 s6.8 n:
  7164. // A kernel function argument cannot be declared
  7165. // of event_t type.
  7166. // Do not diagnose half type since it is diagnosed as invalid argument
  7167. // type for any function elsewhere.
  7168. if (!PT->isHalfType())
  7169. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7170. D.setInvalidType();
  7171. return;
  7172. case PtrKernelParam:
  7173. case ValidKernelParam:
  7174. ValidTypes.insert(PT.getTypePtr());
  7175. return;
  7176. case RecordKernelParam:
  7177. break;
  7178. }
  7179. // Track nested structs we will inspect
  7180. SmallVector<const Decl *, 4> VisitStack;
  7181. // Track where we are in the nested structs. Items will migrate from
  7182. // VisitStack to HistoryStack as we do the DFS for bad field.
  7183. SmallVector<const FieldDecl *, 4> HistoryStack;
  7184. HistoryStack.push_back(nullptr);
  7185. const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
  7186. VisitStack.push_back(PD);
  7187. assert(VisitStack.back() && "First decl null?");
  7188. do {
  7189. const Decl *Next = VisitStack.pop_back_val();
  7190. if (!Next) {
  7191. assert(!HistoryStack.empty());
  7192. // Found a marker, we have gone up a level
  7193. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  7194. ValidTypes.insert(Hist->getType().getTypePtr());
  7195. continue;
  7196. }
  7197. // Adds everything except the original parameter declaration (which is not a
  7198. // field itself) to the history stack.
  7199. const RecordDecl *RD;
  7200. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  7201. HistoryStack.push_back(Field);
  7202. RD = Field->getType()->castAs<RecordType>()->getDecl();
  7203. } else {
  7204. RD = cast<RecordDecl>(Next);
  7205. }
  7206. // Add a null marker so we know when we've gone back up a level
  7207. VisitStack.push_back(nullptr);
  7208. for (const auto *FD : RD->fields()) {
  7209. QualType QT = FD->getType();
  7210. if (ValidTypes.count(QT.getTypePtr()))
  7211. continue;
  7212. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  7213. if (ParamType == ValidKernelParam)
  7214. continue;
  7215. if (ParamType == RecordKernelParam) {
  7216. VisitStack.push_back(FD);
  7217. continue;
  7218. }
  7219. // OpenCL v1.2 s6.9.p:
  7220. // Arguments to kernel functions that are declared to be a struct or union
  7221. // do not allow OpenCL objects to be passed as elements of the struct or
  7222. // union.
  7223. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  7224. ParamType == InvalidAddrSpacePtrKernelParam) {
  7225. S.Diag(Param->getLocation(),
  7226. diag::err_record_with_pointers_kernel_param)
  7227. << PT->isUnionType()
  7228. << PT;
  7229. } else {
  7230. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7231. }
  7232. S.Diag(PD->getLocation(), diag::note_within_field_of_type)
  7233. << PD->getDeclName();
  7234. // We have an error, now let's go back up through history and show where
  7235. // the offending field came from
  7236. for (ArrayRef<const FieldDecl *>::const_iterator
  7237. I = HistoryStack.begin() + 1,
  7238. E = HistoryStack.end();
  7239. I != E; ++I) {
  7240. const FieldDecl *OuterField = *I;
  7241. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  7242. << OuterField->getType();
  7243. }
  7244. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  7245. << QT->isPointerType()
  7246. << QT;
  7247. D.setInvalidType();
  7248. return;
  7249. }
  7250. } while (!VisitStack.empty());
  7251. }
  7252. /// Find the DeclContext in which a tag is implicitly declared if we see an
  7253. /// elaborated type specifier in the specified context, and lookup finds
  7254. /// nothing.
  7255. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  7256. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  7257. DC = DC->getParent();
  7258. return DC;
  7259. }
  7260. /// Find the Scope in which a tag is implicitly declared if we see an
  7261. /// elaborated type specifier in the specified context, and lookup finds
  7262. /// nothing.
  7263. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  7264. while (S->isClassScope() ||
  7265. (LangOpts.CPlusPlus &&
  7266. S->isFunctionPrototypeScope()) ||
  7267. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7268. (S->getEntity() && S->getEntity()->isTransparentContext()))
  7269. S = S->getParent();
  7270. return S;
  7271. }
  7272. NamedDecl*
  7273. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  7274. TypeSourceInfo *TInfo, LookupResult &Previous,
  7275. MultiTemplateParamsArg TemplateParamLists,
  7276. bool &AddToScope) {
  7277. QualType R = TInfo->getType();
  7278. assert(R.getTypePtr()->isFunctionType());
  7279. // TODO: consider using NameInfo for diagnostic.
  7280. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  7281. DeclarationName Name = NameInfo.getName();
  7282. StorageClass SC = getFunctionStorageClass(*this, D);
  7283. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  7284. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  7285. diag::err_invalid_thread)
  7286. << DeclSpec::getSpecifierName(TSCS);
  7287. if (D.isFirstDeclarationOfMember())
  7288. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  7289. D.getIdentifierLoc());
  7290. bool isFriend = false;
  7291. FunctionTemplateDecl *FunctionTemplate = nullptr;
  7292. bool isMemberSpecialization = false;
  7293. bool isFunctionTemplateSpecialization = false;
  7294. bool isDependentClassScopeExplicitSpecialization = false;
  7295. bool HasExplicitTemplateArgs = false;
  7296. TemplateArgumentListInfo TemplateArgs;
  7297. bool isVirtualOkay = false;
  7298. DeclContext *OriginalDC = DC;
  7299. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  7300. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  7301. isVirtualOkay);
  7302. if (!NewFD) return nullptr;
  7303. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  7304. NewFD->setTopLevelDeclInObjCContainer();
  7305. // Set the lexical context. If this is a function-scope declaration, or has a
  7306. // C++ scope specifier, or is the object of a friend declaration, the lexical
  7307. // context will be different from the semantic context.
  7308. NewFD->setLexicalDeclContext(CurContext);
  7309. if (IsLocalExternDecl)
  7310. NewFD->setLocalExternDecl();
  7311. if (getLangOpts().CPlusPlus) {
  7312. bool isInline = D.getDeclSpec().isInlineSpecified();
  7313. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7314. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  7315. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  7316. isFriend = D.getDeclSpec().isFriendSpecified();
  7317. if (isFriend && !isInline && D.isFunctionDefinition()) {
  7318. // C++ [class.friend]p5
  7319. // A function can be defined in a friend declaration of a
  7320. // class . . . . Such a function is implicitly inline.
  7321. NewFD->setImplicitlyInline();
  7322. }
  7323. // If this is a method defined in an __interface, and is not a constructor
  7324. // or an overloaded operator, then set the pure flag (isVirtual will already
  7325. // return true).
  7326. if (const CXXRecordDecl *Parent =
  7327. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  7328. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  7329. NewFD->setPure(true);
  7330. // C++ [class.union]p2
  7331. // A union can have member functions, but not virtual functions.
  7332. if (isVirtual && Parent->isUnion())
  7333. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  7334. }
  7335. SetNestedNameSpecifier(NewFD, D);
  7336. isMemberSpecialization = false;
  7337. isFunctionTemplateSpecialization = false;
  7338. if (D.isInvalidType())
  7339. NewFD->setInvalidDecl();
  7340. // Match up the template parameter lists with the scope specifier, then
  7341. // determine whether we have a template or a template specialization.
  7342. bool Invalid = false;
  7343. if (TemplateParameterList *TemplateParams =
  7344. MatchTemplateParametersToScopeSpecifier(
  7345. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  7346. D.getCXXScopeSpec(),
  7347. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  7348. ? D.getName().TemplateId
  7349. : nullptr,
  7350. TemplateParamLists, isFriend, isMemberSpecialization,
  7351. Invalid)) {
  7352. if (TemplateParams->size() > 0) {
  7353. // This is a function template
  7354. // Check that we can declare a template here.
  7355. if (CheckTemplateDeclScope(S, TemplateParams))
  7356. NewFD->setInvalidDecl();
  7357. // A destructor cannot be a template.
  7358. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7359. Diag(NewFD->getLocation(), diag::err_destructor_template);
  7360. NewFD->setInvalidDecl();
  7361. }
  7362. // If we're adding a template to a dependent context, we may need to
  7363. // rebuilding some of the types used within the template parameter list,
  7364. // now that we know what the current instantiation is.
  7365. if (DC->isDependentContext()) {
  7366. ContextRAII SavedContext(*this, DC);
  7367. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  7368. Invalid = true;
  7369. }
  7370. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  7371. NewFD->getLocation(),
  7372. Name, TemplateParams,
  7373. NewFD);
  7374. FunctionTemplate->setLexicalDeclContext(CurContext);
  7375. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  7376. // For source fidelity, store the other template param lists.
  7377. if (TemplateParamLists.size() > 1) {
  7378. NewFD->setTemplateParameterListsInfo(Context,
  7379. TemplateParamLists.drop_back(1));
  7380. }
  7381. } else {
  7382. // This is a function template specialization.
  7383. isFunctionTemplateSpecialization = true;
  7384. // For source fidelity, store all the template param lists.
  7385. if (TemplateParamLists.size() > 0)
  7386. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7387. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  7388. if (isFriend) {
  7389. // We want to remove the "template<>", found here.
  7390. SourceRange RemoveRange = TemplateParams->getSourceRange();
  7391. // If we remove the template<> and the name is not a
  7392. // template-id, we're actually silently creating a problem:
  7393. // the friend declaration will refer to an untemplated decl,
  7394. // and clearly the user wants a template specialization. So
  7395. // we need to insert '<>' after the name.
  7396. SourceLocation InsertLoc;
  7397. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  7398. InsertLoc = D.getName().getSourceRange().getEnd();
  7399. InsertLoc = getLocForEndOfToken(InsertLoc);
  7400. }
  7401. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  7402. << Name << RemoveRange
  7403. << FixItHint::CreateRemoval(RemoveRange)
  7404. << FixItHint::CreateInsertion(InsertLoc, "<>");
  7405. }
  7406. }
  7407. }
  7408. else {
  7409. // All template param lists were matched against the scope specifier:
  7410. // this is NOT (an explicit specialization of) a template.
  7411. if (TemplateParamLists.size() > 0)
  7412. // For source fidelity, store all the template param lists.
  7413. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7414. }
  7415. if (Invalid) {
  7416. NewFD->setInvalidDecl();
  7417. if (FunctionTemplate)
  7418. FunctionTemplate->setInvalidDecl();
  7419. }
  7420. // C++ [dcl.fct.spec]p5:
  7421. // The virtual specifier shall only be used in declarations of
  7422. // nonstatic class member functions that appear within a
  7423. // member-specification of a class declaration; see 10.3.
  7424. //
  7425. if (isVirtual && !NewFD->isInvalidDecl()) {
  7426. if (!isVirtualOkay) {
  7427. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7428. diag::err_virtual_non_function);
  7429. } else if (!CurContext->isRecord()) {
  7430. // 'virtual' was specified outside of the class.
  7431. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7432. diag::err_virtual_out_of_class)
  7433. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7434. } else if (NewFD->getDescribedFunctionTemplate()) {
  7435. // C++ [temp.mem]p3:
  7436. // A member function template shall not be virtual.
  7437. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7438. diag::err_virtual_member_function_template)
  7439. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7440. } else {
  7441. // Okay: Add virtual to the method.
  7442. NewFD->setVirtualAsWritten(true);
  7443. }
  7444. if (getLangOpts().CPlusPlus14 &&
  7445. NewFD->getReturnType()->isUndeducedType())
  7446. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  7447. }
  7448. if (getLangOpts().CPlusPlus14 &&
  7449. (NewFD->isDependentContext() ||
  7450. (isFriend && CurContext->isDependentContext())) &&
  7451. NewFD->getReturnType()->isUndeducedType()) {
  7452. // If the function template is referenced directly (for instance, as a
  7453. // member of the current instantiation), pretend it has a dependent type.
  7454. // This is not really justified by the standard, but is the only sane
  7455. // thing to do.
  7456. // FIXME: For a friend function, we have not marked the function as being
  7457. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  7458. const FunctionProtoType *FPT =
  7459. NewFD->getType()->castAs<FunctionProtoType>();
  7460. QualType Result =
  7461. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  7462. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  7463. FPT->getExtProtoInfo()));
  7464. }
  7465. // C++ [dcl.fct.spec]p3:
  7466. // The inline specifier shall not appear on a block scope function
  7467. // declaration.
  7468. if (isInline && !NewFD->isInvalidDecl()) {
  7469. if (CurContext->isFunctionOrMethod()) {
  7470. // 'inline' is not allowed on block scope function declaration.
  7471. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7472. diag::err_inline_declaration_block_scope) << Name
  7473. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7474. }
  7475. }
  7476. // C++ [dcl.fct.spec]p6:
  7477. // The explicit specifier shall be used only in the declaration of a
  7478. // constructor or conversion function within its class definition;
  7479. // see 12.3.1 and 12.3.2.
  7480. if (isExplicit && !NewFD->isInvalidDecl() &&
  7481. !isa<CXXDeductionGuideDecl>(NewFD)) {
  7482. if (!CurContext->isRecord()) {
  7483. // 'explicit' was specified outside of the class.
  7484. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7485. diag::err_explicit_out_of_class)
  7486. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  7487. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  7488. !isa<CXXConversionDecl>(NewFD)) {
  7489. // 'explicit' was specified on a function that wasn't a constructor
  7490. // or conversion function.
  7491. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7492. diag::err_explicit_non_ctor_or_conv_function)
  7493. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  7494. }
  7495. }
  7496. if (isConstexpr) {
  7497. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  7498. // are implicitly inline.
  7499. NewFD->setImplicitlyInline();
  7500. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  7501. // be either constructors or to return a literal type. Therefore,
  7502. // destructors cannot be declared constexpr.
  7503. if (isa<CXXDestructorDecl>(NewFD))
  7504. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  7505. }
  7506. // If __module_private__ was specified, mark the function accordingly.
  7507. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7508. if (isFunctionTemplateSpecialization) {
  7509. SourceLocation ModulePrivateLoc
  7510. = D.getDeclSpec().getModulePrivateSpecLoc();
  7511. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  7512. << 0
  7513. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7514. } else {
  7515. NewFD->setModulePrivate();
  7516. if (FunctionTemplate)
  7517. FunctionTemplate->setModulePrivate();
  7518. }
  7519. }
  7520. if (isFriend) {
  7521. if (FunctionTemplate) {
  7522. FunctionTemplate->setObjectOfFriendDecl();
  7523. FunctionTemplate->setAccess(AS_public);
  7524. }
  7525. NewFD->setObjectOfFriendDecl();
  7526. NewFD->setAccess(AS_public);
  7527. }
  7528. // If a function is defined as defaulted or deleted, mark it as such now.
  7529. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  7530. // definition kind to FDK_Definition.
  7531. switch (D.getFunctionDefinitionKind()) {
  7532. case FDK_Declaration:
  7533. case FDK_Definition:
  7534. break;
  7535. case FDK_Defaulted:
  7536. NewFD->setDefaulted();
  7537. break;
  7538. case FDK_Deleted:
  7539. NewFD->setDeletedAsWritten();
  7540. break;
  7541. }
  7542. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  7543. D.isFunctionDefinition()) {
  7544. // C++ [class.mfct]p2:
  7545. // A member function may be defined (8.4) in its class definition, in
  7546. // which case it is an inline member function (7.1.2)
  7547. NewFD->setImplicitlyInline();
  7548. }
  7549. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  7550. !CurContext->isRecord()) {
  7551. // C++ [class.static]p1:
  7552. // A data or function member of a class may be declared static
  7553. // in a class definition, in which case it is a static member of
  7554. // the class.
  7555. // Complain about the 'static' specifier if it's on an out-of-line
  7556. // member function definition.
  7557. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7558. diag::err_static_out_of_line)
  7559. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7560. }
  7561. // C++11 [except.spec]p15:
  7562. // A deallocation function with no exception-specification is treated
  7563. // as if it were specified with noexcept(true).
  7564. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  7565. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  7566. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  7567. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  7568. NewFD->setType(Context.getFunctionType(
  7569. FPT->getReturnType(), FPT->getParamTypes(),
  7570. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  7571. }
  7572. // Filter out previous declarations that don't match the scope.
  7573. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  7574. D.getCXXScopeSpec().isNotEmpty() ||
  7575. isMemberSpecialization ||
  7576. isFunctionTemplateSpecialization);
  7577. // Handle GNU asm-label extension (encoded as an attribute).
  7578. if (Expr *E = (Expr*) D.getAsmLabel()) {
  7579. // The parser guarantees this is a string.
  7580. StringLiteral *SE = cast<StringLiteral>(E);
  7581. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  7582. SE->getString(), 0));
  7583. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7584. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7585. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  7586. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7587. if (isDeclExternC(NewFD)) {
  7588. NewFD->addAttr(I->second);
  7589. ExtnameUndeclaredIdentifiers.erase(I);
  7590. } else
  7591. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  7592. << /*Variable*/0 << NewFD;
  7593. }
  7594. }
  7595. // Copy the parameter declarations from the declarator D to the function
  7596. // declaration NewFD, if they are available. First scavenge them into Params.
  7597. SmallVector<ParmVarDecl*, 16> Params;
  7598. unsigned FTIIdx;
  7599. if (D.isFunctionDeclarator(FTIIdx)) {
  7600. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  7601. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  7602. // function that takes no arguments, not a function that takes a
  7603. // single void argument.
  7604. // We let through "const void" here because Sema::GetTypeForDeclarator
  7605. // already checks for that case.
  7606. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  7607. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  7608. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  7609. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  7610. Param->setDeclContext(NewFD);
  7611. Params.push_back(Param);
  7612. if (Param->isInvalidDecl())
  7613. NewFD->setInvalidDecl();
  7614. }
  7615. }
  7616. if (!getLangOpts().CPlusPlus) {
  7617. // In C, find all the tag declarations from the prototype and move them
  7618. // into the function DeclContext. Remove them from the surrounding tag
  7619. // injection context of the function, which is typically but not always
  7620. // the TU.
  7621. DeclContext *PrototypeTagContext =
  7622. getTagInjectionContext(NewFD->getLexicalDeclContext());
  7623. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  7624. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  7625. // We don't want to reparent enumerators. Look at their parent enum
  7626. // instead.
  7627. if (!TD) {
  7628. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  7629. TD = cast<EnumDecl>(ECD->getDeclContext());
  7630. }
  7631. if (!TD)
  7632. continue;
  7633. DeclContext *TagDC = TD->getLexicalDeclContext();
  7634. if (!TagDC->containsDecl(TD))
  7635. continue;
  7636. TagDC->removeDecl(TD);
  7637. TD->setDeclContext(NewFD);
  7638. NewFD->addDecl(TD);
  7639. // Preserve the lexical DeclContext if it is not the surrounding tag
  7640. // injection context of the FD. In this example, the semantic context of
  7641. // E will be f and the lexical context will be S, while both the
  7642. // semantic and lexical contexts of S will be f:
  7643. // void f(struct S { enum E { a } f; } s);
  7644. if (TagDC != PrototypeTagContext)
  7645. TD->setLexicalDeclContext(TagDC);
  7646. }
  7647. }
  7648. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  7649. // When we're declaring a function with a typedef, typeof, etc as in the
  7650. // following example, we'll need to synthesize (unnamed)
  7651. // parameters for use in the declaration.
  7652. //
  7653. // @code
  7654. // typedef void fn(int);
  7655. // fn f;
  7656. // @endcode
  7657. // Synthesize a parameter for each argument type.
  7658. for (const auto &AI : FT->param_types()) {
  7659. ParmVarDecl *Param =
  7660. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  7661. Param->setScopeInfo(0, Params.size());
  7662. Params.push_back(Param);
  7663. }
  7664. } else {
  7665. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  7666. "Should not need args for typedef of non-prototype fn");
  7667. }
  7668. // Finally, we know we have the right number of parameters, install them.
  7669. NewFD->setParams(Params);
  7670. if (D.getDeclSpec().isNoreturnSpecified())
  7671. NewFD->addAttr(
  7672. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  7673. Context, 0));
  7674. // Functions returning a variably modified type violate C99 6.7.5.2p2
  7675. // because all functions have linkage.
  7676. if (!NewFD->isInvalidDecl() &&
  7677. NewFD->getReturnType()->isVariablyModifiedType()) {
  7678. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  7679. NewFD->setInvalidDecl();
  7680. }
  7681. // Apply an implicit SectionAttr if '#pragma clang section text' is active
  7682. if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
  7683. !NewFD->hasAttr<SectionAttr>()) {
  7684. NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
  7685. PragmaClangTextSection.SectionName,
  7686. PragmaClangTextSection.PragmaLocation));
  7687. }
  7688. // Apply an implicit SectionAttr if #pragma code_seg is active.
  7689. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  7690. !NewFD->hasAttr<SectionAttr>()) {
  7691. NewFD->addAttr(
  7692. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  7693. CodeSegStack.CurrentValue->getString(),
  7694. CodeSegStack.CurrentPragmaLocation));
  7695. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  7696. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  7697. ASTContext::PSF_Read,
  7698. NewFD))
  7699. NewFD->dropAttr<SectionAttr>();
  7700. }
  7701. // Handle attributes.
  7702. ProcessDeclAttributes(S, NewFD, D);
  7703. if (getLangOpts().OpenCL) {
  7704. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  7705. // type declaration will generate a compilation error.
  7706. LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
  7707. if (AddressSpace != LangAS::Default) {
  7708. Diag(NewFD->getLocation(),
  7709. diag::err_opencl_return_value_with_address_space);
  7710. NewFD->setInvalidDecl();
  7711. }
  7712. }
  7713. if (!getLangOpts().CPlusPlus) {
  7714. // Perform semantic checking on the function declaration.
  7715. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7716. CheckMain(NewFD, D.getDeclSpec());
  7717. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7718. CheckMSVCRTEntryPoint(NewFD);
  7719. if (!NewFD->isInvalidDecl())
  7720. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7721. isMemberSpecialization));
  7722. else if (!Previous.empty())
  7723. // Recover gracefully from an invalid redeclaration.
  7724. D.setRedeclaration(true);
  7725. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7726. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7727. "previous declaration set still overloaded");
  7728. // Diagnose no-prototype function declarations with calling conventions that
  7729. // don't support variadic calls. Only do this in C and do it after merging
  7730. // possibly prototyped redeclarations.
  7731. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  7732. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  7733. CallingConv CC = FT->getExtInfo().getCC();
  7734. if (!supportsVariadicCall(CC)) {
  7735. // Windows system headers sometimes accidentally use stdcall without
  7736. // (void) parameters, so we relax this to a warning.
  7737. int DiagID =
  7738. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  7739. Diag(NewFD->getLocation(), DiagID)
  7740. << FunctionType::getNameForCallConv(CC);
  7741. }
  7742. }
  7743. } else {
  7744. // C++11 [replacement.functions]p3:
  7745. // The program's definitions shall not be specified as inline.
  7746. //
  7747. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  7748. //
  7749. // Suppress the diagnostic if the function is __attribute__((used)), since
  7750. // that forces an external definition to be emitted.
  7751. if (D.getDeclSpec().isInlineSpecified() &&
  7752. NewFD->isReplaceableGlobalAllocationFunction() &&
  7753. !NewFD->hasAttr<UsedAttr>())
  7754. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7755. diag::ext_operator_new_delete_declared_inline)
  7756. << NewFD->getDeclName();
  7757. // If the declarator is a template-id, translate the parser's template
  7758. // argument list into our AST format.
  7759. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  7760. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  7761. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  7762. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  7763. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  7764. TemplateId->NumArgs);
  7765. translateTemplateArguments(TemplateArgsPtr,
  7766. TemplateArgs);
  7767. HasExplicitTemplateArgs = true;
  7768. if (NewFD->isInvalidDecl()) {
  7769. HasExplicitTemplateArgs = false;
  7770. } else if (FunctionTemplate) {
  7771. // Function template with explicit template arguments.
  7772. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  7773. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  7774. HasExplicitTemplateArgs = false;
  7775. } else {
  7776. assert((isFunctionTemplateSpecialization ||
  7777. D.getDeclSpec().isFriendSpecified()) &&
  7778. "should have a 'template<>' for this decl");
  7779. // "friend void foo<>(int);" is an implicit specialization decl.
  7780. isFunctionTemplateSpecialization = true;
  7781. }
  7782. } else if (isFriend && isFunctionTemplateSpecialization) {
  7783. // This combination is only possible in a recovery case; the user
  7784. // wrote something like:
  7785. // template <> friend void foo(int);
  7786. // which we're recovering from as if the user had written:
  7787. // friend void foo<>(int);
  7788. // Go ahead and fake up a template id.
  7789. HasExplicitTemplateArgs = true;
  7790. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  7791. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  7792. }
  7793. // We do not add HD attributes to specializations here because
  7794. // they may have different constexpr-ness compared to their
  7795. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  7796. // may end up with different effective targets. Instead, a
  7797. // specialization inherits its target attributes from its template
  7798. // in the CheckFunctionTemplateSpecialization() call below.
  7799. if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
  7800. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  7801. // If it's a friend (and only if it's a friend), it's possible
  7802. // that either the specialized function type or the specialized
  7803. // template is dependent, and therefore matching will fail. In
  7804. // this case, don't check the specialization yet.
  7805. bool InstantiationDependent = false;
  7806. if (isFunctionTemplateSpecialization && isFriend &&
  7807. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  7808. TemplateSpecializationType::anyDependentTemplateArguments(
  7809. TemplateArgs,
  7810. InstantiationDependent))) {
  7811. assert(HasExplicitTemplateArgs &&
  7812. "friend function specialization without template args");
  7813. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  7814. Previous))
  7815. NewFD->setInvalidDecl();
  7816. } else if (isFunctionTemplateSpecialization) {
  7817. if (CurContext->isDependentContext() && CurContext->isRecord()
  7818. && !isFriend) {
  7819. isDependentClassScopeExplicitSpecialization = true;
  7820. } else if (!NewFD->isInvalidDecl() &&
  7821. CheckFunctionTemplateSpecialization(
  7822. NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
  7823. Previous))
  7824. NewFD->setInvalidDecl();
  7825. // C++ [dcl.stc]p1:
  7826. // A storage-class-specifier shall not be specified in an explicit
  7827. // specialization (14.7.3)
  7828. FunctionTemplateSpecializationInfo *Info =
  7829. NewFD->getTemplateSpecializationInfo();
  7830. if (Info && SC != SC_None) {
  7831. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  7832. Diag(NewFD->getLocation(),
  7833. diag::err_explicit_specialization_inconsistent_storage_class)
  7834. << SC
  7835. << FixItHint::CreateRemoval(
  7836. D.getDeclSpec().getStorageClassSpecLoc());
  7837. else
  7838. Diag(NewFD->getLocation(),
  7839. diag::ext_explicit_specialization_storage_class)
  7840. << FixItHint::CreateRemoval(
  7841. D.getDeclSpec().getStorageClassSpecLoc());
  7842. }
  7843. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  7844. if (CheckMemberSpecialization(NewFD, Previous))
  7845. NewFD->setInvalidDecl();
  7846. }
  7847. // Perform semantic checking on the function declaration.
  7848. if (!isDependentClassScopeExplicitSpecialization) {
  7849. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7850. CheckMain(NewFD, D.getDeclSpec());
  7851. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7852. CheckMSVCRTEntryPoint(NewFD);
  7853. if (!NewFD->isInvalidDecl())
  7854. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7855. isMemberSpecialization));
  7856. else if (!Previous.empty())
  7857. // Recover gracefully from an invalid redeclaration.
  7858. D.setRedeclaration(true);
  7859. }
  7860. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7861. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7862. "previous declaration set still overloaded");
  7863. NamedDecl *PrincipalDecl = (FunctionTemplate
  7864. ? cast<NamedDecl>(FunctionTemplate)
  7865. : NewFD);
  7866. if (isFriend && NewFD->getPreviousDecl()) {
  7867. AccessSpecifier Access = AS_public;
  7868. if (!NewFD->isInvalidDecl())
  7869. Access = NewFD->getPreviousDecl()->getAccess();
  7870. NewFD->setAccess(Access);
  7871. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  7872. }
  7873. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  7874. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  7875. PrincipalDecl->setNonMemberOperator();
  7876. // If we have a function template, check the template parameter
  7877. // list. This will check and merge default template arguments.
  7878. if (FunctionTemplate) {
  7879. FunctionTemplateDecl *PrevTemplate =
  7880. FunctionTemplate->getPreviousDecl();
  7881. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  7882. PrevTemplate ? PrevTemplate->getTemplateParameters()
  7883. : nullptr,
  7884. D.getDeclSpec().isFriendSpecified()
  7885. ? (D.isFunctionDefinition()
  7886. ? TPC_FriendFunctionTemplateDefinition
  7887. : TPC_FriendFunctionTemplate)
  7888. : (D.getCXXScopeSpec().isSet() &&
  7889. DC && DC->isRecord() &&
  7890. DC->isDependentContext())
  7891. ? TPC_ClassTemplateMember
  7892. : TPC_FunctionTemplate);
  7893. }
  7894. if (NewFD->isInvalidDecl()) {
  7895. // Ignore all the rest of this.
  7896. } else if (!D.isRedeclaration()) {
  7897. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  7898. AddToScope };
  7899. // Fake up an access specifier if it's supposed to be a class member.
  7900. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  7901. NewFD->setAccess(AS_public);
  7902. // Qualified decls generally require a previous declaration.
  7903. if (D.getCXXScopeSpec().isSet()) {
  7904. // ...with the major exception of templated-scope or
  7905. // dependent-scope friend declarations.
  7906. // TODO: we currently also suppress this check in dependent
  7907. // contexts because (1) the parameter depth will be off when
  7908. // matching friend templates and (2) we might actually be
  7909. // selecting a friend based on a dependent factor. But there
  7910. // are situations where these conditions don't apply and we
  7911. // can actually do this check immediately.
  7912. if (isFriend &&
  7913. (TemplateParamLists.size() ||
  7914. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  7915. CurContext->isDependentContext())) {
  7916. // ignore these
  7917. } else {
  7918. // The user tried to provide an out-of-line definition for a
  7919. // function that is a member of a class or namespace, but there
  7920. // was no such member function declared (C++ [class.mfct]p2,
  7921. // C++ [namespace.memdef]p2). For example:
  7922. //
  7923. // class X {
  7924. // void f() const;
  7925. // };
  7926. //
  7927. // void X::f() { } // ill-formed
  7928. //
  7929. // Complain about this problem, and attempt to suggest close
  7930. // matches (e.g., those that differ only in cv-qualifiers and
  7931. // whether the parameter types are references).
  7932. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7933. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  7934. AddToScope = ExtraArgs.AddToScope;
  7935. return Result;
  7936. }
  7937. }
  7938. // Unqualified local friend declarations are required to resolve
  7939. // to something.
  7940. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  7941. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7942. *this, Previous, NewFD, ExtraArgs, true, S)) {
  7943. AddToScope = ExtraArgs.AddToScope;
  7944. return Result;
  7945. }
  7946. }
  7947. } else if (!D.isFunctionDefinition() &&
  7948. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  7949. !isFriend && !isFunctionTemplateSpecialization &&
  7950. !isMemberSpecialization) {
  7951. // An out-of-line member function declaration must also be a
  7952. // definition (C++ [class.mfct]p2).
  7953. // Note that this is not the case for explicit specializations of
  7954. // function templates or member functions of class templates, per
  7955. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  7956. // extension for compatibility with old SWIG code which likes to
  7957. // generate them.
  7958. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  7959. << D.getCXXScopeSpec().getRange();
  7960. }
  7961. }
  7962. ProcessPragmaWeak(S, NewFD);
  7963. checkAttributesAfterMerging(*this, *NewFD);
  7964. AddKnownFunctionAttributes(NewFD);
  7965. if (NewFD->hasAttr<OverloadableAttr>() &&
  7966. !NewFD->getType()->getAs<FunctionProtoType>()) {
  7967. Diag(NewFD->getLocation(),
  7968. diag::err_attribute_overloadable_no_prototype)
  7969. << NewFD;
  7970. // Turn this into a variadic function with no parameters.
  7971. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  7972. FunctionProtoType::ExtProtoInfo EPI(
  7973. Context.getDefaultCallingConvention(true, false));
  7974. EPI.Variadic = true;
  7975. EPI.ExtInfo = FT->getExtInfo();
  7976. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  7977. NewFD->setType(R);
  7978. }
  7979. // If there's a #pragma GCC visibility in scope, and this isn't a class
  7980. // member, set the visibility of this function.
  7981. if (!DC->isRecord() && NewFD->isExternallyVisible())
  7982. AddPushedVisibilityAttribute(NewFD);
  7983. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  7984. // marking the function.
  7985. AddCFAuditedAttribute(NewFD);
  7986. // If this is a function definition, check if we have to apply optnone due to
  7987. // a pragma.
  7988. if(D.isFunctionDefinition())
  7989. AddRangeBasedOptnone(NewFD);
  7990. // If this is the first declaration of an extern C variable, update
  7991. // the map of such variables.
  7992. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  7993. isIncompleteDeclExternC(*this, NewFD))
  7994. RegisterLocallyScopedExternCDecl(NewFD, S);
  7995. // Set this FunctionDecl's range up to the right paren.
  7996. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  7997. if (D.isRedeclaration() && !Previous.empty()) {
  7998. NamedDecl *Prev = Previous.getRepresentativeDecl();
  7999. checkDLLAttributeRedeclaration(*this, Prev, NewFD,
  8000. isMemberSpecialization ||
  8001. isFunctionTemplateSpecialization,
  8002. D.isFunctionDefinition());
  8003. }
  8004. if (getLangOpts().CUDA) {
  8005. IdentifierInfo *II = NewFD->getIdentifier();
  8006. if (II &&
  8007. II->isStr(getLangOpts().HIP ? "hipConfigureCall"
  8008. : "cudaConfigureCall") &&
  8009. !NewFD->isInvalidDecl() &&
  8010. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  8011. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  8012. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  8013. Context.setcudaConfigureCallDecl(NewFD);
  8014. }
  8015. // Variadic functions, other than a *declaration* of printf, are not allowed
  8016. // in device-side CUDA code, unless someone passed
  8017. // -fcuda-allow-variadic-functions.
  8018. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  8019. (NewFD->hasAttr<CUDADeviceAttr>() ||
  8020. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  8021. !(II && II->isStr("printf") && NewFD->isExternC() &&
  8022. !D.isFunctionDefinition())) {
  8023. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  8024. }
  8025. }
  8026. MarkUnusedFileScopedDecl(NewFD);
  8027. if (getLangOpts().CPlusPlus) {
  8028. if (FunctionTemplate) {
  8029. if (NewFD->isInvalidDecl())
  8030. FunctionTemplate->setInvalidDecl();
  8031. return FunctionTemplate;
  8032. }
  8033. if (isMemberSpecialization && !NewFD->isInvalidDecl())
  8034. CompleteMemberSpecialization(NewFD, Previous);
  8035. }
  8036. if (NewFD->hasAttr<OpenCLKernelAttr>()) {
  8037. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  8038. if ((getLangOpts().OpenCLVersion >= 120)
  8039. && (SC == SC_Static)) {
  8040. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  8041. D.setInvalidType();
  8042. }
  8043. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  8044. if (!NewFD->getReturnType()->isVoidType()) {
  8045. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  8046. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  8047. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  8048. : FixItHint());
  8049. D.setInvalidType();
  8050. }
  8051. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  8052. for (auto Param : NewFD->parameters())
  8053. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  8054. }
  8055. for (const ParmVarDecl *Param : NewFD->parameters()) {
  8056. QualType PT = Param->getType();
  8057. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  8058. // types.
  8059. if (getLangOpts().OpenCLVersion >= 200) {
  8060. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  8061. QualType ElemTy = PipeTy->getElementType();
  8062. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  8063. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  8064. D.setInvalidType();
  8065. }
  8066. }
  8067. }
  8068. }
  8069. // Here we have an function template explicit specialization at class scope.
  8070. // The actual specialization will be postponed to template instatiation
  8071. // time via the ClassScopeFunctionSpecializationDecl node.
  8072. if (isDependentClassScopeExplicitSpecialization) {
  8073. ClassScopeFunctionSpecializationDecl *NewSpec =
  8074. ClassScopeFunctionSpecializationDecl::Create(
  8075. Context, CurContext, NewFD->getLocation(),
  8076. cast<CXXMethodDecl>(NewFD),
  8077. HasExplicitTemplateArgs, TemplateArgs);
  8078. CurContext->addDecl(NewSpec);
  8079. AddToScope = false;
  8080. }
  8081. // Diagnose availability attributes. Availability cannot be used on functions
  8082. // that are run during load/unload.
  8083. if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
  8084. if (NewFD->hasAttr<ConstructorAttr>()) {
  8085. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8086. << 1;
  8087. NewFD->dropAttr<AvailabilityAttr>();
  8088. }
  8089. if (NewFD->hasAttr<DestructorAttr>()) {
  8090. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8091. << 2;
  8092. NewFD->dropAttr<AvailabilityAttr>();
  8093. }
  8094. }
  8095. return NewFD;
  8096. }
  8097. /// \brief Checks if the new declaration declared in dependent context must be
  8098. /// put in the same redeclaration chain as the specified declaration.
  8099. ///
  8100. /// \param D Declaration that is checked.
  8101. /// \param PrevDecl Previous declaration found with proper lookup method for the
  8102. /// same declaration name.
  8103. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  8104. /// belongs to.
  8105. ///
  8106. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  8107. // Any declarations should be put into redeclaration chains except for
  8108. // friend declaration in a dependent context that names a function in
  8109. // namespace scope.
  8110. //
  8111. // This allows to compile code like:
  8112. //
  8113. // void func();
  8114. // template<typename T> class C1 { friend void func() { } };
  8115. // template<typename T> class C2 { friend void func() { } };
  8116. //
  8117. // This code snippet is a valid code unless both templates are instantiated.
  8118. return !(D->getLexicalDeclContext()->isDependentContext() &&
  8119. D->getDeclContext()->isFileContext() &&
  8120. D->getFriendObjectKind() != Decl::FOK_None);
  8121. }
  8122. /// \brief Check the target attribute of the function for MultiVersion
  8123. /// validity.
  8124. ///
  8125. /// Returns true if there was an error, false otherwise.
  8126. static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
  8127. const auto *TA = FD->getAttr<TargetAttr>();
  8128. assert(TA && "MultiVersion Candidate requires a target attribute");
  8129. TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
  8130. const TargetInfo &TargetInfo = S.Context.getTargetInfo();
  8131. enum ErrType { Feature = 0, Architecture = 1 };
  8132. if (!ParseInfo.Architecture.empty() &&
  8133. !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
  8134. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8135. << Architecture << ParseInfo.Architecture;
  8136. return true;
  8137. }
  8138. for (const auto &Feat : ParseInfo.Features) {
  8139. auto BareFeat = StringRef{Feat}.substr(1);
  8140. if (Feat[0] == '-') {
  8141. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8142. << Feature << ("no-" + BareFeat).str();
  8143. return true;
  8144. }
  8145. if (!TargetInfo.validateCpuSupports(BareFeat) ||
  8146. !TargetInfo.isValidFeatureName(BareFeat)) {
  8147. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8148. << Feature << BareFeat;
  8149. return true;
  8150. }
  8151. }
  8152. return false;
  8153. }
  8154. static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
  8155. const FunctionDecl *NewFD,
  8156. bool CausesMV) {
  8157. enum DoesntSupport {
  8158. FuncTemplates = 0,
  8159. VirtFuncs = 1,
  8160. DeducedReturn = 2,
  8161. Constructors = 3,
  8162. Destructors = 4,
  8163. DeletedFuncs = 5,
  8164. DefaultedFuncs = 6
  8165. };
  8166. enum Different {
  8167. CallingConv = 0,
  8168. ReturnType = 1,
  8169. ConstexprSpec = 2,
  8170. InlineSpec = 3,
  8171. StorageClass = 4,
  8172. Linkage = 5
  8173. };
  8174. // For now, disallow all other attributes. These should be opt-in, but
  8175. // an analysis of all of them is a future FIXME.
  8176. if (CausesMV && OldFD &&
  8177. std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) {
  8178. S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs);
  8179. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8180. return true;
  8181. }
  8182. if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1)
  8183. return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs);
  8184. if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  8185. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8186. << FuncTemplates;
  8187. if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
  8188. if (NewCXXFD->isVirtual())
  8189. return S.Diag(NewCXXFD->getLocation(),
  8190. diag::err_multiversion_doesnt_support)
  8191. << VirtFuncs;
  8192. if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
  8193. return S.Diag(NewCXXCtor->getLocation(),
  8194. diag::err_multiversion_doesnt_support)
  8195. << Constructors;
  8196. if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
  8197. return S.Diag(NewCXXDtor->getLocation(),
  8198. diag::err_multiversion_doesnt_support)
  8199. << Destructors;
  8200. }
  8201. if (NewFD->isDeleted())
  8202. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8203. << DeletedFuncs;
  8204. if (NewFD->isDefaulted())
  8205. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8206. << DefaultedFuncs;
  8207. QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
  8208. const auto *NewType = cast<FunctionType>(NewQType);
  8209. QualType NewReturnType = NewType->getReturnType();
  8210. if (NewReturnType->isUndeducedType())
  8211. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8212. << DeducedReturn;
  8213. // Only allow transition to MultiVersion if it hasn't been used.
  8214. if (OldFD && CausesMV && OldFD->isUsed(false))
  8215. return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
  8216. // Ensure the return type is identical.
  8217. if (OldFD) {
  8218. QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
  8219. const auto *OldType = cast<FunctionType>(OldQType);
  8220. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  8221. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  8222. if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
  8223. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8224. << CallingConv;
  8225. QualType OldReturnType = OldType->getReturnType();
  8226. if (OldReturnType != NewReturnType)
  8227. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8228. << ReturnType;
  8229. if (OldFD->isConstexpr() != NewFD->isConstexpr())
  8230. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8231. << ConstexprSpec;
  8232. if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
  8233. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8234. << InlineSpec;
  8235. if (OldFD->getStorageClass() != NewFD->getStorageClass())
  8236. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8237. << StorageClass;
  8238. if (OldFD->isExternC() != NewFD->isExternC())
  8239. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8240. << Linkage;
  8241. if (S.CheckEquivalentExceptionSpec(
  8242. OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
  8243. NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
  8244. return true;
  8245. }
  8246. return false;
  8247. }
  8248. /// \brief Check the validity of a mulitversion function declaration.
  8249. /// Also sets the multiversion'ness' of the function itself.
  8250. ///
  8251. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8252. ///
  8253. /// Returns true if there was an error, false otherwise.
  8254. static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
  8255. bool &Redeclaration, NamedDecl *&OldDecl,
  8256. bool &MergeTypeWithPrevious,
  8257. LookupResult &Previous) {
  8258. const auto *NewTA = NewFD->getAttr<TargetAttr>();
  8259. if (NewFD->isMain()) {
  8260. if (NewTA && NewTA->isDefaultVersion()) {
  8261. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
  8262. NewFD->setInvalidDecl();
  8263. return true;
  8264. }
  8265. return false;
  8266. }
  8267. // If there is no matching previous decl, only 'default' can
  8268. // cause MultiVersioning.
  8269. if (!OldDecl) {
  8270. if (NewTA && NewTA->isDefaultVersion()) {
  8271. if (!NewFD->getType()->getAs<FunctionProtoType>()) {
  8272. S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
  8273. NewFD->setInvalidDecl();
  8274. return true;
  8275. }
  8276. if (CheckMultiVersionAdditionalRules(S, nullptr, NewFD, true)) {
  8277. NewFD->setInvalidDecl();
  8278. return true;
  8279. }
  8280. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8281. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8282. NewFD->setInvalidDecl();
  8283. return true;
  8284. }
  8285. NewFD->setIsMultiVersion();
  8286. }
  8287. return false;
  8288. }
  8289. if (OldDecl->getDeclContext()->getRedeclContext() !=
  8290. NewFD->getDeclContext()->getRedeclContext())
  8291. return false;
  8292. FunctionDecl *OldFD = OldDecl->getAsFunction();
  8293. // Unresolved 'using' statements (the other way OldDecl can be not a function)
  8294. // likely cannot cause a problem here.
  8295. if (!OldFD)
  8296. return false;
  8297. if (!OldFD->isMultiVersion() && !NewTA)
  8298. return false;
  8299. if (OldFD->isMultiVersion() && !NewTA) {
  8300. S.Diag(NewFD->getLocation(), diag::err_target_required_in_redecl);
  8301. NewFD->setInvalidDecl();
  8302. return true;
  8303. }
  8304. TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
  8305. // Sort order doesn't matter, it just needs to be consistent.
  8306. llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end());
  8307. const auto *OldTA = OldFD->getAttr<TargetAttr>();
  8308. if (!OldFD->isMultiVersion()) {
  8309. // If the old decl is NOT MultiVersioned yet, and we don't cause that
  8310. // to change, this is a simple redeclaration.
  8311. if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())
  8312. return false;
  8313. // Otherwise, this decl causes MultiVersioning.
  8314. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8315. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8316. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8317. NewFD->setInvalidDecl();
  8318. return true;
  8319. }
  8320. if (!OldFD->getType()->getAs<FunctionProtoType>()) {
  8321. S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
  8322. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8323. NewFD->setInvalidDecl();
  8324. return true;
  8325. }
  8326. if (CheckMultiVersionValue(S, NewFD)) {
  8327. NewFD->setInvalidDecl();
  8328. return true;
  8329. }
  8330. if (CheckMultiVersionValue(S, OldFD)) {
  8331. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8332. NewFD->setInvalidDecl();
  8333. return true;
  8334. }
  8335. TargetAttr::ParsedTargetAttr OldParsed =
  8336. OldTA->parse(std::less<std::string>());
  8337. if (OldParsed == NewParsed) {
  8338. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8339. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8340. NewFD->setInvalidDecl();
  8341. return true;
  8342. }
  8343. for (const auto *FD : OldFD->redecls()) {
  8344. const auto *CurTA = FD->getAttr<TargetAttr>();
  8345. if (!CurTA || CurTA->isInherited()) {
  8346. S.Diag(FD->getLocation(), diag::err_target_required_in_redecl);
  8347. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8348. NewFD->setInvalidDecl();
  8349. return true;
  8350. }
  8351. }
  8352. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true)) {
  8353. NewFD->setInvalidDecl();
  8354. return true;
  8355. }
  8356. OldFD->setIsMultiVersion();
  8357. NewFD->setIsMultiVersion();
  8358. Redeclaration = false;
  8359. MergeTypeWithPrevious = false;
  8360. OldDecl = nullptr;
  8361. Previous.clear();
  8362. return false;
  8363. }
  8364. bool UseMemberUsingDeclRules =
  8365. S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
  8366. // Next, check ALL non-overloads to see if this is a redeclaration of a
  8367. // previous member of the MultiVersion set.
  8368. for (NamedDecl *ND : Previous) {
  8369. FunctionDecl *CurFD = ND->getAsFunction();
  8370. if (!CurFD)
  8371. continue;
  8372. if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
  8373. continue;
  8374. const auto *CurTA = CurFD->getAttr<TargetAttr>();
  8375. if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
  8376. NewFD->setIsMultiVersion();
  8377. Redeclaration = true;
  8378. OldDecl = ND;
  8379. return false;
  8380. }
  8381. TargetAttr::ParsedTargetAttr CurParsed =
  8382. CurTA->parse(std::less<std::string>());
  8383. if (CurParsed == NewParsed) {
  8384. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8385. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8386. NewFD->setInvalidDecl();
  8387. return true;
  8388. }
  8389. }
  8390. // Else, this is simply a non-redecl case.
  8391. if (CheckMultiVersionValue(S, NewFD)) {
  8392. NewFD->setInvalidDecl();
  8393. return true;
  8394. }
  8395. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false)) {
  8396. NewFD->setInvalidDecl();
  8397. return true;
  8398. }
  8399. NewFD->setIsMultiVersion();
  8400. Redeclaration = false;
  8401. MergeTypeWithPrevious = false;
  8402. OldDecl = nullptr;
  8403. Previous.clear();
  8404. return false;
  8405. }
  8406. /// \brief Perform semantic checking of a new function declaration.
  8407. ///
  8408. /// Performs semantic analysis of the new function declaration
  8409. /// NewFD. This routine performs all semantic checking that does not
  8410. /// require the actual declarator involved in the declaration, and is
  8411. /// used both for the declaration of functions as they are parsed
  8412. /// (called via ActOnDeclarator) and for the declaration of functions
  8413. /// that have been instantiated via C++ template instantiation (called
  8414. /// via InstantiateDecl).
  8415. ///
  8416. /// \param IsMemberSpecialization whether this new function declaration is
  8417. /// a member specialization (that replaces any definition provided by the
  8418. /// previous declaration).
  8419. ///
  8420. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8421. ///
  8422. /// \returns true if the function declaration is a redeclaration.
  8423. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  8424. LookupResult &Previous,
  8425. bool IsMemberSpecialization) {
  8426. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  8427. "Variably modified return types are not handled here");
  8428. // Determine whether the type of this function should be merged with
  8429. // a previous visible declaration. This never happens for functions in C++,
  8430. // and always happens in C if the previous declaration was visible.
  8431. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  8432. !Previous.isShadowed();
  8433. bool Redeclaration = false;
  8434. NamedDecl *OldDecl = nullptr;
  8435. bool MayNeedOverloadableChecks = false;
  8436. // Merge or overload the declaration with an existing declaration of
  8437. // the same name, if appropriate.
  8438. if (!Previous.empty()) {
  8439. // Determine whether NewFD is an overload of PrevDecl or
  8440. // a declaration that requires merging. If it's an overload,
  8441. // there's no more work to do here; we'll just add the new
  8442. // function to the scope.
  8443. if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
  8444. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  8445. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  8446. Redeclaration = true;
  8447. OldDecl = Candidate;
  8448. }
  8449. } else {
  8450. MayNeedOverloadableChecks = true;
  8451. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  8452. /*NewIsUsingDecl*/ false)) {
  8453. case Ovl_Match:
  8454. Redeclaration = true;
  8455. break;
  8456. case Ovl_NonFunction:
  8457. Redeclaration = true;
  8458. break;
  8459. case Ovl_Overload:
  8460. Redeclaration = false;
  8461. break;
  8462. }
  8463. }
  8464. }
  8465. // Check for a previous extern "C" declaration with this name.
  8466. if (!Redeclaration &&
  8467. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  8468. if (!Previous.empty()) {
  8469. // This is an extern "C" declaration with the same name as a previous
  8470. // declaration, and thus redeclares that entity...
  8471. Redeclaration = true;
  8472. OldDecl = Previous.getFoundDecl();
  8473. MergeTypeWithPrevious = false;
  8474. // ... except in the presence of __attribute__((overloadable)).
  8475. if (OldDecl->hasAttr<OverloadableAttr>() ||
  8476. NewFD->hasAttr<OverloadableAttr>()) {
  8477. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  8478. MayNeedOverloadableChecks = true;
  8479. Redeclaration = false;
  8480. OldDecl = nullptr;
  8481. }
  8482. }
  8483. }
  8484. }
  8485. if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
  8486. MergeTypeWithPrevious, Previous))
  8487. return Redeclaration;
  8488. // C++11 [dcl.constexpr]p8:
  8489. // A constexpr specifier for a non-static member function that is not
  8490. // a constructor declares that member function to be const.
  8491. //
  8492. // This needs to be delayed until we know whether this is an out-of-line
  8493. // definition of a static member function.
  8494. //
  8495. // This rule is not present in C++1y, so we produce a backwards
  8496. // compatibility warning whenever it happens in C++11.
  8497. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  8498. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  8499. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  8500. (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
  8501. CXXMethodDecl *OldMD = nullptr;
  8502. if (OldDecl)
  8503. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  8504. if (!OldMD || !OldMD->isStatic()) {
  8505. const FunctionProtoType *FPT =
  8506. MD->getType()->castAs<FunctionProtoType>();
  8507. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  8508. EPI.TypeQuals |= Qualifiers::Const;
  8509. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  8510. FPT->getParamTypes(), EPI));
  8511. // Warn that we did this, if we're not performing template instantiation.
  8512. // In that case, we'll have warned already when the template was defined.
  8513. if (!inTemplateInstantiation()) {
  8514. SourceLocation AddConstLoc;
  8515. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  8516. .IgnoreParens().getAs<FunctionTypeLoc>())
  8517. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  8518. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  8519. << FixItHint::CreateInsertion(AddConstLoc, " const");
  8520. }
  8521. }
  8522. }
  8523. if (Redeclaration) {
  8524. // NewFD and OldDecl represent declarations that need to be
  8525. // merged.
  8526. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  8527. NewFD->setInvalidDecl();
  8528. return Redeclaration;
  8529. }
  8530. Previous.clear();
  8531. Previous.addDecl(OldDecl);
  8532. if (FunctionTemplateDecl *OldTemplateDecl =
  8533. dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  8534. auto *OldFD = OldTemplateDecl->getTemplatedDecl();
  8535. NewFD->setPreviousDeclaration(OldFD);
  8536. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  8537. FunctionTemplateDecl *NewTemplateDecl
  8538. = NewFD->getDescribedFunctionTemplate();
  8539. assert(NewTemplateDecl && "Template/non-template mismatch");
  8540. if (NewFD->isCXXClassMember()) {
  8541. NewFD->setAccess(OldTemplateDecl->getAccess());
  8542. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  8543. }
  8544. // If this is an explicit specialization of a member that is a function
  8545. // template, mark it as a member specialization.
  8546. if (IsMemberSpecialization &&
  8547. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  8548. NewTemplateDecl->setMemberSpecialization();
  8549. assert(OldTemplateDecl->isMemberSpecialization());
  8550. // Explicit specializations of a member template do not inherit deleted
  8551. // status from the parent member template that they are specializing.
  8552. if (OldFD->isDeleted()) {
  8553. // FIXME: This assert will not hold in the presence of modules.
  8554. assert(OldFD->getCanonicalDecl() == OldFD);
  8555. // FIXME: We need an update record for this AST mutation.
  8556. OldFD->setDeletedAsWritten(false);
  8557. }
  8558. }
  8559. } else {
  8560. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  8561. auto *OldFD = cast<FunctionDecl>(OldDecl);
  8562. // This needs to happen first so that 'inline' propagates.
  8563. NewFD->setPreviousDeclaration(OldFD);
  8564. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  8565. if (NewFD->isCXXClassMember())
  8566. NewFD->setAccess(OldFD->getAccess());
  8567. }
  8568. }
  8569. } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
  8570. !NewFD->getAttr<OverloadableAttr>()) {
  8571. assert((Previous.empty() ||
  8572. llvm::any_of(Previous,
  8573. [](const NamedDecl *ND) {
  8574. return ND->hasAttr<OverloadableAttr>();
  8575. })) &&
  8576. "Non-redecls shouldn't happen without overloadable present");
  8577. auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
  8578. const auto *FD = dyn_cast<FunctionDecl>(ND);
  8579. return FD && !FD->hasAttr<OverloadableAttr>();
  8580. });
  8581. if (OtherUnmarkedIter != Previous.end()) {
  8582. Diag(NewFD->getLocation(),
  8583. diag::err_attribute_overloadable_multiple_unmarked_overloads);
  8584. Diag((*OtherUnmarkedIter)->getLocation(),
  8585. diag::note_attribute_overloadable_prev_overload)
  8586. << false;
  8587. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  8588. }
  8589. }
  8590. // Semantic checking for this function declaration (in isolation).
  8591. if (getLangOpts().CPlusPlus) {
  8592. // C++-specific checks.
  8593. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  8594. CheckConstructor(Constructor);
  8595. } else if (CXXDestructorDecl *Destructor =
  8596. dyn_cast<CXXDestructorDecl>(NewFD)) {
  8597. CXXRecordDecl *Record = Destructor->getParent();
  8598. QualType ClassType = Context.getTypeDeclType(Record);
  8599. // FIXME: Shouldn't we be able to perform this check even when the class
  8600. // type is dependent? Both gcc and edg can handle that.
  8601. if (!ClassType->isDependentType()) {
  8602. DeclarationName Name
  8603. = Context.DeclarationNames.getCXXDestructorName(
  8604. Context.getCanonicalType(ClassType));
  8605. if (NewFD->getDeclName() != Name) {
  8606. Diag(NewFD->getLocation(), diag::err_destructor_name);
  8607. NewFD->setInvalidDecl();
  8608. return Redeclaration;
  8609. }
  8610. }
  8611. } else if (CXXConversionDecl *Conversion
  8612. = dyn_cast<CXXConversionDecl>(NewFD)) {
  8613. ActOnConversionDeclarator(Conversion);
  8614. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  8615. if (auto *TD = Guide->getDescribedFunctionTemplate())
  8616. CheckDeductionGuideTemplate(TD);
  8617. // A deduction guide is not on the list of entities that can be
  8618. // explicitly specialized.
  8619. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  8620. Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
  8621. << /*explicit specialization*/ 1;
  8622. }
  8623. // Find any virtual functions that this function overrides.
  8624. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  8625. if (!Method->isFunctionTemplateSpecialization() &&
  8626. !Method->getDescribedFunctionTemplate() &&
  8627. Method->isCanonicalDecl()) {
  8628. if (AddOverriddenMethods(Method->getParent(), Method)) {
  8629. // If the function was marked as "static", we have a problem.
  8630. if (NewFD->getStorageClass() == SC_Static) {
  8631. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  8632. }
  8633. }
  8634. }
  8635. if (Method->isStatic())
  8636. checkThisInStaticMemberFunctionType(Method);
  8637. }
  8638. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  8639. if (NewFD->isOverloadedOperator() &&
  8640. CheckOverloadedOperatorDeclaration(NewFD)) {
  8641. NewFD->setInvalidDecl();
  8642. return Redeclaration;
  8643. }
  8644. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  8645. if (NewFD->getLiteralIdentifier() &&
  8646. CheckLiteralOperatorDeclaration(NewFD)) {
  8647. NewFD->setInvalidDecl();
  8648. return Redeclaration;
  8649. }
  8650. // In C++, check default arguments now that we have merged decls. Unless
  8651. // the lexical context is the class, because in this case this is done
  8652. // during delayed parsing anyway.
  8653. if (!CurContext->isRecord())
  8654. CheckCXXDefaultArguments(NewFD);
  8655. // If this function declares a builtin function, check the type of this
  8656. // declaration against the expected type for the builtin.
  8657. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  8658. ASTContext::GetBuiltinTypeError Error;
  8659. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  8660. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  8661. // If the type of the builtin differs only in its exception
  8662. // specification, that's OK.
  8663. // FIXME: If the types do differ in this way, it would be better to
  8664. // retain the 'noexcept' form of the type.
  8665. if (!T.isNull() &&
  8666. !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
  8667. NewFD->getType()))
  8668. // The type of this function differs from the type of the builtin,
  8669. // so forget about the builtin entirely.
  8670. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  8671. }
  8672. // If this function is declared as being extern "C", then check to see if
  8673. // the function returns a UDT (class, struct, or union type) that is not C
  8674. // compatible, and if it does, warn the user.
  8675. // But, issue any diagnostic on the first declaration only.
  8676. if (Previous.empty() && NewFD->isExternC()) {
  8677. QualType R = NewFD->getReturnType();
  8678. if (R->isIncompleteType() && !R->isVoidType())
  8679. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  8680. << NewFD << R;
  8681. else if (!R.isPODType(Context) && !R->isVoidType() &&
  8682. !R->isObjCObjectPointerType())
  8683. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  8684. }
  8685. // C++1z [dcl.fct]p6:
  8686. // [...] whether the function has a non-throwing exception-specification
  8687. // [is] part of the function type
  8688. //
  8689. // This results in an ABI break between C++14 and C++17 for functions whose
  8690. // declared type includes an exception-specification in a parameter or
  8691. // return type. (Exception specifications on the function itself are OK in
  8692. // most cases, and exception specifications are not permitted in most other
  8693. // contexts where they could make it into a mangling.)
  8694. if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
  8695. auto HasNoexcept = [&](QualType T) -> bool {
  8696. // Strip off declarator chunks that could be between us and a function
  8697. // type. We don't need to look far, exception specifications are very
  8698. // restricted prior to C++17.
  8699. if (auto *RT = T->getAs<ReferenceType>())
  8700. T = RT->getPointeeType();
  8701. else if (T->isAnyPointerType())
  8702. T = T->getPointeeType();
  8703. else if (auto *MPT = T->getAs<MemberPointerType>())
  8704. T = MPT->getPointeeType();
  8705. if (auto *FPT = T->getAs<FunctionProtoType>())
  8706. if (FPT->isNothrow(Context))
  8707. return true;
  8708. return false;
  8709. };
  8710. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  8711. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  8712. for (QualType T : FPT->param_types())
  8713. AnyNoexcept |= HasNoexcept(T);
  8714. if (AnyNoexcept)
  8715. Diag(NewFD->getLocation(),
  8716. diag::warn_cxx17_compat_exception_spec_in_signature)
  8717. << NewFD;
  8718. }
  8719. if (!Redeclaration && LangOpts.CUDA)
  8720. checkCUDATargetOverload(NewFD, Previous);
  8721. }
  8722. return Redeclaration;
  8723. }
  8724. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  8725. // C++11 [basic.start.main]p3:
  8726. // A program that [...] declares main to be inline, static or
  8727. // constexpr is ill-formed.
  8728. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  8729. // appear in a declaration of main.
  8730. // static main is not an error under C99, but we should warn about it.
  8731. // We accept _Noreturn main as an extension.
  8732. if (FD->getStorageClass() == SC_Static)
  8733. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  8734. ? diag::err_static_main : diag::warn_static_main)
  8735. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  8736. if (FD->isInlineSpecified())
  8737. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  8738. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  8739. if (DS.isNoreturnSpecified()) {
  8740. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  8741. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  8742. Diag(NoreturnLoc, diag::ext_noreturn_main);
  8743. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  8744. << FixItHint::CreateRemoval(NoreturnRange);
  8745. }
  8746. if (FD->isConstexpr()) {
  8747. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  8748. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  8749. FD->setConstexpr(false);
  8750. }
  8751. if (getLangOpts().OpenCL) {
  8752. Diag(FD->getLocation(), diag::err_opencl_no_main)
  8753. << FD->hasAttr<OpenCLKernelAttr>();
  8754. FD->setInvalidDecl();
  8755. return;
  8756. }
  8757. QualType T = FD->getType();
  8758. assert(T->isFunctionType() && "function decl is not of function type");
  8759. const FunctionType* FT = T->castAs<FunctionType>();
  8760. // Set default calling convention for main()
  8761. if (FT->getCallConv() != CC_C) {
  8762. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
  8763. FD->setType(QualType(FT, 0));
  8764. T = Context.getCanonicalType(FD->getType());
  8765. }
  8766. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  8767. // In C with GNU extensions we allow main() to have non-integer return
  8768. // type, but we should warn about the extension, and we disable the
  8769. // implicit-return-zero rule.
  8770. // GCC in C mode accepts qualified 'int'.
  8771. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  8772. FD->setHasImplicitReturnZero(true);
  8773. else {
  8774. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  8775. SourceRange RTRange = FD->getReturnTypeSourceRange();
  8776. if (RTRange.isValid())
  8777. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  8778. << FixItHint::CreateReplacement(RTRange, "int");
  8779. }
  8780. } else {
  8781. // In C and C++, main magically returns 0 if you fall off the end;
  8782. // set the flag which tells us that.
  8783. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  8784. // All the standards say that main() should return 'int'.
  8785. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  8786. FD->setHasImplicitReturnZero(true);
  8787. else {
  8788. // Otherwise, this is just a flat-out error.
  8789. SourceRange RTRange = FD->getReturnTypeSourceRange();
  8790. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  8791. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  8792. : FixItHint());
  8793. FD->setInvalidDecl(true);
  8794. }
  8795. }
  8796. // Treat protoless main() as nullary.
  8797. if (isa<FunctionNoProtoType>(FT)) return;
  8798. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  8799. unsigned nparams = FTP->getNumParams();
  8800. assert(FD->getNumParams() == nparams);
  8801. bool HasExtraParameters = (nparams > 3);
  8802. if (FTP->isVariadic()) {
  8803. Diag(FD->getLocation(), diag::ext_variadic_main);
  8804. // FIXME: if we had information about the location of the ellipsis, we
  8805. // could add a FixIt hint to remove it as a parameter.
  8806. }
  8807. // Darwin passes an undocumented fourth argument of type char**. If
  8808. // other platforms start sprouting these, the logic below will start
  8809. // getting shifty.
  8810. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  8811. HasExtraParameters = false;
  8812. if (HasExtraParameters) {
  8813. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  8814. FD->setInvalidDecl(true);
  8815. nparams = 3;
  8816. }
  8817. // FIXME: a lot of the following diagnostics would be improved
  8818. // if we had some location information about types.
  8819. QualType CharPP =
  8820. Context.getPointerType(Context.getPointerType(Context.CharTy));
  8821. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  8822. for (unsigned i = 0; i < nparams; ++i) {
  8823. QualType AT = FTP->getParamType(i);
  8824. bool mismatch = true;
  8825. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  8826. mismatch = false;
  8827. else if (Expected[i] == CharPP) {
  8828. // As an extension, the following forms are okay:
  8829. // char const **
  8830. // char const * const *
  8831. // char * const *
  8832. QualifierCollector qs;
  8833. const PointerType* PT;
  8834. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  8835. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  8836. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  8837. Context.CharTy)) {
  8838. qs.removeConst();
  8839. mismatch = !qs.empty();
  8840. }
  8841. }
  8842. if (mismatch) {
  8843. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  8844. // TODO: suggest replacing given type with expected type
  8845. FD->setInvalidDecl(true);
  8846. }
  8847. }
  8848. if (nparams == 1 && !FD->isInvalidDecl()) {
  8849. Diag(FD->getLocation(), diag::warn_main_one_arg);
  8850. }
  8851. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  8852. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  8853. FD->setInvalidDecl();
  8854. }
  8855. }
  8856. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  8857. QualType T = FD->getType();
  8858. assert(T->isFunctionType() && "function decl is not of function type");
  8859. const FunctionType *FT = T->castAs<FunctionType>();
  8860. // Set an implicit return of 'zero' if the function can return some integral,
  8861. // enumeration, pointer or nullptr type.
  8862. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  8863. FT->getReturnType()->isAnyPointerType() ||
  8864. FT->getReturnType()->isNullPtrType())
  8865. // DllMain is exempt because a return value of zero means it failed.
  8866. if (FD->getName() != "DllMain")
  8867. FD->setHasImplicitReturnZero(true);
  8868. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  8869. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  8870. FD->setInvalidDecl();
  8871. }
  8872. }
  8873. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  8874. // FIXME: Need strict checking. In C89, we need to check for
  8875. // any assignment, increment, decrement, function-calls, or
  8876. // commas outside of a sizeof. In C99, it's the same list,
  8877. // except that the aforementioned are allowed in unevaluated
  8878. // expressions. Everything else falls under the
  8879. // "may accept other forms of constant expressions" exception.
  8880. // (We never end up here for C++, so the constant expression
  8881. // rules there don't matter.)
  8882. const Expr *Culprit;
  8883. if (Init->isConstantInitializer(Context, false, &Culprit))
  8884. return false;
  8885. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  8886. << Culprit->getSourceRange();
  8887. return true;
  8888. }
  8889. namespace {
  8890. // Visits an initialization expression to see if OrigDecl is evaluated in
  8891. // its own initialization and throws a warning if it does.
  8892. class SelfReferenceChecker
  8893. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  8894. Sema &S;
  8895. Decl *OrigDecl;
  8896. bool isRecordType;
  8897. bool isPODType;
  8898. bool isReferenceType;
  8899. bool isInitList;
  8900. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  8901. public:
  8902. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  8903. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  8904. S(S), OrigDecl(OrigDecl) {
  8905. isPODType = false;
  8906. isRecordType = false;
  8907. isReferenceType = false;
  8908. isInitList = false;
  8909. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  8910. isPODType = VD->getType().isPODType(S.Context);
  8911. isRecordType = VD->getType()->isRecordType();
  8912. isReferenceType = VD->getType()->isReferenceType();
  8913. }
  8914. }
  8915. // For most expressions, just call the visitor. For initializer lists,
  8916. // track the index of the field being initialized since fields are
  8917. // initialized in order allowing use of previously initialized fields.
  8918. void CheckExpr(Expr *E) {
  8919. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  8920. if (!InitList) {
  8921. Visit(E);
  8922. return;
  8923. }
  8924. // Track and increment the index here.
  8925. isInitList = true;
  8926. InitFieldIndex.push_back(0);
  8927. for (auto Child : InitList->children()) {
  8928. CheckExpr(cast<Expr>(Child));
  8929. ++InitFieldIndex.back();
  8930. }
  8931. InitFieldIndex.pop_back();
  8932. }
  8933. // Returns true if MemberExpr is checked and no further checking is needed.
  8934. // Returns false if additional checking is required.
  8935. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  8936. llvm::SmallVector<FieldDecl*, 4> Fields;
  8937. Expr *Base = E;
  8938. bool ReferenceField = false;
  8939. // Get the field memebers used.
  8940. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  8941. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  8942. if (!FD)
  8943. return false;
  8944. Fields.push_back(FD);
  8945. if (FD->getType()->isReferenceType())
  8946. ReferenceField = true;
  8947. Base = ME->getBase()->IgnoreParenImpCasts();
  8948. }
  8949. // Keep checking only if the base Decl is the same.
  8950. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  8951. if (!DRE || DRE->getDecl() != OrigDecl)
  8952. return false;
  8953. // A reference field can be bound to an unininitialized field.
  8954. if (CheckReference && !ReferenceField)
  8955. return true;
  8956. // Convert FieldDecls to their index number.
  8957. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  8958. for (const FieldDecl *I : llvm::reverse(Fields))
  8959. UsedFieldIndex.push_back(I->getFieldIndex());
  8960. // See if a warning is needed by checking the first difference in index
  8961. // numbers. If field being used has index less than the field being
  8962. // initialized, then the use is safe.
  8963. for (auto UsedIter = UsedFieldIndex.begin(),
  8964. UsedEnd = UsedFieldIndex.end(),
  8965. OrigIter = InitFieldIndex.begin(),
  8966. OrigEnd = InitFieldIndex.end();
  8967. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  8968. if (*UsedIter < *OrigIter)
  8969. return true;
  8970. if (*UsedIter > *OrigIter)
  8971. break;
  8972. }
  8973. // TODO: Add a different warning which will print the field names.
  8974. HandleDeclRefExpr(DRE);
  8975. return true;
  8976. }
  8977. // For most expressions, the cast is directly above the DeclRefExpr.
  8978. // For conditional operators, the cast can be outside the conditional
  8979. // operator if both expressions are DeclRefExpr's.
  8980. void HandleValue(Expr *E) {
  8981. E = E->IgnoreParens();
  8982. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  8983. HandleDeclRefExpr(DRE);
  8984. return;
  8985. }
  8986. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  8987. Visit(CO->getCond());
  8988. HandleValue(CO->getTrueExpr());
  8989. HandleValue(CO->getFalseExpr());
  8990. return;
  8991. }
  8992. if (BinaryConditionalOperator *BCO =
  8993. dyn_cast<BinaryConditionalOperator>(E)) {
  8994. Visit(BCO->getCond());
  8995. HandleValue(BCO->getFalseExpr());
  8996. return;
  8997. }
  8998. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  8999. HandleValue(OVE->getSourceExpr());
  9000. return;
  9001. }
  9002. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9003. if (BO->getOpcode() == BO_Comma) {
  9004. Visit(BO->getLHS());
  9005. HandleValue(BO->getRHS());
  9006. return;
  9007. }
  9008. }
  9009. if (isa<MemberExpr>(E)) {
  9010. if (isInitList) {
  9011. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  9012. false /*CheckReference*/))
  9013. return;
  9014. }
  9015. Expr *Base = E->IgnoreParenImpCasts();
  9016. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9017. // Check for static member variables and don't warn on them.
  9018. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9019. return;
  9020. Base = ME->getBase()->IgnoreParenImpCasts();
  9021. }
  9022. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  9023. HandleDeclRefExpr(DRE);
  9024. return;
  9025. }
  9026. Visit(E);
  9027. }
  9028. // Reference types not handled in HandleValue are handled here since all
  9029. // uses of references are bad, not just r-value uses.
  9030. void VisitDeclRefExpr(DeclRefExpr *E) {
  9031. if (isReferenceType)
  9032. HandleDeclRefExpr(E);
  9033. }
  9034. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  9035. if (E->getCastKind() == CK_LValueToRValue) {
  9036. HandleValue(E->getSubExpr());
  9037. return;
  9038. }
  9039. Inherited::VisitImplicitCastExpr(E);
  9040. }
  9041. void VisitMemberExpr(MemberExpr *E) {
  9042. if (isInitList) {
  9043. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  9044. return;
  9045. }
  9046. // Don't warn on arrays since they can be treated as pointers.
  9047. if (E->getType()->canDecayToPointerType()) return;
  9048. // Warn when a non-static method call is followed by non-static member
  9049. // field accesses, which is followed by a DeclRefExpr.
  9050. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  9051. bool Warn = (MD && !MD->isStatic());
  9052. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  9053. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9054. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9055. Warn = false;
  9056. Base = ME->getBase()->IgnoreParenImpCasts();
  9057. }
  9058. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  9059. if (Warn)
  9060. HandleDeclRefExpr(DRE);
  9061. return;
  9062. }
  9063. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  9064. // Visit that expression.
  9065. Visit(Base);
  9066. }
  9067. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  9068. Expr *Callee = E->getCallee();
  9069. if (isa<UnresolvedLookupExpr>(Callee))
  9070. return Inherited::VisitCXXOperatorCallExpr(E);
  9071. Visit(Callee);
  9072. for (auto Arg: E->arguments())
  9073. HandleValue(Arg->IgnoreParenImpCasts());
  9074. }
  9075. void VisitUnaryOperator(UnaryOperator *E) {
  9076. // For POD record types, addresses of its own members are well-defined.
  9077. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  9078. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  9079. if (!isPODType)
  9080. HandleValue(E->getSubExpr());
  9081. return;
  9082. }
  9083. if (E->isIncrementDecrementOp()) {
  9084. HandleValue(E->getSubExpr());
  9085. return;
  9086. }
  9087. Inherited::VisitUnaryOperator(E);
  9088. }
  9089. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  9090. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  9091. if (E->getConstructor()->isCopyConstructor()) {
  9092. Expr *ArgExpr = E->getArg(0);
  9093. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  9094. if (ILE->getNumInits() == 1)
  9095. ArgExpr = ILE->getInit(0);
  9096. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  9097. if (ICE->getCastKind() == CK_NoOp)
  9098. ArgExpr = ICE->getSubExpr();
  9099. HandleValue(ArgExpr);
  9100. return;
  9101. }
  9102. Inherited::VisitCXXConstructExpr(E);
  9103. }
  9104. void VisitCallExpr(CallExpr *E) {
  9105. // Treat std::move as a use.
  9106. if (E->isCallToStdMove()) {
  9107. HandleValue(E->getArg(0));
  9108. return;
  9109. }
  9110. Inherited::VisitCallExpr(E);
  9111. }
  9112. void VisitBinaryOperator(BinaryOperator *E) {
  9113. if (E->isCompoundAssignmentOp()) {
  9114. HandleValue(E->getLHS());
  9115. Visit(E->getRHS());
  9116. return;
  9117. }
  9118. Inherited::VisitBinaryOperator(E);
  9119. }
  9120. // A custom visitor for BinaryConditionalOperator is needed because the
  9121. // regular visitor would check the condition and true expression separately
  9122. // but both point to the same place giving duplicate diagnostics.
  9123. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  9124. Visit(E->getCond());
  9125. Visit(E->getFalseExpr());
  9126. }
  9127. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  9128. Decl* ReferenceDecl = DRE->getDecl();
  9129. if (OrigDecl != ReferenceDecl) return;
  9130. unsigned diag;
  9131. if (isReferenceType) {
  9132. diag = diag::warn_uninit_self_reference_in_reference_init;
  9133. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  9134. diag = diag::warn_static_self_reference_in_init;
  9135. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  9136. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  9137. DRE->getDecl()->getType()->isRecordType()) {
  9138. diag = diag::warn_uninit_self_reference_in_init;
  9139. } else {
  9140. // Local variables will be handled by the CFG analysis.
  9141. return;
  9142. }
  9143. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  9144. S.PDiag(diag)
  9145. << DRE->getDecl()
  9146. << OrigDecl->getLocation()
  9147. << DRE->getSourceRange());
  9148. }
  9149. };
  9150. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  9151. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  9152. bool DirectInit) {
  9153. // Parameters arguments are occassionially constructed with itself,
  9154. // for instance, in recursive functions. Skip them.
  9155. if (isa<ParmVarDecl>(OrigDecl))
  9156. return;
  9157. E = E->IgnoreParens();
  9158. // Skip checking T a = a where T is not a record or reference type.
  9159. // Doing so is a way to silence uninitialized warnings.
  9160. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  9161. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  9162. if (ICE->getCastKind() == CK_LValueToRValue)
  9163. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  9164. if (DRE->getDecl() == OrigDecl)
  9165. return;
  9166. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  9167. }
  9168. } // end anonymous namespace
  9169. namespace {
  9170. // Simple wrapper to add the name of a variable or (if no variable is
  9171. // available) a DeclarationName into a diagnostic.
  9172. struct VarDeclOrName {
  9173. VarDecl *VDecl;
  9174. DeclarationName Name;
  9175. friend const Sema::SemaDiagnosticBuilder &
  9176. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  9177. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  9178. }
  9179. };
  9180. } // end anonymous namespace
  9181. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  9182. DeclarationName Name, QualType Type,
  9183. TypeSourceInfo *TSI,
  9184. SourceRange Range, bool DirectInit,
  9185. Expr *Init) {
  9186. bool IsInitCapture = !VDecl;
  9187. assert((!VDecl || !VDecl->isInitCapture()) &&
  9188. "init captures are expected to be deduced prior to initialization");
  9189. VarDeclOrName VN{VDecl, Name};
  9190. DeducedType *Deduced = Type->getContainedDeducedType();
  9191. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  9192. // C++11 [dcl.spec.auto]p3
  9193. if (!Init) {
  9194. assert(VDecl && "no init for init capture deduction?");
  9195. // Except for class argument deduction, and then for an initializing
  9196. // declaration only, i.e. no static at class scope or extern.
  9197. if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
  9198. VDecl->hasExternalStorage() ||
  9199. VDecl->isStaticDataMember()) {
  9200. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  9201. << VDecl->getDeclName() << Type;
  9202. return QualType();
  9203. }
  9204. }
  9205. ArrayRef<Expr*> DeduceInits;
  9206. if (Init)
  9207. DeduceInits = Init;
  9208. if (DirectInit) {
  9209. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  9210. DeduceInits = PL->exprs();
  9211. }
  9212. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  9213. assert(VDecl && "non-auto type for init capture deduction?");
  9214. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9215. InitializationKind Kind = InitializationKind::CreateForInit(
  9216. VDecl->getLocation(), DirectInit, Init);
  9217. // FIXME: Initialization should not be taking a mutable list of inits.
  9218. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  9219. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  9220. InitsCopy);
  9221. }
  9222. if (DirectInit) {
  9223. if (auto *IL = dyn_cast<InitListExpr>(Init))
  9224. DeduceInits = IL->inits();
  9225. }
  9226. // Deduction only works if we have exactly one source expression.
  9227. if (DeduceInits.empty()) {
  9228. // It isn't possible to write this directly, but it is possible to
  9229. // end up in this situation with "auto x(some_pack...);"
  9230. Diag(Init->getLocStart(), IsInitCapture
  9231. ? diag::err_init_capture_no_expression
  9232. : diag::err_auto_var_init_no_expression)
  9233. << VN << Type << Range;
  9234. return QualType();
  9235. }
  9236. if (DeduceInits.size() > 1) {
  9237. Diag(DeduceInits[1]->getLocStart(),
  9238. IsInitCapture ? diag::err_init_capture_multiple_expressions
  9239. : diag::err_auto_var_init_multiple_expressions)
  9240. << VN << Type << Range;
  9241. return QualType();
  9242. }
  9243. Expr *DeduceInit = DeduceInits[0];
  9244. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  9245. Diag(Init->getLocStart(), IsInitCapture
  9246. ? diag::err_init_capture_paren_braces
  9247. : diag::err_auto_var_init_paren_braces)
  9248. << isa<InitListExpr>(Init) << VN << Type << Range;
  9249. return QualType();
  9250. }
  9251. // Expressions default to 'id' when we're in a debugger.
  9252. bool DefaultedAnyToId = false;
  9253. if (getLangOpts().DebuggerCastResultToId &&
  9254. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  9255. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9256. if (Result.isInvalid()) {
  9257. return QualType();
  9258. }
  9259. Init = Result.get();
  9260. DefaultedAnyToId = true;
  9261. }
  9262. // C++ [dcl.decomp]p1:
  9263. // If the assignment-expression [...] has array type A and no ref-qualifier
  9264. // is present, e has type cv A
  9265. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  9266. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  9267. DeduceInit->getType()->isConstantArrayType())
  9268. return Context.getQualifiedType(DeduceInit->getType(),
  9269. Type.getQualifiers());
  9270. QualType DeducedType;
  9271. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  9272. if (!IsInitCapture)
  9273. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  9274. else if (isa<InitListExpr>(Init))
  9275. Diag(Range.getBegin(),
  9276. diag::err_init_capture_deduction_failure_from_init_list)
  9277. << VN
  9278. << (DeduceInit->getType().isNull() ? TSI->getType()
  9279. : DeduceInit->getType())
  9280. << DeduceInit->getSourceRange();
  9281. else
  9282. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  9283. << VN << TSI->getType()
  9284. << (DeduceInit->getType().isNull() ? TSI->getType()
  9285. : DeduceInit->getType())
  9286. << DeduceInit->getSourceRange();
  9287. }
  9288. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  9289. // 'id' instead of a specific object type prevents most of our usual
  9290. // checks.
  9291. // We only want to warn outside of template instantiations, though:
  9292. // inside a template, the 'id' could have come from a parameter.
  9293. if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
  9294. !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  9295. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  9296. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  9297. }
  9298. return DeducedType;
  9299. }
  9300. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  9301. Expr *Init) {
  9302. QualType DeducedType = deduceVarTypeFromInitializer(
  9303. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  9304. VDecl->getSourceRange(), DirectInit, Init);
  9305. if (DeducedType.isNull()) {
  9306. VDecl->setInvalidDecl();
  9307. return true;
  9308. }
  9309. VDecl->setType(DeducedType);
  9310. assert(VDecl->isLinkageValid());
  9311. // In ARC, infer lifetime.
  9312. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  9313. VDecl->setInvalidDecl();
  9314. // If this is a redeclaration, check that the type we just deduced matches
  9315. // the previously declared type.
  9316. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  9317. // We never need to merge the type, because we cannot form an incomplete
  9318. // array of auto, nor deduce such a type.
  9319. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  9320. }
  9321. // Check the deduced type is valid for a variable declaration.
  9322. CheckVariableDeclarationType(VDecl);
  9323. return VDecl->isInvalidDecl();
  9324. }
  9325. /// AddInitializerToDecl - Adds the initializer Init to the
  9326. /// declaration dcl. If DirectInit is true, this is C++ direct
  9327. /// initialization rather than copy initialization.
  9328. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  9329. // If there is no declaration, there was an error parsing it. Just ignore
  9330. // the initializer.
  9331. if (!RealDecl || RealDecl->isInvalidDecl()) {
  9332. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  9333. return;
  9334. }
  9335. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  9336. // Pure-specifiers are handled in ActOnPureSpecifier.
  9337. Diag(Method->getLocation(), diag::err_member_function_initialization)
  9338. << Method->getDeclName() << Init->getSourceRange();
  9339. Method->setInvalidDecl();
  9340. return;
  9341. }
  9342. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  9343. if (!VDecl) {
  9344. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  9345. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  9346. RealDecl->setInvalidDecl();
  9347. return;
  9348. }
  9349. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  9350. if (VDecl->getType()->isUndeducedType()) {
  9351. // Attempt typo correction early so that the type of the init expression can
  9352. // be deduced based on the chosen correction if the original init contains a
  9353. // TypoExpr.
  9354. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  9355. if (!Res.isUsable()) {
  9356. RealDecl->setInvalidDecl();
  9357. return;
  9358. }
  9359. Init = Res.get();
  9360. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  9361. return;
  9362. }
  9363. // dllimport cannot be used on variable definitions.
  9364. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  9365. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  9366. VDecl->setInvalidDecl();
  9367. return;
  9368. }
  9369. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  9370. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  9371. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  9372. VDecl->setInvalidDecl();
  9373. return;
  9374. }
  9375. if (!VDecl->getType()->isDependentType()) {
  9376. // A definition must end up with a complete type, which means it must be
  9377. // complete with the restriction that an array type might be completed by
  9378. // the initializer; note that later code assumes this restriction.
  9379. QualType BaseDeclType = VDecl->getType();
  9380. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  9381. BaseDeclType = Array->getElementType();
  9382. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  9383. diag::err_typecheck_decl_incomplete_type)) {
  9384. RealDecl->setInvalidDecl();
  9385. return;
  9386. }
  9387. // The variable can not have an abstract class type.
  9388. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  9389. diag::err_abstract_type_in_decl,
  9390. AbstractVariableType))
  9391. VDecl->setInvalidDecl();
  9392. }
  9393. // If adding the initializer will turn this declaration into a definition,
  9394. // and we already have a definition for this variable, diagnose or otherwise
  9395. // handle the situation.
  9396. VarDecl *Def;
  9397. if ((Def = VDecl->getDefinition()) && Def != VDecl &&
  9398. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  9399. !VDecl->isThisDeclarationADemotedDefinition() &&
  9400. checkVarDeclRedefinition(Def, VDecl))
  9401. return;
  9402. if (getLangOpts().CPlusPlus) {
  9403. // C++ [class.static.data]p4
  9404. // If a static data member is of const integral or const
  9405. // enumeration type, its declaration in the class definition can
  9406. // specify a constant-initializer which shall be an integral
  9407. // constant expression (5.19). In that case, the member can appear
  9408. // in integral constant expressions. The member shall still be
  9409. // defined in a namespace scope if it is used in the program and the
  9410. // namespace scope definition shall not contain an initializer.
  9411. //
  9412. // We already performed a redefinition check above, but for static
  9413. // data members we also need to check whether there was an in-class
  9414. // declaration with an initializer.
  9415. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  9416. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  9417. << VDecl->getDeclName();
  9418. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  9419. diag::note_previous_initializer)
  9420. << 0;
  9421. return;
  9422. }
  9423. if (VDecl->hasLocalStorage())
  9424. setFunctionHasBranchProtectedScope();
  9425. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  9426. VDecl->setInvalidDecl();
  9427. return;
  9428. }
  9429. }
  9430. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  9431. // a kernel function cannot be initialized."
  9432. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  9433. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  9434. VDecl->setInvalidDecl();
  9435. return;
  9436. }
  9437. // Get the decls type and save a reference for later, since
  9438. // CheckInitializerTypes may change it.
  9439. QualType DclT = VDecl->getType(), SavT = DclT;
  9440. // Expressions default to 'id' when we're in a debugger
  9441. // and we are assigning it to a variable of Objective-C pointer type.
  9442. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  9443. Init->getType() == Context.UnknownAnyTy) {
  9444. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9445. if (Result.isInvalid()) {
  9446. VDecl->setInvalidDecl();
  9447. return;
  9448. }
  9449. Init = Result.get();
  9450. }
  9451. // Perform the initialization.
  9452. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  9453. if (!VDecl->isInvalidDecl()) {
  9454. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9455. InitializationKind Kind = InitializationKind::CreateForInit(
  9456. VDecl->getLocation(), DirectInit, Init);
  9457. MultiExprArg Args = Init;
  9458. if (CXXDirectInit)
  9459. Args = MultiExprArg(CXXDirectInit->getExprs(),
  9460. CXXDirectInit->getNumExprs());
  9461. // Try to correct any TypoExprs in the initialization arguments.
  9462. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  9463. ExprResult Res = CorrectDelayedTyposInExpr(
  9464. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  9465. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  9466. return Init.Failed() ? ExprError() : E;
  9467. });
  9468. if (Res.isInvalid()) {
  9469. VDecl->setInvalidDecl();
  9470. } else if (Res.get() != Args[Idx]) {
  9471. Args[Idx] = Res.get();
  9472. }
  9473. }
  9474. if (VDecl->isInvalidDecl())
  9475. return;
  9476. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  9477. /*TopLevelOfInitList=*/false,
  9478. /*TreatUnavailableAsInvalid=*/false);
  9479. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  9480. if (Result.isInvalid()) {
  9481. VDecl->setInvalidDecl();
  9482. return;
  9483. }
  9484. Init = Result.getAs<Expr>();
  9485. }
  9486. // Check for self-references within variable initializers.
  9487. // Variables declared within a function/method body (except for references)
  9488. // are handled by a dataflow analysis.
  9489. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  9490. VDecl->getType()->isReferenceType()) {
  9491. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  9492. }
  9493. // If the type changed, it means we had an incomplete type that was
  9494. // completed by the initializer. For example:
  9495. // int ary[] = { 1, 3, 5 };
  9496. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  9497. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  9498. VDecl->setType(DclT);
  9499. if (!VDecl->isInvalidDecl()) {
  9500. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  9501. if (VDecl->hasAttr<BlocksAttr>())
  9502. checkRetainCycles(VDecl, Init);
  9503. // It is safe to assign a weak reference into a strong variable.
  9504. // Although this code can still have problems:
  9505. // id x = self.weakProp;
  9506. // id y = self.weakProp;
  9507. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  9508. // paths through the function. This should be revisited if
  9509. // -Wrepeated-use-of-weak is made flow-sensitive.
  9510. if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
  9511. VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
  9512. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  9513. Init->getLocStart()))
  9514. getCurFunction()->markSafeWeakUse(Init);
  9515. }
  9516. // The initialization is usually a full-expression.
  9517. //
  9518. // FIXME: If this is a braced initialization of an aggregate, it is not
  9519. // an expression, and each individual field initializer is a separate
  9520. // full-expression. For instance, in:
  9521. //
  9522. // struct Temp { ~Temp(); };
  9523. // struct S { S(Temp); };
  9524. // struct T { S a, b; } t = { Temp(), Temp() }
  9525. //
  9526. // we should destroy the first Temp before constructing the second.
  9527. ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
  9528. false,
  9529. VDecl->isConstexpr());
  9530. if (Result.isInvalid()) {
  9531. VDecl->setInvalidDecl();
  9532. return;
  9533. }
  9534. Init = Result.get();
  9535. // Attach the initializer to the decl.
  9536. VDecl->setInit(Init);
  9537. if (VDecl->isLocalVarDecl()) {
  9538. // Don't check the initializer if the declaration is malformed.
  9539. if (VDecl->isInvalidDecl()) {
  9540. // do nothing
  9541. // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
  9542. // This is true even in OpenCL C++.
  9543. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
  9544. CheckForConstantInitializer(Init, DclT);
  9545. // Otherwise, C++ does not restrict the initializer.
  9546. } else if (getLangOpts().CPlusPlus) {
  9547. // do nothing
  9548. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  9549. // static storage duration shall be constant expressions or string literals.
  9550. } else if (VDecl->getStorageClass() == SC_Static) {
  9551. CheckForConstantInitializer(Init, DclT);
  9552. // C89 is stricter than C99 for aggregate initializers.
  9553. // C89 6.5.7p3: All the expressions [...] in an initializer list
  9554. // for an object that has aggregate or union type shall be
  9555. // constant expressions.
  9556. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  9557. isa<InitListExpr>(Init)) {
  9558. const Expr *Culprit;
  9559. if (!Init->isConstantInitializer(Context, false, &Culprit)) {
  9560. Diag(Culprit->getExprLoc(),
  9561. diag::ext_aggregate_init_not_constant)
  9562. << Culprit->getSourceRange();
  9563. }
  9564. }
  9565. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  9566. VDecl->getLexicalDeclContext()->isRecord()) {
  9567. // This is an in-class initialization for a static data member, e.g.,
  9568. //
  9569. // struct S {
  9570. // static const int value = 17;
  9571. // };
  9572. // C++ [class.mem]p4:
  9573. // A member-declarator can contain a constant-initializer only
  9574. // if it declares a static member (9.4) of const integral or
  9575. // const enumeration type, see 9.4.2.
  9576. //
  9577. // C++11 [class.static.data]p3:
  9578. // If a non-volatile non-inline const static data member is of integral
  9579. // or enumeration type, its declaration in the class definition can
  9580. // specify a brace-or-equal-initializer in which every initializer-clause
  9581. // that is an assignment-expression is a constant expression. A static
  9582. // data member of literal type can be declared in the class definition
  9583. // with the constexpr specifier; if so, its declaration shall specify a
  9584. // brace-or-equal-initializer in which every initializer-clause that is
  9585. // an assignment-expression is a constant expression.
  9586. // Do nothing on dependent types.
  9587. if (DclT->isDependentType()) {
  9588. // Allow any 'static constexpr' members, whether or not they are of literal
  9589. // type. We separately check that every constexpr variable is of literal
  9590. // type.
  9591. } else if (VDecl->isConstexpr()) {
  9592. // Require constness.
  9593. } else if (!DclT.isConstQualified()) {
  9594. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  9595. << Init->getSourceRange();
  9596. VDecl->setInvalidDecl();
  9597. // We allow integer constant expressions in all cases.
  9598. } else if (DclT->isIntegralOrEnumerationType()) {
  9599. // Check whether the expression is a constant expression.
  9600. SourceLocation Loc;
  9601. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  9602. // In C++11, a non-constexpr const static data member with an
  9603. // in-class initializer cannot be volatile.
  9604. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  9605. else if (Init->isValueDependent())
  9606. ; // Nothing to check.
  9607. else if (Init->isIntegerConstantExpr(Context, &Loc))
  9608. ; // Ok, it's an ICE!
  9609. else if (Init->isEvaluatable(Context)) {
  9610. // If we can constant fold the initializer through heroics, accept it,
  9611. // but report this as a use of an extension for -pedantic.
  9612. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  9613. << Init->getSourceRange();
  9614. } else {
  9615. // Otherwise, this is some crazy unknown case. Report the issue at the
  9616. // location provided by the isIntegerConstantExpr failed check.
  9617. Diag(Loc, diag::err_in_class_initializer_non_constant)
  9618. << Init->getSourceRange();
  9619. VDecl->setInvalidDecl();
  9620. }
  9621. // We allow foldable floating-point constants as an extension.
  9622. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  9623. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  9624. // it anyway and provide a fixit to add the 'constexpr'.
  9625. if (getLangOpts().CPlusPlus11) {
  9626. Diag(VDecl->getLocation(),
  9627. diag::ext_in_class_initializer_float_type_cxx11)
  9628. << DclT << Init->getSourceRange();
  9629. Diag(VDecl->getLocStart(),
  9630. diag::note_in_class_initializer_float_type_cxx11)
  9631. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  9632. } else {
  9633. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  9634. << DclT << Init->getSourceRange();
  9635. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  9636. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  9637. << Init->getSourceRange();
  9638. VDecl->setInvalidDecl();
  9639. }
  9640. }
  9641. // Suggest adding 'constexpr' in C++11 for literal types.
  9642. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  9643. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  9644. << DclT << Init->getSourceRange()
  9645. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  9646. VDecl->setConstexpr(true);
  9647. } else {
  9648. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  9649. << DclT << Init->getSourceRange();
  9650. VDecl->setInvalidDecl();
  9651. }
  9652. } else if (VDecl->isFileVarDecl()) {
  9653. // In C, extern is typically used to avoid tentative definitions when
  9654. // declaring variables in headers, but adding an intializer makes it a
  9655. // definition. This is somewhat confusing, so GCC and Clang both warn on it.
  9656. // In C++, extern is often used to give implictly static const variables
  9657. // external linkage, so don't warn in that case. If selectany is present,
  9658. // this might be header code intended for C and C++ inclusion, so apply the
  9659. // C++ rules.
  9660. if (VDecl->getStorageClass() == SC_Extern &&
  9661. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  9662. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  9663. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  9664. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  9665. Diag(VDecl->getLocation(), diag::warn_extern_init);
  9666. // C99 6.7.8p4. All file scoped initializers need to be constant.
  9667. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  9668. CheckForConstantInitializer(Init, DclT);
  9669. }
  9670. // We will represent direct-initialization similarly to copy-initialization:
  9671. // int x(1); -as-> int x = 1;
  9672. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  9673. //
  9674. // Clients that want to distinguish between the two forms, can check for
  9675. // direct initializer using VarDecl::getInitStyle().
  9676. // A major benefit is that clients that don't particularly care about which
  9677. // exactly form was it (like the CodeGen) can handle both cases without
  9678. // special case code.
  9679. // C++ 8.5p11:
  9680. // The form of initialization (using parentheses or '=') is generally
  9681. // insignificant, but does matter when the entity being initialized has a
  9682. // class type.
  9683. if (CXXDirectInit) {
  9684. assert(DirectInit && "Call-style initializer must be direct init.");
  9685. VDecl->setInitStyle(VarDecl::CallInit);
  9686. } else if (DirectInit) {
  9687. // This must be list-initialization. No other way is direct-initialization.
  9688. VDecl->setInitStyle(VarDecl::ListInit);
  9689. }
  9690. CheckCompleteVariableDeclaration(VDecl);
  9691. }
  9692. /// ActOnInitializerError - Given that there was an error parsing an
  9693. /// initializer for the given declaration, try to return to some form
  9694. /// of sanity.
  9695. void Sema::ActOnInitializerError(Decl *D) {
  9696. // Our main concern here is re-establishing invariants like "a
  9697. // variable's type is either dependent or complete".
  9698. if (!D || D->isInvalidDecl()) return;
  9699. VarDecl *VD = dyn_cast<VarDecl>(D);
  9700. if (!VD) return;
  9701. // Bindings are not usable if we can't make sense of the initializer.
  9702. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  9703. for (auto *BD : DD->bindings())
  9704. BD->setInvalidDecl();
  9705. // Auto types are meaningless if we can't make sense of the initializer.
  9706. if (ParsingInitForAutoVars.count(D)) {
  9707. D->setInvalidDecl();
  9708. return;
  9709. }
  9710. QualType Ty = VD->getType();
  9711. if (Ty->isDependentType()) return;
  9712. // Require a complete type.
  9713. if (RequireCompleteType(VD->getLocation(),
  9714. Context.getBaseElementType(Ty),
  9715. diag::err_typecheck_decl_incomplete_type)) {
  9716. VD->setInvalidDecl();
  9717. return;
  9718. }
  9719. // Require a non-abstract type.
  9720. if (RequireNonAbstractType(VD->getLocation(), Ty,
  9721. diag::err_abstract_type_in_decl,
  9722. AbstractVariableType)) {
  9723. VD->setInvalidDecl();
  9724. return;
  9725. }
  9726. // Don't bother complaining about constructors or destructors,
  9727. // though.
  9728. }
  9729. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  9730. // If there is no declaration, there was an error parsing it. Just ignore it.
  9731. if (!RealDecl)
  9732. return;
  9733. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  9734. QualType Type = Var->getType();
  9735. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  9736. if (isa<DecompositionDecl>(RealDecl)) {
  9737. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  9738. Var->setInvalidDecl();
  9739. return;
  9740. }
  9741. if (Type->isUndeducedType() &&
  9742. DeduceVariableDeclarationType(Var, false, nullptr))
  9743. return;
  9744. // C++11 [class.static.data]p3: A static data member can be declared with
  9745. // the constexpr specifier; if so, its declaration shall specify
  9746. // a brace-or-equal-initializer.
  9747. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  9748. // the definition of a variable [...] or the declaration of a static data
  9749. // member.
  9750. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  9751. !Var->isThisDeclarationADemotedDefinition()) {
  9752. if (Var->isStaticDataMember()) {
  9753. // C++1z removes the relevant rule; the in-class declaration is always
  9754. // a definition there.
  9755. if (!getLangOpts().CPlusPlus17) {
  9756. Diag(Var->getLocation(),
  9757. diag::err_constexpr_static_mem_var_requires_init)
  9758. << Var->getDeclName();
  9759. Var->setInvalidDecl();
  9760. return;
  9761. }
  9762. } else {
  9763. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  9764. Var->setInvalidDecl();
  9765. return;
  9766. }
  9767. }
  9768. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  9769. // be initialized.
  9770. if (!Var->isInvalidDecl() &&
  9771. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  9772. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  9773. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  9774. Var->setInvalidDecl();
  9775. return;
  9776. }
  9777. switch (Var->isThisDeclarationADefinition()) {
  9778. case VarDecl::Definition:
  9779. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  9780. break;
  9781. // We have an out-of-line definition of a static data member
  9782. // that has an in-class initializer, so we type-check this like
  9783. // a declaration.
  9784. //
  9785. LLVM_FALLTHROUGH;
  9786. case VarDecl::DeclarationOnly:
  9787. // It's only a declaration.
  9788. // Block scope. C99 6.7p7: If an identifier for an object is
  9789. // declared with no linkage (C99 6.2.2p6), the type for the
  9790. // object shall be complete.
  9791. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  9792. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  9793. RequireCompleteType(Var->getLocation(), Type,
  9794. diag::err_typecheck_decl_incomplete_type))
  9795. Var->setInvalidDecl();
  9796. // Make sure that the type is not abstract.
  9797. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  9798. RequireNonAbstractType(Var->getLocation(), Type,
  9799. diag::err_abstract_type_in_decl,
  9800. AbstractVariableType))
  9801. Var->setInvalidDecl();
  9802. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  9803. Var->getStorageClass() == SC_PrivateExtern) {
  9804. Diag(Var->getLocation(), diag::warn_private_extern);
  9805. Diag(Var->getLocation(), diag::note_private_extern);
  9806. }
  9807. return;
  9808. case VarDecl::TentativeDefinition:
  9809. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  9810. // object that has file scope without an initializer, and without a
  9811. // storage-class specifier or with the storage-class specifier "static",
  9812. // constitutes a tentative definition. Note: A tentative definition with
  9813. // external linkage is valid (C99 6.2.2p5).
  9814. if (!Var->isInvalidDecl()) {
  9815. if (const IncompleteArrayType *ArrayT
  9816. = Context.getAsIncompleteArrayType(Type)) {
  9817. if (RequireCompleteType(Var->getLocation(),
  9818. ArrayT->getElementType(),
  9819. diag::err_illegal_decl_array_incomplete_type))
  9820. Var->setInvalidDecl();
  9821. } else if (Var->getStorageClass() == SC_Static) {
  9822. // C99 6.9.2p3: If the declaration of an identifier for an object is
  9823. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  9824. // declared type shall not be an incomplete type.
  9825. // NOTE: code such as the following
  9826. // static struct s;
  9827. // struct s { int a; };
  9828. // is accepted by gcc. Hence here we issue a warning instead of
  9829. // an error and we do not invalidate the static declaration.
  9830. // NOTE: to avoid multiple warnings, only check the first declaration.
  9831. if (Var->isFirstDecl())
  9832. RequireCompleteType(Var->getLocation(), Type,
  9833. diag::ext_typecheck_decl_incomplete_type);
  9834. }
  9835. }
  9836. // Record the tentative definition; we're done.
  9837. if (!Var->isInvalidDecl())
  9838. TentativeDefinitions.push_back(Var);
  9839. return;
  9840. }
  9841. // Provide a specific diagnostic for uninitialized variable
  9842. // definitions with incomplete array type.
  9843. if (Type->isIncompleteArrayType()) {
  9844. Diag(Var->getLocation(),
  9845. diag::err_typecheck_incomplete_array_needs_initializer);
  9846. Var->setInvalidDecl();
  9847. return;
  9848. }
  9849. // Provide a specific diagnostic for uninitialized variable
  9850. // definitions with reference type.
  9851. if (Type->isReferenceType()) {
  9852. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  9853. << Var->getDeclName()
  9854. << SourceRange(Var->getLocation(), Var->getLocation());
  9855. Var->setInvalidDecl();
  9856. return;
  9857. }
  9858. // Do not attempt to type-check the default initializer for a
  9859. // variable with dependent type.
  9860. if (Type->isDependentType())
  9861. return;
  9862. if (Var->isInvalidDecl())
  9863. return;
  9864. if (!Var->hasAttr<AliasAttr>()) {
  9865. if (RequireCompleteType(Var->getLocation(),
  9866. Context.getBaseElementType(Type),
  9867. diag::err_typecheck_decl_incomplete_type)) {
  9868. Var->setInvalidDecl();
  9869. return;
  9870. }
  9871. } else {
  9872. return;
  9873. }
  9874. // The variable can not have an abstract class type.
  9875. if (RequireNonAbstractType(Var->getLocation(), Type,
  9876. diag::err_abstract_type_in_decl,
  9877. AbstractVariableType)) {
  9878. Var->setInvalidDecl();
  9879. return;
  9880. }
  9881. // Check for jumps past the implicit initializer. C++0x
  9882. // clarifies that this applies to a "variable with automatic
  9883. // storage duration", not a "local variable".
  9884. // C++11 [stmt.dcl]p3
  9885. // A program that jumps from a point where a variable with automatic
  9886. // storage duration is not in scope to a point where it is in scope is
  9887. // ill-formed unless the variable has scalar type, class type with a
  9888. // trivial default constructor and a trivial destructor, a cv-qualified
  9889. // version of one of these types, or an array of one of the preceding
  9890. // types and is declared without an initializer.
  9891. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  9892. if (const RecordType *Record
  9893. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  9894. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  9895. // Mark the function (if we're in one) for further checking even if the
  9896. // looser rules of C++11 do not require such checks, so that we can
  9897. // diagnose incompatibilities with C++98.
  9898. if (!CXXRecord->isPOD())
  9899. setFunctionHasBranchProtectedScope();
  9900. }
  9901. }
  9902. // C++03 [dcl.init]p9:
  9903. // If no initializer is specified for an object, and the
  9904. // object is of (possibly cv-qualified) non-POD class type (or
  9905. // array thereof), the object shall be default-initialized; if
  9906. // the object is of const-qualified type, the underlying class
  9907. // type shall have a user-declared default
  9908. // constructor. Otherwise, if no initializer is specified for
  9909. // a non- static object, the object and its subobjects, if
  9910. // any, have an indeterminate initial value); if the object
  9911. // or any of its subobjects are of const-qualified type, the
  9912. // program is ill-formed.
  9913. // C++0x [dcl.init]p11:
  9914. // If no initializer is specified for an object, the object is
  9915. // default-initialized; [...].
  9916. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  9917. InitializationKind Kind
  9918. = InitializationKind::CreateDefault(Var->getLocation());
  9919. InitializationSequence InitSeq(*this, Entity, Kind, None);
  9920. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  9921. if (Init.isInvalid())
  9922. Var->setInvalidDecl();
  9923. else if (Init.get()) {
  9924. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  9925. // This is important for template substitution.
  9926. Var->setInitStyle(VarDecl::CallInit);
  9927. }
  9928. CheckCompleteVariableDeclaration(Var);
  9929. }
  9930. }
  9931. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  9932. // If there is no declaration, there was an error parsing it. Ignore it.
  9933. if (!D)
  9934. return;
  9935. VarDecl *VD = dyn_cast<VarDecl>(D);
  9936. if (!VD) {
  9937. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  9938. D->setInvalidDecl();
  9939. return;
  9940. }
  9941. VD->setCXXForRangeDecl(true);
  9942. // for-range-declaration cannot be given a storage class specifier.
  9943. int Error = -1;
  9944. switch (VD->getStorageClass()) {
  9945. case SC_None:
  9946. break;
  9947. case SC_Extern:
  9948. Error = 0;
  9949. break;
  9950. case SC_Static:
  9951. Error = 1;
  9952. break;
  9953. case SC_PrivateExtern:
  9954. Error = 2;
  9955. break;
  9956. case SC_Auto:
  9957. Error = 3;
  9958. break;
  9959. case SC_Register:
  9960. Error = 4;
  9961. break;
  9962. }
  9963. if (Error != -1) {
  9964. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  9965. << VD->getDeclName() << Error;
  9966. D->setInvalidDecl();
  9967. }
  9968. }
  9969. StmtResult
  9970. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  9971. IdentifierInfo *Ident,
  9972. ParsedAttributes &Attrs,
  9973. SourceLocation AttrEnd) {
  9974. // C++1y [stmt.iter]p1:
  9975. // A range-based for statement of the form
  9976. // for ( for-range-identifier : for-range-initializer ) statement
  9977. // is equivalent to
  9978. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  9979. DeclSpec DS(Attrs.getPool().getFactory());
  9980. const char *PrevSpec;
  9981. unsigned DiagID;
  9982. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  9983. getPrintingPolicy());
  9984. Declarator D(DS, DeclaratorContext::ForContext);
  9985. D.SetIdentifier(Ident, IdentLoc);
  9986. D.takeAttributes(Attrs, AttrEnd);
  9987. ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
  9988. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
  9989. EmptyAttrs, IdentLoc);
  9990. Decl *Var = ActOnDeclarator(S, D);
  9991. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  9992. FinalizeDeclaration(Var);
  9993. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  9994. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  9995. }
  9996. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  9997. if (var->isInvalidDecl()) return;
  9998. if (getLangOpts().OpenCL) {
  9999. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  10000. // initialiser
  10001. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  10002. !var->hasInit()) {
  10003. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  10004. << 1 /*Init*/;
  10005. var->setInvalidDecl();
  10006. return;
  10007. }
  10008. }
  10009. // In Objective-C, don't allow jumps past the implicit initialization of a
  10010. // local retaining variable.
  10011. if (getLangOpts().ObjC1 &&
  10012. var->hasLocalStorage()) {
  10013. switch (var->getType().getObjCLifetime()) {
  10014. case Qualifiers::OCL_None:
  10015. case Qualifiers::OCL_ExplicitNone:
  10016. case Qualifiers::OCL_Autoreleasing:
  10017. break;
  10018. case Qualifiers::OCL_Weak:
  10019. case Qualifiers::OCL_Strong:
  10020. setFunctionHasBranchProtectedScope();
  10021. break;
  10022. }
  10023. }
  10024. if (var->hasLocalStorage() &&
  10025. var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  10026. setFunctionHasBranchProtectedScope();
  10027. // Warn about externally-visible variables being defined without a
  10028. // prior declaration. We only want to do this for global
  10029. // declarations, but we also specifically need to avoid doing it for
  10030. // class members because the linkage of an anonymous class can
  10031. // change if it's later given a typedef name.
  10032. if (var->isThisDeclarationADefinition() &&
  10033. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  10034. var->isExternallyVisible() && var->hasLinkage() &&
  10035. !var->isInline() && !var->getDescribedVarTemplate() &&
  10036. !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
  10037. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  10038. var->getLocation())) {
  10039. // Find a previous declaration that's not a definition.
  10040. VarDecl *prev = var->getPreviousDecl();
  10041. while (prev && prev->isThisDeclarationADefinition())
  10042. prev = prev->getPreviousDecl();
  10043. if (!prev)
  10044. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  10045. }
  10046. // Cache the result of checking for constant initialization.
  10047. Optional<bool> CacheHasConstInit;
  10048. const Expr *CacheCulprit;
  10049. auto checkConstInit = [&]() mutable {
  10050. if (!CacheHasConstInit)
  10051. CacheHasConstInit = var->getInit()->isConstantInitializer(
  10052. Context, var->getType()->isReferenceType(), &CacheCulprit);
  10053. return *CacheHasConstInit;
  10054. };
  10055. if (var->getTLSKind() == VarDecl::TLS_Static) {
  10056. if (var->getType().isDestructedType()) {
  10057. // GNU C++98 edits for __thread, [basic.start.term]p3:
  10058. // The type of an object with thread storage duration shall not
  10059. // have a non-trivial destructor.
  10060. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  10061. if (getLangOpts().CPlusPlus11)
  10062. Diag(var->getLocation(), diag::note_use_thread_local);
  10063. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  10064. if (!checkConstInit()) {
  10065. // GNU C++98 edits for __thread, [basic.start.init]p4:
  10066. // An object of thread storage duration shall not require dynamic
  10067. // initialization.
  10068. // FIXME: Need strict checking here.
  10069. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  10070. << CacheCulprit->getSourceRange();
  10071. if (getLangOpts().CPlusPlus11)
  10072. Diag(var->getLocation(), diag::note_use_thread_local);
  10073. }
  10074. }
  10075. }
  10076. // Apply section attributes and pragmas to global variables.
  10077. bool GlobalStorage = var->hasGlobalStorage();
  10078. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  10079. !inTemplateInstantiation()) {
  10080. PragmaStack<StringLiteral *> *Stack = nullptr;
  10081. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  10082. if (var->getType().isConstQualified())
  10083. Stack = &ConstSegStack;
  10084. else if (!var->getInit()) {
  10085. Stack = &BSSSegStack;
  10086. SectionFlags |= ASTContext::PSF_Write;
  10087. } else {
  10088. Stack = &DataSegStack;
  10089. SectionFlags |= ASTContext::PSF_Write;
  10090. }
  10091. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  10092. var->addAttr(SectionAttr::CreateImplicit(
  10093. Context, SectionAttr::Declspec_allocate,
  10094. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  10095. }
  10096. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  10097. if (UnifySection(SA->getName(), SectionFlags, var))
  10098. var->dropAttr<SectionAttr>();
  10099. // Apply the init_seg attribute if this has an initializer. If the
  10100. // initializer turns out to not be dynamic, we'll end up ignoring this
  10101. // attribute.
  10102. if (CurInitSeg && var->getInit())
  10103. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  10104. CurInitSegLoc));
  10105. }
  10106. // All the following checks are C++ only.
  10107. if (!getLangOpts().CPlusPlus) {
  10108. // If this variable must be emitted, add it as an initializer for the
  10109. // current module.
  10110. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10111. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10112. return;
  10113. }
  10114. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  10115. CheckCompleteDecompositionDeclaration(DD);
  10116. QualType type = var->getType();
  10117. if (type->isDependentType()) return;
  10118. // __block variables might require us to capture a copy-initializer.
  10119. if (var->hasAttr<BlocksAttr>()) {
  10120. // It's currently invalid to ever have a __block variable with an
  10121. // array type; should we diagnose that here?
  10122. // Regardless, we don't want to ignore array nesting when
  10123. // constructing this copy.
  10124. if (type->isStructureOrClassType()) {
  10125. EnterExpressionEvaluationContext scope(
  10126. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  10127. SourceLocation poi = var->getLocation();
  10128. Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
  10129. ExprResult result
  10130. = PerformMoveOrCopyInitialization(
  10131. InitializedEntity::InitializeBlock(poi, type, false),
  10132. var, var->getType(), varRef, /*AllowNRVO=*/true);
  10133. if (!result.isInvalid()) {
  10134. result = MaybeCreateExprWithCleanups(result);
  10135. Expr *init = result.getAs<Expr>();
  10136. Context.setBlockVarCopyInits(var, init);
  10137. }
  10138. }
  10139. }
  10140. Expr *Init = var->getInit();
  10141. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  10142. QualType baseType = Context.getBaseElementType(type);
  10143. if (Init && !Init->isValueDependent()) {
  10144. if (var->isConstexpr()) {
  10145. SmallVector<PartialDiagnosticAt, 8> Notes;
  10146. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  10147. SourceLocation DiagLoc = var->getLocation();
  10148. // If the note doesn't add any useful information other than a source
  10149. // location, fold it into the primary diagnostic.
  10150. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10151. diag::note_invalid_subexpr_in_const_expr) {
  10152. DiagLoc = Notes[0].first;
  10153. Notes.clear();
  10154. }
  10155. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  10156. << var << Init->getSourceRange();
  10157. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10158. Diag(Notes[I].first, Notes[I].second);
  10159. }
  10160. } else if (var->isUsableInConstantExpressions(Context)) {
  10161. // Check whether the initializer of a const variable of integral or
  10162. // enumeration type is an ICE now, since we can't tell whether it was
  10163. // initialized by a constant expression if we check later.
  10164. var->checkInitIsICE();
  10165. }
  10166. // Don't emit further diagnostics about constexpr globals since they
  10167. // were just diagnosed.
  10168. if (!var->isConstexpr() && GlobalStorage &&
  10169. var->hasAttr<RequireConstantInitAttr>()) {
  10170. // FIXME: Need strict checking in C++03 here.
  10171. bool DiagErr = getLangOpts().CPlusPlus11
  10172. ? !var->checkInitIsICE() : !checkConstInit();
  10173. if (DiagErr) {
  10174. auto attr = var->getAttr<RequireConstantInitAttr>();
  10175. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  10176. << Init->getSourceRange();
  10177. Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
  10178. << attr->getRange();
  10179. if (getLangOpts().CPlusPlus11) {
  10180. APValue Value;
  10181. SmallVector<PartialDiagnosticAt, 8> Notes;
  10182. Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
  10183. for (auto &it : Notes)
  10184. Diag(it.first, it.second);
  10185. } else {
  10186. Diag(CacheCulprit->getExprLoc(),
  10187. diag::note_invalid_subexpr_in_const_expr)
  10188. << CacheCulprit->getSourceRange();
  10189. }
  10190. }
  10191. }
  10192. else if (!var->isConstexpr() && IsGlobal &&
  10193. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  10194. var->getLocation())) {
  10195. // Warn about globals which don't have a constant initializer. Don't
  10196. // warn about globals with a non-trivial destructor because we already
  10197. // warned about them.
  10198. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  10199. if (!(RD && !RD->hasTrivialDestructor())) {
  10200. if (!checkConstInit())
  10201. Diag(var->getLocation(), diag::warn_global_constructor)
  10202. << Init->getSourceRange();
  10203. }
  10204. }
  10205. }
  10206. // Require the destructor.
  10207. if (const RecordType *recordType = baseType->getAs<RecordType>())
  10208. FinalizeVarWithDestructor(var, recordType);
  10209. // If this variable must be emitted, add it as an initializer for the current
  10210. // module.
  10211. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10212. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10213. }
  10214. /// \brief Determines if a variable's alignment is dependent.
  10215. static bool hasDependentAlignment(VarDecl *VD) {
  10216. if (VD->getType()->isDependentType())
  10217. return true;
  10218. for (auto *I : VD->specific_attrs<AlignedAttr>())
  10219. if (I->isAlignmentDependent())
  10220. return true;
  10221. return false;
  10222. }
  10223. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  10224. /// any semantic actions necessary after any initializer has been attached.
  10225. void Sema::FinalizeDeclaration(Decl *ThisDecl) {
  10226. // Note that we are no longer parsing the initializer for this declaration.
  10227. ParsingInitForAutoVars.erase(ThisDecl);
  10228. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  10229. if (!VD)
  10230. return;
  10231. // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
  10232. if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
  10233. !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
  10234. if (PragmaClangBSSSection.Valid)
  10235. VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
  10236. PragmaClangBSSSection.SectionName,
  10237. PragmaClangBSSSection.PragmaLocation));
  10238. if (PragmaClangDataSection.Valid)
  10239. VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
  10240. PragmaClangDataSection.SectionName,
  10241. PragmaClangDataSection.PragmaLocation));
  10242. if (PragmaClangRodataSection.Valid)
  10243. VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
  10244. PragmaClangRodataSection.SectionName,
  10245. PragmaClangRodataSection.PragmaLocation));
  10246. }
  10247. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  10248. for (auto *BD : DD->bindings()) {
  10249. FinalizeDeclaration(BD);
  10250. }
  10251. }
  10252. checkAttributesAfterMerging(*this, *VD);
  10253. // Perform TLS alignment check here after attributes attached to the variable
  10254. // which may affect the alignment have been processed. Only perform the check
  10255. // if the target has a maximum TLS alignment (zero means no constraints).
  10256. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  10257. // Protect the check so that it's not performed on dependent types and
  10258. // dependent alignments (we can't determine the alignment in that case).
  10259. if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
  10260. !VD->isInvalidDecl()) {
  10261. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  10262. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  10263. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  10264. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  10265. << (unsigned)MaxAlignChars.getQuantity();
  10266. }
  10267. }
  10268. }
  10269. if (VD->isStaticLocal()) {
  10270. if (FunctionDecl *FD =
  10271. dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  10272. // Static locals inherit dll attributes from their function.
  10273. if (Attr *A = getDLLAttr(FD)) {
  10274. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  10275. NewAttr->setInherited(true);
  10276. VD->addAttr(NewAttr);
  10277. }
  10278. // CUDA E.2.9.4: Within the body of a __device__ or __global__
  10279. // function, only __shared__ variables may be declared with
  10280. // static storage class.
  10281. if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
  10282. CUDADiagIfDeviceCode(VD->getLocation(),
  10283. diag::err_device_static_local_var)
  10284. << CurrentCUDATarget())
  10285. VD->setInvalidDecl();
  10286. }
  10287. }
  10288. // Perform check for initializers of device-side global variables.
  10289. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  10290. // 7.5). We must also apply the same checks to all __shared__
  10291. // variables whether they are local or not. CUDA also allows
  10292. // constant initializers for __constant__ and __device__ variables.
  10293. if (getLangOpts().CUDA) {
  10294. const Expr *Init = VD->getInit();
  10295. if (Init && VD->hasGlobalStorage()) {
  10296. if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
  10297. VD->hasAttr<CUDASharedAttr>()) {
  10298. assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
  10299. bool AllowedInit = false;
  10300. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
  10301. AllowedInit =
  10302. isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
  10303. // We'll allow constant initializers even if it's a non-empty
  10304. // constructor according to CUDA rules. This deviates from NVCC,
  10305. // but allows us to handle things like constexpr constructors.
  10306. if (!AllowedInit &&
  10307. (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  10308. AllowedInit = VD->getInit()->isConstantInitializer(
  10309. Context, VD->getType()->isReferenceType());
  10310. // Also make sure that destructor, if there is one, is empty.
  10311. if (AllowedInit)
  10312. if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
  10313. AllowedInit =
  10314. isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
  10315. if (!AllowedInit) {
  10316. Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
  10317. ? diag::err_shared_var_init
  10318. : diag::err_dynamic_var_init)
  10319. << Init->getSourceRange();
  10320. VD->setInvalidDecl();
  10321. }
  10322. } else {
  10323. // This is a host-side global variable. Check that the initializer is
  10324. // callable from the host side.
  10325. const FunctionDecl *InitFn = nullptr;
  10326. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
  10327. InitFn = CE->getConstructor();
  10328. } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
  10329. InitFn = CE->getDirectCallee();
  10330. }
  10331. if (InitFn) {
  10332. CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
  10333. if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
  10334. Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
  10335. << InitFnTarget << InitFn;
  10336. Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
  10337. VD->setInvalidDecl();
  10338. }
  10339. }
  10340. }
  10341. }
  10342. }
  10343. // Grab the dllimport or dllexport attribute off of the VarDecl.
  10344. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  10345. // Imported static data members cannot be defined out-of-line.
  10346. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  10347. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  10348. VD->isThisDeclarationADefinition()) {
  10349. // We allow definitions of dllimport class template static data members
  10350. // with a warning.
  10351. CXXRecordDecl *Context =
  10352. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  10353. bool IsClassTemplateMember =
  10354. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  10355. Context->getDescribedClassTemplate();
  10356. Diag(VD->getLocation(),
  10357. IsClassTemplateMember
  10358. ? diag::warn_attribute_dllimport_static_field_definition
  10359. : diag::err_attribute_dllimport_static_field_definition);
  10360. Diag(IA->getLocation(), diag::note_attribute);
  10361. if (!IsClassTemplateMember)
  10362. VD->setInvalidDecl();
  10363. }
  10364. }
  10365. // dllimport/dllexport variables cannot be thread local, their TLS index
  10366. // isn't exported with the variable.
  10367. if (DLLAttr && VD->getTLSKind()) {
  10368. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  10369. if (F && getDLLAttr(F)) {
  10370. assert(VD->isStaticLocal());
  10371. // But if this is a static local in a dlimport/dllexport function, the
  10372. // function will never be inlined, which means the var would never be
  10373. // imported, so having it marked import/export is safe.
  10374. } else {
  10375. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  10376. << DLLAttr;
  10377. VD->setInvalidDecl();
  10378. }
  10379. }
  10380. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  10381. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  10382. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  10383. VD->dropAttr<UsedAttr>();
  10384. }
  10385. }
  10386. const DeclContext *DC = VD->getDeclContext();
  10387. // If there's a #pragma GCC visibility in scope, and this isn't a class
  10388. // member, set the visibility of this variable.
  10389. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  10390. AddPushedVisibilityAttribute(VD);
  10391. // FIXME: Warn on unused var template partial specializations.
  10392. if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
  10393. MarkUnusedFileScopedDecl(VD);
  10394. // Now we have parsed the initializer and can update the table of magic
  10395. // tag values.
  10396. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  10397. !VD->getType()->isIntegralOrEnumerationType())
  10398. return;
  10399. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  10400. const Expr *MagicValueExpr = VD->getInit();
  10401. if (!MagicValueExpr) {
  10402. continue;
  10403. }
  10404. llvm::APSInt MagicValueInt;
  10405. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  10406. Diag(I->getRange().getBegin(),
  10407. diag::err_type_tag_for_datatype_not_ice)
  10408. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  10409. continue;
  10410. }
  10411. if (MagicValueInt.getActiveBits() > 64) {
  10412. Diag(I->getRange().getBegin(),
  10413. diag::err_type_tag_for_datatype_too_large)
  10414. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  10415. continue;
  10416. }
  10417. uint64_t MagicValue = MagicValueInt.getZExtValue();
  10418. RegisterTypeTagForDatatype(I->getArgumentKind(),
  10419. MagicValue,
  10420. I->getMatchingCType(),
  10421. I->getLayoutCompatible(),
  10422. I->getMustBeNull());
  10423. }
  10424. }
  10425. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  10426. auto *VD = dyn_cast<VarDecl>(DD);
  10427. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  10428. }
  10429. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  10430. ArrayRef<Decl *> Group) {
  10431. SmallVector<Decl*, 8> Decls;
  10432. if (DS.isTypeSpecOwned())
  10433. Decls.push_back(DS.getRepAsDecl());
  10434. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  10435. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  10436. bool DiagnosedMultipleDecomps = false;
  10437. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  10438. bool DiagnosedNonDeducedAuto = false;
  10439. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  10440. if (Decl *D = Group[i]) {
  10441. // For declarators, there are some additional syntactic-ish checks we need
  10442. // to perform.
  10443. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  10444. if (!FirstDeclaratorInGroup)
  10445. FirstDeclaratorInGroup = DD;
  10446. if (!FirstDecompDeclaratorInGroup)
  10447. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  10448. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  10449. !hasDeducedAuto(DD))
  10450. FirstNonDeducedAutoInGroup = DD;
  10451. if (FirstDeclaratorInGroup != DD) {
  10452. // A decomposition declaration cannot be combined with any other
  10453. // declaration in the same group.
  10454. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  10455. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  10456. diag::err_decomp_decl_not_alone)
  10457. << FirstDeclaratorInGroup->getSourceRange()
  10458. << DD->getSourceRange();
  10459. DiagnosedMultipleDecomps = true;
  10460. }
  10461. // A declarator that uses 'auto' in any way other than to declare a
  10462. // variable with a deduced type cannot be combined with any other
  10463. // declarator in the same group.
  10464. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  10465. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  10466. diag::err_auto_non_deduced_not_alone)
  10467. << FirstNonDeducedAutoInGroup->getType()
  10468. ->hasAutoForTrailingReturnType()
  10469. << FirstDeclaratorInGroup->getSourceRange()
  10470. << DD->getSourceRange();
  10471. DiagnosedNonDeducedAuto = true;
  10472. }
  10473. }
  10474. }
  10475. Decls.push_back(D);
  10476. }
  10477. }
  10478. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  10479. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  10480. handleTagNumbering(Tag, S);
  10481. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  10482. getLangOpts().CPlusPlus)
  10483. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  10484. }
  10485. }
  10486. return BuildDeclaratorGroup(Decls);
  10487. }
  10488. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  10489. /// group, performing any necessary semantic checking.
  10490. Sema::DeclGroupPtrTy
  10491. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  10492. // C++14 [dcl.spec.auto]p7: (DR1347)
  10493. // If the type that replaces the placeholder type is not the same in each
  10494. // deduction, the program is ill-formed.
  10495. if (Group.size() > 1) {
  10496. QualType Deduced;
  10497. VarDecl *DeducedDecl = nullptr;
  10498. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  10499. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  10500. if (!D || D->isInvalidDecl())
  10501. break;
  10502. DeducedType *DT = D->getType()->getContainedDeducedType();
  10503. if (!DT || DT->getDeducedType().isNull())
  10504. continue;
  10505. if (Deduced.isNull()) {
  10506. Deduced = DT->getDeducedType();
  10507. DeducedDecl = D;
  10508. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  10509. auto *AT = dyn_cast<AutoType>(DT);
  10510. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  10511. diag::err_auto_different_deductions)
  10512. << (AT ? (unsigned)AT->getKeyword() : 3)
  10513. << Deduced << DeducedDecl->getDeclName()
  10514. << DT->getDeducedType() << D->getDeclName()
  10515. << DeducedDecl->getInit()->getSourceRange()
  10516. << D->getInit()->getSourceRange();
  10517. D->setInvalidDecl();
  10518. break;
  10519. }
  10520. }
  10521. }
  10522. ActOnDocumentableDecls(Group);
  10523. return DeclGroupPtrTy::make(
  10524. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  10525. }
  10526. void Sema::ActOnDocumentableDecl(Decl *D) {
  10527. ActOnDocumentableDecls(D);
  10528. }
  10529. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  10530. // Don't parse the comment if Doxygen diagnostics are ignored.
  10531. if (Group.empty() || !Group[0])
  10532. return;
  10533. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  10534. Group[0]->getLocation()) &&
  10535. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  10536. Group[0]->getLocation()))
  10537. return;
  10538. if (Group.size() >= 2) {
  10539. // This is a decl group. Normally it will contain only declarations
  10540. // produced from declarator list. But in case we have any definitions or
  10541. // additional declaration references:
  10542. // 'typedef struct S {} S;'
  10543. // 'typedef struct S *S;'
  10544. // 'struct S *pS;'
  10545. // FinalizeDeclaratorGroup adds these as separate declarations.
  10546. Decl *MaybeTagDecl = Group[0];
  10547. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  10548. Group = Group.slice(1);
  10549. }
  10550. }
  10551. // See if there are any new comments that are not attached to a decl.
  10552. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  10553. if (!Comments.empty() &&
  10554. !Comments.back()->isAttached()) {
  10555. // There is at least one comment that not attached to a decl.
  10556. // Maybe it should be attached to one of these decls?
  10557. //
  10558. // Note that this way we pick up not only comments that precede the
  10559. // declaration, but also comments that *follow* the declaration -- thanks to
  10560. // the lookahead in the lexer: we've consumed the semicolon and looked
  10561. // ahead through comments.
  10562. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  10563. Context.getCommentForDecl(Group[i], &PP);
  10564. }
  10565. }
  10566. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  10567. /// to introduce parameters into function prototype scope.
  10568. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  10569. const DeclSpec &DS = D.getDeclSpec();
  10570. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  10571. // C++03 [dcl.stc]p2 also permits 'auto'.
  10572. StorageClass SC = SC_None;
  10573. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  10574. SC = SC_Register;
  10575. // In C++11, the 'register' storage class specifier is deprecated.
  10576. // In C++17, it is not allowed, but we tolerate it as an extension.
  10577. if (getLangOpts().CPlusPlus11) {
  10578. Diag(DS.getStorageClassSpecLoc(),
  10579. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  10580. : diag::warn_deprecated_register)
  10581. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  10582. }
  10583. } else if (getLangOpts().CPlusPlus &&
  10584. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  10585. SC = SC_Auto;
  10586. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  10587. Diag(DS.getStorageClassSpecLoc(),
  10588. diag::err_invalid_storage_class_in_func_decl);
  10589. D.getMutableDeclSpec().ClearStorageClassSpecs();
  10590. }
  10591. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  10592. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  10593. << DeclSpec::getSpecifierName(TSCS);
  10594. if (DS.isInlineSpecified())
  10595. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  10596. << getLangOpts().CPlusPlus17;
  10597. if (DS.isConstexprSpecified())
  10598. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  10599. << 0;
  10600. DiagnoseFunctionSpecifiers(DS);
  10601. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  10602. QualType parmDeclType = TInfo->getType();
  10603. if (getLangOpts().CPlusPlus) {
  10604. // Check that there are no default arguments inside the type of this
  10605. // parameter.
  10606. CheckExtraCXXDefaultArguments(D);
  10607. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  10608. if (D.getCXXScopeSpec().isSet()) {
  10609. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  10610. << D.getCXXScopeSpec().getRange();
  10611. D.getCXXScopeSpec().clear();
  10612. }
  10613. }
  10614. // Ensure we have a valid name
  10615. IdentifierInfo *II = nullptr;
  10616. if (D.hasName()) {
  10617. II = D.getIdentifier();
  10618. if (!II) {
  10619. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  10620. << GetNameForDeclarator(D).getName();
  10621. D.setInvalidType(true);
  10622. }
  10623. }
  10624. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  10625. if (II) {
  10626. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  10627. ForVisibleRedeclaration);
  10628. LookupName(R, S);
  10629. if (R.isSingleResult()) {
  10630. NamedDecl *PrevDecl = R.getFoundDecl();
  10631. if (PrevDecl->isTemplateParameter()) {
  10632. // Maybe we will complain about the shadowed template parameter.
  10633. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  10634. // Just pretend that we didn't see the previous declaration.
  10635. PrevDecl = nullptr;
  10636. } else if (S->isDeclScope(PrevDecl)) {
  10637. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  10638. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  10639. // Recover by removing the name
  10640. II = nullptr;
  10641. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  10642. D.setInvalidType(true);
  10643. }
  10644. }
  10645. }
  10646. // Temporarily put parameter variables in the translation unit, not
  10647. // the enclosing context. This prevents them from accidentally
  10648. // looking like class members in C++.
  10649. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  10650. D.getLocStart(),
  10651. D.getIdentifierLoc(), II,
  10652. parmDeclType, TInfo,
  10653. SC);
  10654. if (D.isInvalidType())
  10655. New->setInvalidDecl();
  10656. assert(S->isFunctionPrototypeScope());
  10657. assert(S->getFunctionPrototypeDepth() >= 1);
  10658. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  10659. S->getNextFunctionPrototypeIndex());
  10660. // Add the parameter declaration into this scope.
  10661. S->AddDecl(New);
  10662. if (II)
  10663. IdResolver.AddDecl(New);
  10664. ProcessDeclAttributes(S, New, D);
  10665. if (D.getDeclSpec().isModulePrivateSpecified())
  10666. Diag(New->getLocation(), diag::err_module_private_local)
  10667. << 1 << New->getDeclName()
  10668. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  10669. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  10670. if (New->hasAttr<BlocksAttr>()) {
  10671. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  10672. }
  10673. return New;
  10674. }
  10675. /// \brief Synthesizes a variable for a parameter arising from a
  10676. /// typedef.
  10677. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  10678. SourceLocation Loc,
  10679. QualType T) {
  10680. /* FIXME: setting StartLoc == Loc.
  10681. Would it be worth to modify callers so as to provide proper source
  10682. location for the unnamed parameters, embedding the parameter's type? */
  10683. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  10684. T, Context.getTrivialTypeSourceInfo(T, Loc),
  10685. SC_None, nullptr);
  10686. Param->setImplicit();
  10687. return Param;
  10688. }
  10689. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  10690. // Don't diagnose unused-parameter errors in template instantiations; we
  10691. // will already have done so in the template itself.
  10692. if (inTemplateInstantiation())
  10693. return;
  10694. for (const ParmVarDecl *Parameter : Parameters) {
  10695. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  10696. !Parameter->hasAttr<UnusedAttr>()) {
  10697. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  10698. << Parameter->getDeclName();
  10699. }
  10700. }
  10701. }
  10702. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  10703. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  10704. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  10705. return;
  10706. // Warn if the return value is pass-by-value and larger than the specified
  10707. // threshold.
  10708. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  10709. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  10710. if (Size > LangOpts.NumLargeByValueCopy)
  10711. Diag(D->getLocation(), diag::warn_return_value_size)
  10712. << D->getDeclName() << Size;
  10713. }
  10714. // Warn if any parameter is pass-by-value and larger than the specified
  10715. // threshold.
  10716. for (const ParmVarDecl *Parameter : Parameters) {
  10717. QualType T = Parameter->getType();
  10718. if (T->isDependentType() || !T.isPODType(Context))
  10719. continue;
  10720. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  10721. if (Size > LangOpts.NumLargeByValueCopy)
  10722. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  10723. << Parameter->getDeclName() << Size;
  10724. }
  10725. }
  10726. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  10727. SourceLocation NameLoc, IdentifierInfo *Name,
  10728. QualType T, TypeSourceInfo *TSInfo,
  10729. StorageClass SC) {
  10730. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  10731. if (getLangOpts().ObjCAutoRefCount &&
  10732. T.getObjCLifetime() == Qualifiers::OCL_None &&
  10733. T->isObjCLifetimeType()) {
  10734. Qualifiers::ObjCLifetime lifetime;
  10735. // Special cases for arrays:
  10736. // - if it's const, use __unsafe_unretained
  10737. // - otherwise, it's an error
  10738. if (T->isArrayType()) {
  10739. if (!T.isConstQualified()) {
  10740. DelayedDiagnostics.add(
  10741. sema::DelayedDiagnostic::makeForbiddenType(
  10742. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  10743. }
  10744. lifetime = Qualifiers::OCL_ExplicitNone;
  10745. } else {
  10746. lifetime = T->getObjCARCImplicitLifetime();
  10747. }
  10748. T = Context.getLifetimeQualifiedType(T, lifetime);
  10749. }
  10750. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  10751. Context.getAdjustedParameterType(T),
  10752. TSInfo, SC, nullptr);
  10753. // Parameters can not be abstract class types.
  10754. // For record types, this is done by the AbstractClassUsageDiagnoser once
  10755. // the class has been completely parsed.
  10756. if (!CurContext->isRecord() &&
  10757. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  10758. AbstractParamType))
  10759. New->setInvalidDecl();
  10760. // Parameter declarators cannot be interface types. All ObjC objects are
  10761. // passed by reference.
  10762. if (T->isObjCObjectType()) {
  10763. SourceLocation TypeEndLoc =
  10764. getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
  10765. Diag(NameLoc,
  10766. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  10767. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  10768. T = Context.getObjCObjectPointerType(T);
  10769. New->setType(T);
  10770. }
  10771. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  10772. // duration shall not be qualified by an address-space qualifier."
  10773. // Since all parameters have automatic store duration, they can not have
  10774. // an address space.
  10775. if (T.getAddressSpace() != LangAS::Default &&
  10776. // OpenCL allows function arguments declared to be an array of a type
  10777. // to be qualified with an address space.
  10778. !(getLangOpts().OpenCL &&
  10779. (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
  10780. Diag(NameLoc, diag::err_arg_with_address_space);
  10781. New->setInvalidDecl();
  10782. }
  10783. return New;
  10784. }
  10785. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  10786. SourceLocation LocAfterDecls) {
  10787. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  10788. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  10789. // for a K&R function.
  10790. if (!FTI.hasPrototype) {
  10791. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  10792. --i;
  10793. if (FTI.Params[i].Param == nullptr) {
  10794. SmallString<256> Code;
  10795. llvm::raw_svector_ostream(Code)
  10796. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  10797. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  10798. << FTI.Params[i].Ident
  10799. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  10800. // Implicitly declare the argument as type 'int' for lack of a better
  10801. // type.
  10802. AttributeFactory attrs;
  10803. DeclSpec DS(attrs);
  10804. const char* PrevSpec; // unused
  10805. unsigned DiagID; // unused
  10806. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  10807. DiagID, Context.getPrintingPolicy());
  10808. // Use the identifier location for the type source range.
  10809. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  10810. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  10811. Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
  10812. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  10813. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  10814. }
  10815. }
  10816. }
  10817. }
  10818. Decl *
  10819. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  10820. MultiTemplateParamsArg TemplateParameterLists,
  10821. SkipBodyInfo *SkipBody) {
  10822. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  10823. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  10824. Scope *ParentScope = FnBodyScope->getParent();
  10825. D.setFunctionDefinitionKind(FDK_Definition);
  10826. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  10827. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  10828. }
  10829. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  10830. Consumer.HandleInlineFunctionDefinition(D);
  10831. }
  10832. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  10833. const FunctionDecl*& PossibleZeroParamPrototype) {
  10834. // Don't warn about invalid declarations.
  10835. if (FD->isInvalidDecl())
  10836. return false;
  10837. // Or declarations that aren't global.
  10838. if (!FD->isGlobal())
  10839. return false;
  10840. // Don't warn about C++ member functions.
  10841. if (isa<CXXMethodDecl>(FD))
  10842. return false;
  10843. // Don't warn about 'main'.
  10844. if (FD->isMain())
  10845. return false;
  10846. // Don't warn about inline functions.
  10847. if (FD->isInlined())
  10848. return false;
  10849. // Don't warn about function templates.
  10850. if (FD->getDescribedFunctionTemplate())
  10851. return false;
  10852. // Don't warn about function template specializations.
  10853. if (FD->isFunctionTemplateSpecialization())
  10854. return false;
  10855. // Don't warn for OpenCL kernels.
  10856. if (FD->hasAttr<OpenCLKernelAttr>())
  10857. return false;
  10858. // Don't warn on explicitly deleted functions.
  10859. if (FD->isDeleted())
  10860. return false;
  10861. bool MissingPrototype = true;
  10862. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  10863. Prev; Prev = Prev->getPreviousDecl()) {
  10864. // Ignore any declarations that occur in function or method
  10865. // scope, because they aren't visible from the header.
  10866. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  10867. continue;
  10868. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  10869. if (FD->getNumParams() == 0)
  10870. PossibleZeroParamPrototype = Prev;
  10871. break;
  10872. }
  10873. return MissingPrototype;
  10874. }
  10875. void
  10876. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  10877. const FunctionDecl *EffectiveDefinition,
  10878. SkipBodyInfo *SkipBody) {
  10879. const FunctionDecl *Definition = EffectiveDefinition;
  10880. if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
  10881. // If this is a friend function defined in a class template, it does not
  10882. // have a body until it is used, nevertheless it is a definition, see
  10883. // [temp.inst]p2:
  10884. //
  10885. // ... for the purpose of determining whether an instantiated redeclaration
  10886. // is valid according to [basic.def.odr] and [class.mem], a declaration that
  10887. // corresponds to a definition in the template is considered to be a
  10888. // definition.
  10889. //
  10890. // The following code must produce redefinition error:
  10891. //
  10892. // template<typename T> struct C20 { friend void func_20() {} };
  10893. // C20<int> c20i;
  10894. // void func_20() {}
  10895. //
  10896. for (auto I : FD->redecls()) {
  10897. if (I != FD && !I->isInvalidDecl() &&
  10898. I->getFriendObjectKind() != Decl::FOK_None) {
  10899. if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
  10900. if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
  10901. // A merged copy of the same function, instantiated as a member of
  10902. // the same class, is OK.
  10903. if (declaresSameEntity(OrigFD, Original) &&
  10904. declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
  10905. cast<Decl>(FD->getLexicalDeclContext())))
  10906. continue;
  10907. }
  10908. if (Original->isThisDeclarationADefinition()) {
  10909. Definition = I;
  10910. break;
  10911. }
  10912. }
  10913. }
  10914. }
  10915. }
  10916. if (!Definition)
  10917. return;
  10918. if (canRedefineFunction(Definition, getLangOpts()))
  10919. return;
  10920. // Don't emit an error when this is redefinition of a typo-corrected
  10921. // definition.
  10922. if (TypoCorrectedFunctionDefinitions.count(Definition))
  10923. return;
  10924. // If we don't have a visible definition of the function, and it's inline or
  10925. // a template, skip the new definition.
  10926. if (SkipBody && !hasVisibleDefinition(Definition) &&
  10927. (Definition->getFormalLinkage() == InternalLinkage ||
  10928. Definition->isInlined() ||
  10929. Definition->getDescribedFunctionTemplate() ||
  10930. Definition->getNumTemplateParameterLists())) {
  10931. SkipBody->ShouldSkip = true;
  10932. if (auto *TD = Definition->getDescribedFunctionTemplate())
  10933. makeMergedDefinitionVisible(TD);
  10934. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
  10935. return;
  10936. }
  10937. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  10938. Definition->getStorageClass() == SC_Extern)
  10939. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  10940. << FD->getDeclName() << getLangOpts().CPlusPlus;
  10941. else
  10942. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  10943. Diag(Definition->getLocation(), diag::note_previous_definition);
  10944. FD->setInvalidDecl();
  10945. }
  10946. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  10947. Sema &S) {
  10948. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  10949. LambdaScopeInfo *LSI = S.PushLambdaScope();
  10950. LSI->CallOperator = CallOperator;
  10951. LSI->Lambda = LambdaClass;
  10952. LSI->ReturnType = CallOperator->getReturnType();
  10953. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  10954. if (LCD == LCD_None)
  10955. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  10956. else if (LCD == LCD_ByCopy)
  10957. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  10958. else if (LCD == LCD_ByRef)
  10959. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  10960. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  10961. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  10962. LSI->Mutable = !CallOperator->isConst();
  10963. // Add the captures to the LSI so they can be noted as already
  10964. // captured within tryCaptureVar.
  10965. auto I = LambdaClass->field_begin();
  10966. for (const auto &C : LambdaClass->captures()) {
  10967. if (C.capturesVariable()) {
  10968. VarDecl *VD = C.getCapturedVar();
  10969. if (VD->isInitCapture())
  10970. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  10971. QualType CaptureType = VD->getType();
  10972. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  10973. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  10974. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  10975. /*EllipsisLoc*/C.isPackExpansion()
  10976. ? C.getEllipsisLoc() : SourceLocation(),
  10977. CaptureType, /*Expr*/ nullptr);
  10978. } else if (C.capturesThis()) {
  10979. LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
  10980. /*Expr*/ nullptr,
  10981. C.getCaptureKind() == LCK_StarThis);
  10982. } else {
  10983. LSI->addVLATypeCapture(C.getLocation(), I->getType());
  10984. }
  10985. ++I;
  10986. }
  10987. }
  10988. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  10989. SkipBodyInfo *SkipBody) {
  10990. if (!D) {
  10991. // Parsing the function declaration failed in some way. Push on a fake scope
  10992. // anyway so we can try to parse the function body.
  10993. PushFunctionScope();
  10994. return D;
  10995. }
  10996. FunctionDecl *FD = nullptr;
  10997. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  10998. FD = FunTmpl->getTemplatedDecl();
  10999. else
  11000. FD = cast<FunctionDecl>(D);
  11001. // Check for defining attributes before the check for redefinition.
  11002. if (const auto *Attr = FD->getAttr<AliasAttr>()) {
  11003. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
  11004. FD->dropAttr<AliasAttr>();
  11005. FD->setInvalidDecl();
  11006. }
  11007. if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
  11008. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
  11009. FD->dropAttr<IFuncAttr>();
  11010. FD->setInvalidDecl();
  11011. }
  11012. // See if this is a redefinition. If 'will have body' is already set, then
  11013. // these checks were already performed when it was set.
  11014. if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
  11015. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  11016. // If we're skipping the body, we're done. Don't enter the scope.
  11017. if (SkipBody && SkipBody->ShouldSkip)
  11018. return D;
  11019. }
  11020. // Mark this function as "will have a body eventually". This lets users to
  11021. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  11022. // this function.
  11023. FD->setWillHaveBody();
  11024. // If we are instantiating a generic lambda call operator, push
  11025. // a LambdaScopeInfo onto the function stack. But use the information
  11026. // that's already been calculated (ActOnLambdaExpr) to prime the current
  11027. // LambdaScopeInfo.
  11028. // When the template operator is being specialized, the LambdaScopeInfo,
  11029. // has to be properly restored so that tryCaptureVariable doesn't try
  11030. // and capture any new variables. In addition when calculating potential
  11031. // captures during transformation of nested lambdas, it is necessary to
  11032. // have the LSI properly restored.
  11033. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  11034. assert(inTemplateInstantiation() &&
  11035. "There should be an active template instantiation on the stack "
  11036. "when instantiating a generic lambda!");
  11037. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  11038. } else {
  11039. // Enter a new function scope
  11040. PushFunctionScope();
  11041. }
  11042. // Builtin functions cannot be defined.
  11043. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11044. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  11045. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  11046. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  11047. FD->setInvalidDecl();
  11048. }
  11049. }
  11050. // The return type of a function definition must be complete
  11051. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  11052. QualType ResultType = FD->getReturnType();
  11053. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  11054. !FD->isInvalidDecl() &&
  11055. RequireCompleteType(FD->getLocation(), ResultType,
  11056. diag::err_func_def_incomplete_result))
  11057. FD->setInvalidDecl();
  11058. if (FnBodyScope)
  11059. PushDeclContext(FnBodyScope, FD);
  11060. // Check the validity of our function parameters
  11061. CheckParmsForFunctionDef(FD->parameters(),
  11062. /*CheckParameterNames=*/true);
  11063. // Add non-parameter declarations already in the function to the current
  11064. // scope.
  11065. if (FnBodyScope) {
  11066. for (Decl *NPD : FD->decls()) {
  11067. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  11068. if (!NonParmDecl)
  11069. continue;
  11070. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  11071. "parameters should not be in newly created FD yet");
  11072. // If the decl has a name, make it accessible in the current scope.
  11073. if (NonParmDecl->getDeclName())
  11074. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  11075. // Similarly, dive into enums and fish their constants out, making them
  11076. // accessible in this scope.
  11077. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  11078. for (auto *EI : ED->enumerators())
  11079. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  11080. }
  11081. }
  11082. }
  11083. // Introduce our parameters into the function scope
  11084. for (auto Param : FD->parameters()) {
  11085. Param->setOwningFunction(FD);
  11086. // If this has an identifier, add it to the scope stack.
  11087. if (Param->getIdentifier() && FnBodyScope) {
  11088. CheckShadow(FnBodyScope, Param);
  11089. PushOnScopeChains(Param, FnBodyScope);
  11090. }
  11091. }
  11092. // Ensure that the function's exception specification is instantiated.
  11093. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  11094. ResolveExceptionSpec(D->getLocation(), FPT);
  11095. // dllimport cannot be applied to non-inline function definitions.
  11096. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  11097. !FD->isTemplateInstantiation()) {
  11098. assert(!FD->hasAttr<DLLExportAttr>());
  11099. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  11100. FD->setInvalidDecl();
  11101. return D;
  11102. }
  11103. // We want to attach documentation to original Decl (which might be
  11104. // a function template).
  11105. ActOnDocumentableDecl(D);
  11106. if (getCurLexicalContext()->isObjCContainer() &&
  11107. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  11108. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  11109. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  11110. return D;
  11111. }
  11112. /// \brief Given the set of return statements within a function body,
  11113. /// compute the variables that are subject to the named return value
  11114. /// optimization.
  11115. ///
  11116. /// Each of the variables that is subject to the named return value
  11117. /// optimization will be marked as NRVO variables in the AST, and any
  11118. /// return statement that has a marked NRVO variable as its NRVO candidate can
  11119. /// use the named return value optimization.
  11120. ///
  11121. /// This function applies a very simplistic algorithm for NRVO: if every return
  11122. /// statement in the scope of a variable has the same NRVO candidate, that
  11123. /// candidate is an NRVO variable.
  11124. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  11125. ReturnStmt **Returns = Scope->Returns.data();
  11126. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  11127. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  11128. if (!NRVOCandidate->isNRVOVariable())
  11129. Returns[I]->setNRVOCandidate(nullptr);
  11130. }
  11131. }
  11132. }
  11133. bool Sema::canDelayFunctionBody(const Declarator &D) {
  11134. // We can't delay parsing the body of a constexpr function template (yet).
  11135. if (D.getDeclSpec().isConstexprSpecified())
  11136. return false;
  11137. // We can't delay parsing the body of a function template with a deduced
  11138. // return type (yet).
  11139. if (D.getDeclSpec().hasAutoTypeSpec()) {
  11140. // If the placeholder introduces a non-deduced trailing return type,
  11141. // we can still delay parsing it.
  11142. if (D.getNumTypeObjects()) {
  11143. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  11144. if (Outer.Kind == DeclaratorChunk::Function &&
  11145. Outer.Fun.hasTrailingReturnType()) {
  11146. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  11147. return Ty.isNull() || !Ty->isUndeducedType();
  11148. }
  11149. }
  11150. return false;
  11151. }
  11152. return true;
  11153. }
  11154. bool Sema::canSkipFunctionBody(Decl *D) {
  11155. // We cannot skip the body of a function (or function template) which is
  11156. // constexpr, since we may need to evaluate its body in order to parse the
  11157. // rest of the file.
  11158. // We cannot skip the body of a function with an undeduced return type,
  11159. // because any callers of that function need to know the type.
  11160. if (const FunctionDecl *FD = D->getAsFunction())
  11161. if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
  11162. return false;
  11163. return Consumer.shouldSkipFunctionBody(D);
  11164. }
  11165. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  11166. if (!Decl)
  11167. return nullptr;
  11168. if (FunctionDecl *FD = Decl->getAsFunction())
  11169. FD->setHasSkippedBody();
  11170. else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
  11171. MD->setHasSkippedBody();
  11172. return Decl;
  11173. }
  11174. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  11175. return ActOnFinishFunctionBody(D, BodyArg, false);
  11176. }
  11177. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  11178. bool IsInstantiation) {
  11179. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  11180. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  11181. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  11182. if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
  11183. CheckCompletedCoroutineBody(FD, Body);
  11184. if (FD) {
  11185. FD->setBody(Body);
  11186. FD->setWillHaveBody(false);
  11187. if (getLangOpts().CPlusPlus14) {
  11188. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  11189. FD->getReturnType()->isUndeducedType()) {
  11190. // If the function has a deduced result type but contains no 'return'
  11191. // statements, the result type as written must be exactly 'auto', and
  11192. // the deduced result type is 'void'.
  11193. if (!FD->getReturnType()->getAs<AutoType>()) {
  11194. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  11195. << FD->getReturnType();
  11196. FD->setInvalidDecl();
  11197. } else {
  11198. // Substitute 'void' for the 'auto' in the type.
  11199. TypeLoc ResultType = getReturnTypeLoc(FD);
  11200. Context.adjustDeducedFunctionResultType(
  11201. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  11202. }
  11203. }
  11204. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  11205. // In C++11, we don't use 'auto' deduction rules for lambda call
  11206. // operators because we don't support return type deduction.
  11207. auto *LSI = getCurLambda();
  11208. if (LSI->HasImplicitReturnType) {
  11209. deduceClosureReturnType(*LSI);
  11210. // C++11 [expr.prim.lambda]p4:
  11211. // [...] if there are no return statements in the compound-statement
  11212. // [the deduced type is] the type void
  11213. QualType RetType =
  11214. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  11215. // Update the return type to the deduced type.
  11216. const FunctionProtoType *Proto =
  11217. FD->getType()->getAs<FunctionProtoType>();
  11218. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  11219. Proto->getExtProtoInfo()));
  11220. }
  11221. }
  11222. // If the function implicitly returns zero (like 'main') or is naked,
  11223. // don't complain about missing return statements.
  11224. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  11225. WP.disableCheckFallThrough();
  11226. // MSVC permits the use of pure specifier (=0) on function definition,
  11227. // defined at class scope, warn about this non-standard construct.
  11228. if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
  11229. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  11230. if (!FD->isInvalidDecl()) {
  11231. // Don't diagnose unused parameters of defaulted or deleted functions.
  11232. if (!FD->isDeleted() && !FD->isDefaulted())
  11233. DiagnoseUnusedParameters(FD->parameters());
  11234. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  11235. FD->getReturnType(), FD);
  11236. // If this is a structor, we need a vtable.
  11237. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  11238. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  11239. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  11240. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  11241. // Try to apply the named return value optimization. We have to check
  11242. // if we can do this here because lambdas keep return statements around
  11243. // to deduce an implicit return type.
  11244. if (FD->getReturnType()->isRecordType() &&
  11245. (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
  11246. computeNRVO(Body, getCurFunction());
  11247. }
  11248. // GNU warning -Wmissing-prototypes:
  11249. // Warn if a global function is defined without a previous
  11250. // prototype declaration. This warning is issued even if the
  11251. // definition itself provides a prototype. The aim is to detect
  11252. // global functions that fail to be declared in header files.
  11253. const FunctionDecl *PossibleZeroParamPrototype = nullptr;
  11254. if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
  11255. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  11256. if (PossibleZeroParamPrototype) {
  11257. // We found a declaration that is not a prototype,
  11258. // but that could be a zero-parameter prototype
  11259. if (TypeSourceInfo *TI =
  11260. PossibleZeroParamPrototype->getTypeSourceInfo()) {
  11261. TypeLoc TL = TI->getTypeLoc();
  11262. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  11263. Diag(PossibleZeroParamPrototype->getLocation(),
  11264. diag::note_declaration_not_a_prototype)
  11265. << PossibleZeroParamPrototype
  11266. << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
  11267. }
  11268. }
  11269. // GNU warning -Wstrict-prototypes
  11270. // Warn if K&R function is defined without a previous declaration.
  11271. // This warning is issued only if the definition itself does not provide
  11272. // a prototype. Only K&R definitions do not provide a prototype.
  11273. // An empty list in a function declarator that is part of a definition
  11274. // of that function specifies that the function has no parameters
  11275. // (C99 6.7.5.3p14)
  11276. if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
  11277. !LangOpts.CPlusPlus) {
  11278. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  11279. TypeLoc TL = TI->getTypeLoc();
  11280. FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
  11281. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
  11282. }
  11283. }
  11284. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  11285. const CXXMethodDecl *KeyFunction;
  11286. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  11287. MD->isVirtual() &&
  11288. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  11289. MD == KeyFunction->getCanonicalDecl()) {
  11290. // Update the key-function state if necessary for this ABI.
  11291. if (FD->isInlined() &&
  11292. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  11293. Context.setNonKeyFunction(MD);
  11294. // If the newly-chosen key function is already defined, then we
  11295. // need to mark the vtable as used retroactively.
  11296. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  11297. const FunctionDecl *Definition;
  11298. if (KeyFunction && KeyFunction->isDefined(Definition))
  11299. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  11300. } else {
  11301. // We just defined they key function; mark the vtable as used.
  11302. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  11303. }
  11304. }
  11305. }
  11306. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  11307. "Function parsing confused");
  11308. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  11309. assert(MD == getCurMethodDecl() && "Method parsing confused");
  11310. MD->setBody(Body);
  11311. if (!MD->isInvalidDecl()) {
  11312. DiagnoseUnusedParameters(MD->parameters());
  11313. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  11314. MD->getReturnType(), MD);
  11315. if (Body)
  11316. computeNRVO(Body, getCurFunction());
  11317. }
  11318. if (getCurFunction()->ObjCShouldCallSuper) {
  11319. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
  11320. << MD->getSelector().getAsString();
  11321. getCurFunction()->ObjCShouldCallSuper = false;
  11322. }
  11323. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  11324. const ObjCMethodDecl *InitMethod = nullptr;
  11325. bool isDesignated =
  11326. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  11327. assert(isDesignated && InitMethod);
  11328. (void)isDesignated;
  11329. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  11330. auto IFace = MD->getClassInterface();
  11331. if (!IFace)
  11332. return false;
  11333. auto SuperD = IFace->getSuperClass();
  11334. if (!SuperD)
  11335. return false;
  11336. return SuperD->getIdentifier() ==
  11337. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  11338. };
  11339. // Don't issue this warning for unavailable inits or direct subclasses
  11340. // of NSObject.
  11341. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  11342. Diag(MD->getLocation(),
  11343. diag::warn_objc_designated_init_missing_super_call);
  11344. Diag(InitMethod->getLocation(),
  11345. diag::note_objc_designated_init_marked_here);
  11346. }
  11347. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  11348. }
  11349. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  11350. // Don't issue this warning for unavaialable inits.
  11351. if (!MD->isUnavailable())
  11352. Diag(MD->getLocation(),
  11353. diag::warn_objc_secondary_init_missing_init_call);
  11354. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  11355. }
  11356. } else {
  11357. // Parsing the function declaration failed in some way. Pop the fake scope
  11358. // we pushed on.
  11359. PopFunctionScopeInfo(ActivePolicy, dcl);
  11360. return nullptr;
  11361. }
  11362. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  11363. DiagnoseUnguardedAvailabilityViolations(dcl);
  11364. assert(!getCurFunction()->ObjCShouldCallSuper &&
  11365. "This should only be set for ObjC methods, which should have been "
  11366. "handled in the block above.");
  11367. // Verify and clean out per-function state.
  11368. if (Body && (!FD || !FD->isDefaulted())) {
  11369. // C++ constructors that have function-try-blocks can't have return
  11370. // statements in the handlers of that block. (C++ [except.handle]p14)
  11371. // Verify this.
  11372. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  11373. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  11374. // Verify that gotos and switch cases don't jump into scopes illegally.
  11375. if (getCurFunction()->NeedsScopeChecking() &&
  11376. !PP.isCodeCompletionEnabled())
  11377. DiagnoseInvalidJumps(Body);
  11378. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  11379. if (!Destructor->getParent()->isDependentType())
  11380. CheckDestructor(Destructor);
  11381. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  11382. Destructor->getParent());
  11383. }
  11384. // If any errors have occurred, clear out any temporaries that may have
  11385. // been leftover. This ensures that these temporaries won't be picked up for
  11386. // deletion in some later function.
  11387. if (getDiagnostics().hasErrorOccurred() ||
  11388. getDiagnostics().getSuppressAllDiagnostics()) {
  11389. DiscardCleanupsInEvaluationContext();
  11390. }
  11391. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  11392. !isa<FunctionTemplateDecl>(dcl)) {
  11393. // Since the body is valid, issue any analysis-based warnings that are
  11394. // enabled.
  11395. ActivePolicy = &WP;
  11396. }
  11397. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  11398. (!CheckConstexprFunctionDecl(FD) ||
  11399. !CheckConstexprFunctionBody(FD, Body)))
  11400. FD->setInvalidDecl();
  11401. if (FD && FD->hasAttr<NakedAttr>()) {
  11402. for (const Stmt *S : Body->children()) {
  11403. // Allow local register variables without initializer as they don't
  11404. // require prologue.
  11405. bool RegisterVariables = false;
  11406. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  11407. for (const auto *Decl : DS->decls()) {
  11408. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  11409. RegisterVariables =
  11410. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  11411. if (!RegisterVariables)
  11412. break;
  11413. }
  11414. }
  11415. }
  11416. if (RegisterVariables)
  11417. continue;
  11418. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  11419. Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
  11420. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  11421. FD->setInvalidDecl();
  11422. break;
  11423. }
  11424. }
  11425. }
  11426. assert(ExprCleanupObjects.size() ==
  11427. ExprEvalContexts.back().NumCleanupObjects &&
  11428. "Leftover temporaries in function");
  11429. assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
  11430. assert(MaybeODRUseExprs.empty() &&
  11431. "Leftover expressions for odr-use checking");
  11432. }
  11433. if (!IsInstantiation)
  11434. PopDeclContext();
  11435. PopFunctionScopeInfo(ActivePolicy, dcl);
  11436. // If any errors have occurred, clear out any temporaries that may have
  11437. // been leftover. This ensures that these temporaries won't be picked up for
  11438. // deletion in some later function.
  11439. if (getDiagnostics().hasErrorOccurred()) {
  11440. DiscardCleanupsInEvaluationContext();
  11441. }
  11442. return dcl;
  11443. }
  11444. /// When we finish delayed parsing of an attribute, we must attach it to the
  11445. /// relevant Decl.
  11446. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  11447. ParsedAttributes &Attrs) {
  11448. // Always attach attributes to the underlying decl.
  11449. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  11450. D = TD->getTemplatedDecl();
  11451. ProcessDeclAttributeList(S, D, Attrs.getList());
  11452. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  11453. if (Method->isStatic())
  11454. checkThisInStaticMemberFunctionAttributes(Method);
  11455. }
  11456. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  11457. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  11458. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  11459. IdentifierInfo &II, Scope *S) {
  11460. // Find the scope in which the identifier is injected and the corresponding
  11461. // DeclContext.
  11462. // FIXME: C89 does not say what happens if there is no enclosing block scope.
  11463. // In that case, we inject the declaration into the translation unit scope
  11464. // instead.
  11465. Scope *BlockScope = S;
  11466. while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
  11467. BlockScope = BlockScope->getParent();
  11468. Scope *ContextScope = BlockScope;
  11469. while (!ContextScope->getEntity())
  11470. ContextScope = ContextScope->getParent();
  11471. ContextRAII SavedContext(*this, ContextScope->getEntity());
  11472. // Before we produce a declaration for an implicitly defined
  11473. // function, see whether there was a locally-scoped declaration of
  11474. // this name as a function or variable. If so, use that
  11475. // (non-visible) declaration, and complain about it.
  11476. NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
  11477. if (ExternCPrev) {
  11478. // We still need to inject the function into the enclosing block scope so
  11479. // that later (non-call) uses can see it.
  11480. PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
  11481. // C89 footnote 38:
  11482. // If in fact it is not defined as having type "function returning int",
  11483. // the behavior is undefined.
  11484. if (!isa<FunctionDecl>(ExternCPrev) ||
  11485. !Context.typesAreCompatible(
  11486. cast<FunctionDecl>(ExternCPrev)->getType(),
  11487. Context.getFunctionNoProtoType(Context.IntTy))) {
  11488. Diag(Loc, diag::ext_use_out_of_scope_declaration)
  11489. << ExternCPrev << !getLangOpts().C99;
  11490. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  11491. return ExternCPrev;
  11492. }
  11493. }
  11494. // Extension in C99. Legal in C90, but warn about it.
  11495. // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
  11496. unsigned diag_id;
  11497. if (II.getName().startswith("__builtin_"))
  11498. diag_id = diag::warn_builtin_unknown;
  11499. else if (getLangOpts().C99 || getLangOpts().OpenCL)
  11500. diag_id = diag::ext_implicit_function_decl;
  11501. else
  11502. diag_id = diag::warn_implicit_function_decl;
  11503. Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
  11504. // If we found a prior declaration of this function, don't bother building
  11505. // another one. We've already pushed that one into scope, so there's nothing
  11506. // more to do.
  11507. if (ExternCPrev)
  11508. return ExternCPrev;
  11509. // Because typo correction is expensive, only do it if the implicit
  11510. // function declaration is going to be treated as an error.
  11511. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  11512. TypoCorrection Corrected;
  11513. if (S &&
  11514. (Corrected = CorrectTypo(
  11515. DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
  11516. llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
  11517. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  11518. /*ErrorRecovery*/false);
  11519. }
  11520. // Set a Declarator for the implicit definition: int foo();
  11521. const char *Dummy;
  11522. AttributeFactory attrFactory;
  11523. DeclSpec DS(attrFactory);
  11524. unsigned DiagID;
  11525. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  11526. Context.getPrintingPolicy());
  11527. (void)Error; // Silence warning.
  11528. assert(!Error && "Error setting up implicit decl!");
  11529. SourceLocation NoLoc;
  11530. Declarator D(DS, DeclaratorContext::BlockContext);
  11531. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  11532. /*IsAmbiguous=*/false,
  11533. /*LParenLoc=*/NoLoc,
  11534. /*Params=*/nullptr,
  11535. /*NumParams=*/0,
  11536. /*EllipsisLoc=*/NoLoc,
  11537. /*RParenLoc=*/NoLoc,
  11538. /*TypeQuals=*/0,
  11539. /*RefQualifierIsLvalueRef=*/true,
  11540. /*RefQualifierLoc=*/NoLoc,
  11541. /*ConstQualifierLoc=*/NoLoc,
  11542. /*VolatileQualifierLoc=*/NoLoc,
  11543. /*RestrictQualifierLoc=*/NoLoc,
  11544. /*MutableLoc=*/NoLoc,
  11545. EST_None,
  11546. /*ESpecRange=*/SourceRange(),
  11547. /*Exceptions=*/nullptr,
  11548. /*ExceptionRanges=*/nullptr,
  11549. /*NumExceptions=*/0,
  11550. /*NoexceptExpr=*/nullptr,
  11551. /*ExceptionSpecTokens=*/nullptr,
  11552. /*DeclsInPrototype=*/None,
  11553. Loc, Loc, D),
  11554. DS.getAttributes(),
  11555. SourceLocation());
  11556. D.SetIdentifier(&II, Loc);
  11557. // Insert this function into the enclosing block scope.
  11558. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
  11559. FD->setImplicit();
  11560. AddKnownFunctionAttributes(FD);
  11561. return FD;
  11562. }
  11563. /// \brief Adds any function attributes that we know a priori based on
  11564. /// the declaration of this function.
  11565. ///
  11566. /// These attributes can apply both to implicitly-declared builtins
  11567. /// (like __builtin___printf_chk) or to library-declared functions
  11568. /// like NSLog or printf.
  11569. ///
  11570. /// We need to check for duplicate attributes both here and where user-written
  11571. /// attributes are applied to declarations.
  11572. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  11573. if (FD->isInvalidDecl())
  11574. return;
  11575. // If this is a built-in function, map its builtin attributes to
  11576. // actual attributes.
  11577. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11578. // Handle printf-formatting attributes.
  11579. unsigned FormatIdx;
  11580. bool HasVAListArg;
  11581. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  11582. if (!FD->hasAttr<FormatAttr>()) {
  11583. const char *fmt = "printf";
  11584. unsigned int NumParams = FD->getNumParams();
  11585. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  11586. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  11587. fmt = "NSString";
  11588. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11589. &Context.Idents.get(fmt),
  11590. FormatIdx+1,
  11591. HasVAListArg ? 0 : FormatIdx+2,
  11592. FD->getLocation()));
  11593. }
  11594. }
  11595. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  11596. HasVAListArg)) {
  11597. if (!FD->hasAttr<FormatAttr>())
  11598. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11599. &Context.Idents.get("scanf"),
  11600. FormatIdx+1,
  11601. HasVAListArg ? 0 : FormatIdx+2,
  11602. FD->getLocation()));
  11603. }
  11604. // Mark const if we don't care about errno and that is the only thing
  11605. // preventing the function from being const. This allows IRgen to use LLVM
  11606. // intrinsics for such functions.
  11607. if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
  11608. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
  11609. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  11610. // We make "fma" on some platforms const because we know it does not set
  11611. // errno in those environments even though it could set errno based on the
  11612. // C standard.
  11613. const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
  11614. if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
  11615. !FD->hasAttr<ConstAttr>()) {
  11616. switch (BuiltinID) {
  11617. case Builtin::BI__builtin_fma:
  11618. case Builtin::BI__builtin_fmaf:
  11619. case Builtin::BI__builtin_fmal:
  11620. case Builtin::BIfma:
  11621. case Builtin::BIfmaf:
  11622. case Builtin::BIfmal:
  11623. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  11624. break;
  11625. default:
  11626. break;
  11627. }
  11628. }
  11629. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  11630. !FD->hasAttr<ReturnsTwiceAttr>())
  11631. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  11632. FD->getLocation()));
  11633. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  11634. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  11635. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  11636. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  11637. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  11638. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  11639. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  11640. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  11641. // Add the appropriate attribute, depending on the CUDA compilation mode
  11642. // and which target the builtin belongs to. For example, during host
  11643. // compilation, aux builtins are __device__, while the rest are __host__.
  11644. if (getLangOpts().CUDAIsDevice !=
  11645. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  11646. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  11647. else
  11648. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  11649. }
  11650. }
  11651. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  11652. // throw, add an implicit nothrow attribute to any extern "C" function we come
  11653. // across.
  11654. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  11655. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  11656. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  11657. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  11658. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  11659. }
  11660. IdentifierInfo *Name = FD->getIdentifier();
  11661. if (!Name)
  11662. return;
  11663. if ((!getLangOpts().CPlusPlus &&
  11664. FD->getDeclContext()->isTranslationUnit()) ||
  11665. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  11666. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  11667. LinkageSpecDecl::lang_c)) {
  11668. // Okay: this could be a libc/libm/Objective-C function we know
  11669. // about.
  11670. } else
  11671. return;
  11672. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  11673. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  11674. // target-specific builtins, perhaps?
  11675. if (!FD->hasAttr<FormatAttr>())
  11676. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11677. &Context.Idents.get("printf"), 2,
  11678. Name->isStr("vasprintf") ? 0 : 3,
  11679. FD->getLocation()));
  11680. }
  11681. if (Name->isStr("__CFStringMakeConstantString")) {
  11682. // We already have a __builtin___CFStringMakeConstantString,
  11683. // but builds that use -fno-constant-cfstrings don't go through that.
  11684. if (!FD->hasAttr<FormatArgAttr>())
  11685. FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
  11686. FD->getLocation()));
  11687. }
  11688. }
  11689. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  11690. TypeSourceInfo *TInfo) {
  11691. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  11692. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  11693. if (!TInfo) {
  11694. assert(D.isInvalidType() && "no declarator info for valid type");
  11695. TInfo = Context.getTrivialTypeSourceInfo(T);
  11696. }
  11697. // Scope manipulation handled by caller.
  11698. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  11699. D.getLocStart(),
  11700. D.getIdentifierLoc(),
  11701. D.getIdentifier(),
  11702. TInfo);
  11703. // Bail out immediately if we have an invalid declaration.
  11704. if (D.isInvalidType()) {
  11705. NewTD->setInvalidDecl();
  11706. return NewTD;
  11707. }
  11708. if (D.getDeclSpec().isModulePrivateSpecified()) {
  11709. if (CurContext->isFunctionOrMethod())
  11710. Diag(NewTD->getLocation(), diag::err_module_private_local)
  11711. << 2 << NewTD->getDeclName()
  11712. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  11713. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  11714. else
  11715. NewTD->setModulePrivate();
  11716. }
  11717. // C++ [dcl.typedef]p8:
  11718. // If the typedef declaration defines an unnamed class (or
  11719. // enum), the first typedef-name declared by the declaration
  11720. // to be that class type (or enum type) is used to denote the
  11721. // class type (or enum type) for linkage purposes only.
  11722. // We need to check whether the type was declared in the declaration.
  11723. switch (D.getDeclSpec().getTypeSpecType()) {
  11724. case TST_enum:
  11725. case TST_struct:
  11726. case TST_interface:
  11727. case TST_union:
  11728. case TST_class: {
  11729. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  11730. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  11731. break;
  11732. }
  11733. default:
  11734. break;
  11735. }
  11736. return NewTD;
  11737. }
  11738. /// \brief Check that this is a valid underlying type for an enum declaration.
  11739. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  11740. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  11741. QualType T = TI->getType();
  11742. if (T->isDependentType())
  11743. return false;
  11744. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  11745. if (BT->isInteger())
  11746. return false;
  11747. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  11748. return true;
  11749. }
  11750. /// Check whether this is a valid redeclaration of a previous enumeration.
  11751. /// \return true if the redeclaration was invalid.
  11752. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  11753. QualType EnumUnderlyingTy, bool IsFixed,
  11754. const EnumDecl *Prev) {
  11755. if (IsScoped != Prev->isScoped()) {
  11756. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  11757. << Prev->isScoped();
  11758. Diag(Prev->getLocation(), diag::note_previous_declaration);
  11759. return true;
  11760. }
  11761. if (IsFixed && Prev->isFixed()) {
  11762. if (!EnumUnderlyingTy->isDependentType() &&
  11763. !Prev->getIntegerType()->isDependentType() &&
  11764. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  11765. Prev->getIntegerType())) {
  11766. // TODO: Highlight the underlying type of the redeclaration.
  11767. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  11768. << EnumUnderlyingTy << Prev->getIntegerType();
  11769. Diag(Prev->getLocation(), diag::note_previous_declaration)
  11770. << Prev->getIntegerTypeRange();
  11771. return true;
  11772. }
  11773. } else if (IsFixed != Prev->isFixed()) {
  11774. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  11775. << Prev->isFixed();
  11776. Diag(Prev->getLocation(), diag::note_previous_declaration);
  11777. return true;
  11778. }
  11779. return false;
  11780. }
  11781. /// \brief Get diagnostic %select index for tag kind for
  11782. /// redeclaration diagnostic message.
  11783. /// WARNING: Indexes apply to particular diagnostics only!
  11784. ///
  11785. /// \returns diagnostic %select index.
  11786. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  11787. switch (Tag) {
  11788. case TTK_Struct: return 0;
  11789. case TTK_Interface: return 1;
  11790. case TTK_Class: return 2;
  11791. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  11792. }
  11793. }
  11794. /// \brief Determine if tag kind is a class-key compatible with
  11795. /// class for redeclaration (class, struct, or __interface).
  11796. ///
  11797. /// \returns true iff the tag kind is compatible.
  11798. static bool isClassCompatTagKind(TagTypeKind Tag)
  11799. {
  11800. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  11801. }
  11802. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  11803. TagTypeKind TTK) {
  11804. if (isa<TypedefDecl>(PrevDecl))
  11805. return NTK_Typedef;
  11806. else if (isa<TypeAliasDecl>(PrevDecl))
  11807. return NTK_TypeAlias;
  11808. else if (isa<ClassTemplateDecl>(PrevDecl))
  11809. return NTK_Template;
  11810. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  11811. return NTK_TypeAliasTemplate;
  11812. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  11813. return NTK_TemplateTemplateArgument;
  11814. switch (TTK) {
  11815. case TTK_Struct:
  11816. case TTK_Interface:
  11817. case TTK_Class:
  11818. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  11819. case TTK_Union:
  11820. return NTK_NonUnion;
  11821. case TTK_Enum:
  11822. return NTK_NonEnum;
  11823. }
  11824. llvm_unreachable("invalid TTK");
  11825. }
  11826. /// \brief Determine whether a tag with a given kind is acceptable
  11827. /// as a redeclaration of the given tag declaration.
  11828. ///
  11829. /// \returns true if the new tag kind is acceptable, false otherwise.
  11830. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  11831. TagTypeKind NewTag, bool isDefinition,
  11832. SourceLocation NewTagLoc,
  11833. const IdentifierInfo *Name) {
  11834. // C++ [dcl.type.elab]p3:
  11835. // The class-key or enum keyword present in the
  11836. // elaborated-type-specifier shall agree in kind with the
  11837. // declaration to which the name in the elaborated-type-specifier
  11838. // refers. This rule also applies to the form of
  11839. // elaborated-type-specifier that declares a class-name or
  11840. // friend class since it can be construed as referring to the
  11841. // definition of the class. Thus, in any
  11842. // elaborated-type-specifier, the enum keyword shall be used to
  11843. // refer to an enumeration (7.2), the union class-key shall be
  11844. // used to refer to a union (clause 9), and either the class or
  11845. // struct class-key shall be used to refer to a class (clause 9)
  11846. // declared using the class or struct class-key.
  11847. TagTypeKind OldTag = Previous->getTagKind();
  11848. if (!isDefinition || !isClassCompatTagKind(NewTag))
  11849. if (OldTag == NewTag)
  11850. return true;
  11851. if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
  11852. // Warn about the struct/class tag mismatch.
  11853. bool isTemplate = false;
  11854. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  11855. isTemplate = Record->getDescribedClassTemplate();
  11856. if (inTemplateInstantiation()) {
  11857. // In a template instantiation, do not offer fix-its for tag mismatches
  11858. // since they usually mess up the template instead of fixing the problem.
  11859. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  11860. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11861. << getRedeclDiagFromTagKind(OldTag);
  11862. return true;
  11863. }
  11864. if (isDefinition) {
  11865. // On definitions, check previous tags and issue a fix-it for each
  11866. // one that doesn't match the current tag.
  11867. if (Previous->getDefinition()) {
  11868. // Don't suggest fix-its for redefinitions.
  11869. return true;
  11870. }
  11871. bool previousMismatch = false;
  11872. for (auto I : Previous->redecls()) {
  11873. if (I->getTagKind() != NewTag) {
  11874. if (!previousMismatch) {
  11875. previousMismatch = true;
  11876. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  11877. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11878. << getRedeclDiagFromTagKind(I->getTagKind());
  11879. }
  11880. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  11881. << getRedeclDiagFromTagKind(NewTag)
  11882. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  11883. TypeWithKeyword::getTagTypeKindName(NewTag));
  11884. }
  11885. }
  11886. return true;
  11887. }
  11888. // Check for a previous definition. If current tag and definition
  11889. // are same type, do nothing. If no definition, but disagree with
  11890. // with previous tag type, give a warning, but no fix-it.
  11891. const TagDecl *Redecl = Previous->getDefinition() ?
  11892. Previous->getDefinition() : Previous;
  11893. if (Redecl->getTagKind() == NewTag) {
  11894. return true;
  11895. }
  11896. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  11897. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11898. << getRedeclDiagFromTagKind(OldTag);
  11899. Diag(Redecl->getLocation(), diag::note_previous_use);
  11900. // If there is a previous definition, suggest a fix-it.
  11901. if (Previous->getDefinition()) {
  11902. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  11903. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  11904. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  11905. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  11906. }
  11907. return true;
  11908. }
  11909. return false;
  11910. }
  11911. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  11912. /// from an outer enclosing namespace or file scope inside a friend declaration.
  11913. /// This should provide the commented out code in the following snippet:
  11914. /// namespace N {
  11915. /// struct X;
  11916. /// namespace M {
  11917. /// struct Y { friend struct /*N::*/ X; };
  11918. /// }
  11919. /// }
  11920. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  11921. SourceLocation NameLoc) {
  11922. // While the decl is in a namespace, do repeated lookup of that name and see
  11923. // if we get the same namespace back. If we do not, continue until
  11924. // translation unit scope, at which point we have a fully qualified NNS.
  11925. SmallVector<IdentifierInfo *, 4> Namespaces;
  11926. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  11927. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  11928. // This tag should be declared in a namespace, which can only be enclosed by
  11929. // other namespaces. Bail if there's an anonymous namespace in the chain.
  11930. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  11931. if (!Namespace || Namespace->isAnonymousNamespace())
  11932. return FixItHint();
  11933. IdentifierInfo *II = Namespace->getIdentifier();
  11934. Namespaces.push_back(II);
  11935. NamedDecl *Lookup = SemaRef.LookupSingleName(
  11936. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  11937. if (Lookup == Namespace)
  11938. break;
  11939. }
  11940. // Once we have all the namespaces, reverse them to go outermost first, and
  11941. // build an NNS.
  11942. SmallString<64> Insertion;
  11943. llvm::raw_svector_ostream OS(Insertion);
  11944. if (DC->isTranslationUnit())
  11945. OS << "::";
  11946. std::reverse(Namespaces.begin(), Namespaces.end());
  11947. for (auto *II : Namespaces)
  11948. OS << II->getName() << "::";
  11949. return FixItHint::CreateInsertion(NameLoc, Insertion);
  11950. }
  11951. /// \brief Determine whether a tag originally declared in context \p OldDC can
  11952. /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
  11953. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  11954. /// using-declaration).
  11955. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  11956. DeclContext *NewDC) {
  11957. OldDC = OldDC->getRedeclContext();
  11958. NewDC = NewDC->getRedeclContext();
  11959. if (OldDC->Equals(NewDC))
  11960. return true;
  11961. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  11962. // encloses the other).
  11963. if (S.getLangOpts().MSVCCompat &&
  11964. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  11965. return true;
  11966. return false;
  11967. }
  11968. /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
  11969. /// former case, Name will be non-null. In the later case, Name will be null.
  11970. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  11971. /// reference/declaration/definition of a tag.
  11972. ///
  11973. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  11974. /// trailing-type-specifier) other than one in an alias-declaration.
  11975. ///
  11976. /// \param SkipBody If non-null, will be set to indicate if the caller should
  11977. /// skip the definition of this tag and treat it as if it were a declaration.
  11978. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  11979. SourceLocation KWLoc, CXXScopeSpec &SS,
  11980. IdentifierInfo *Name, SourceLocation NameLoc,
  11981. AttributeList *Attr, AccessSpecifier AS,
  11982. SourceLocation ModulePrivateLoc,
  11983. MultiTemplateParamsArg TemplateParameterLists,
  11984. bool &OwnedDecl, bool &IsDependent,
  11985. SourceLocation ScopedEnumKWLoc,
  11986. bool ScopedEnumUsesClassTag,
  11987. TypeResult UnderlyingType,
  11988. bool IsTypeSpecifier, bool IsTemplateParamOrArg,
  11989. SkipBodyInfo *SkipBody) {
  11990. // If this is not a definition, it must have a name.
  11991. IdentifierInfo *OrigName = Name;
  11992. assert((Name != nullptr || TUK == TUK_Definition) &&
  11993. "Nameless record must be a definition!");
  11994. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  11995. OwnedDecl = false;
  11996. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  11997. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  11998. // FIXME: Check member specializations more carefully.
  11999. bool isMemberSpecialization = false;
  12000. bool Invalid = false;
  12001. // We only need to do this matching if we have template parameters
  12002. // or a scope specifier, which also conveniently avoids this work
  12003. // for non-C++ cases.
  12004. if (TemplateParameterLists.size() > 0 ||
  12005. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  12006. if (TemplateParameterList *TemplateParams =
  12007. MatchTemplateParametersToScopeSpecifier(
  12008. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  12009. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  12010. if (Kind == TTK_Enum) {
  12011. Diag(KWLoc, diag::err_enum_template);
  12012. return nullptr;
  12013. }
  12014. if (TemplateParams->size() > 0) {
  12015. // This is a declaration or definition of a class template (which may
  12016. // be a member of another template).
  12017. if (Invalid)
  12018. return nullptr;
  12019. OwnedDecl = false;
  12020. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  12021. SS, Name, NameLoc, Attr,
  12022. TemplateParams, AS,
  12023. ModulePrivateLoc,
  12024. /*FriendLoc*/SourceLocation(),
  12025. TemplateParameterLists.size()-1,
  12026. TemplateParameterLists.data(),
  12027. SkipBody);
  12028. return Result.get();
  12029. } else {
  12030. // The "template<>" header is extraneous.
  12031. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12032. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12033. isMemberSpecialization = true;
  12034. }
  12035. }
  12036. }
  12037. // Figure out the underlying type if this a enum declaration. We need to do
  12038. // this early, because it's needed to detect if this is an incompatible
  12039. // redeclaration.
  12040. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  12041. bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
  12042. if (Kind == TTK_Enum) {
  12043. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
  12044. // No underlying type explicitly specified, or we failed to parse the
  12045. // type, default to int.
  12046. EnumUnderlying = Context.IntTy.getTypePtr();
  12047. } else if (UnderlyingType.get()) {
  12048. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  12049. // integral type; any cv-qualification is ignored.
  12050. TypeSourceInfo *TI = nullptr;
  12051. GetTypeFromParser(UnderlyingType.get(), &TI);
  12052. EnumUnderlying = TI;
  12053. if (CheckEnumUnderlyingType(TI))
  12054. // Recover by falling back to int.
  12055. EnumUnderlying = Context.IntTy.getTypePtr();
  12056. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  12057. UPPC_FixedUnderlyingType))
  12058. EnumUnderlying = Context.IntTy.getTypePtr();
  12059. } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  12060. // For MSVC ABI compatibility, unfixed enums must use an underlying type
  12061. // of 'int'. However, if this is an unfixed forward declaration, don't set
  12062. // the underlying type unless the user enables -fms-compatibility. This
  12063. // makes unfixed forward declared enums incomplete and is more conforming.
  12064. if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
  12065. EnumUnderlying = Context.IntTy.getTypePtr();
  12066. }
  12067. }
  12068. DeclContext *SearchDC = CurContext;
  12069. DeclContext *DC = CurContext;
  12070. bool isStdBadAlloc = false;
  12071. bool isStdAlignValT = false;
  12072. RedeclarationKind Redecl = forRedeclarationInCurContext();
  12073. if (TUK == TUK_Friend || TUK == TUK_Reference)
  12074. Redecl = NotForRedeclaration;
  12075. /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
  12076. /// implemented asks for structural equivalence checking, the returned decl
  12077. /// here is passed back to the parser, allowing the tag body to be parsed.
  12078. auto createTagFromNewDecl = [&]() -> TagDecl * {
  12079. assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
  12080. // If there is an identifier, use the location of the identifier as the
  12081. // location of the decl, otherwise use the location of the struct/union
  12082. // keyword.
  12083. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  12084. TagDecl *New = nullptr;
  12085. if (Kind == TTK_Enum) {
  12086. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
  12087. ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
  12088. // If this is an undefined enum, bail.
  12089. if (TUK != TUK_Definition && !Invalid)
  12090. return nullptr;
  12091. if (EnumUnderlying) {
  12092. EnumDecl *ED = cast<EnumDecl>(New);
  12093. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
  12094. ED->setIntegerTypeSourceInfo(TI);
  12095. else
  12096. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  12097. ED->setPromotionType(ED->getIntegerType());
  12098. }
  12099. } else { // struct/union
  12100. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12101. nullptr);
  12102. }
  12103. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  12104. // Add alignment attributes if necessary; these attributes are checked
  12105. // when the ASTContext lays out the structure.
  12106. //
  12107. // It is important for implementing the correct semantics that this
  12108. // happen here (in ActOnTag). The #pragma pack stack is
  12109. // maintained as a result of parser callbacks which can occur at
  12110. // many points during the parsing of a struct declaration (because
  12111. // the #pragma tokens are effectively skipped over during the
  12112. // parsing of the struct).
  12113. if (TUK == TUK_Definition) {
  12114. AddAlignmentAttributesForRecord(RD);
  12115. AddMsStructLayoutForRecord(RD);
  12116. }
  12117. }
  12118. New->setLexicalDeclContext(CurContext);
  12119. return New;
  12120. };
  12121. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  12122. if (Name && SS.isNotEmpty()) {
  12123. // We have a nested-name tag ('struct foo::bar').
  12124. // Check for invalid 'foo::'.
  12125. if (SS.isInvalid()) {
  12126. Name = nullptr;
  12127. goto CreateNewDecl;
  12128. }
  12129. // If this is a friend or a reference to a class in a dependent
  12130. // context, don't try to make a decl for it.
  12131. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  12132. DC = computeDeclContext(SS, false);
  12133. if (!DC) {
  12134. IsDependent = true;
  12135. return nullptr;
  12136. }
  12137. } else {
  12138. DC = computeDeclContext(SS, true);
  12139. if (!DC) {
  12140. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  12141. << SS.getRange();
  12142. return nullptr;
  12143. }
  12144. }
  12145. if (RequireCompleteDeclContext(SS, DC))
  12146. return nullptr;
  12147. SearchDC = DC;
  12148. // Look-up name inside 'foo::'.
  12149. LookupQualifiedName(Previous, DC);
  12150. if (Previous.isAmbiguous())
  12151. return nullptr;
  12152. if (Previous.empty()) {
  12153. // Name lookup did not find anything. However, if the
  12154. // nested-name-specifier refers to the current instantiation,
  12155. // and that current instantiation has any dependent base
  12156. // classes, we might find something at instantiation time: treat
  12157. // this as a dependent elaborated-type-specifier.
  12158. // But this only makes any sense for reference-like lookups.
  12159. if (Previous.wasNotFoundInCurrentInstantiation() &&
  12160. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  12161. IsDependent = true;
  12162. return nullptr;
  12163. }
  12164. // A tag 'foo::bar' must already exist.
  12165. Diag(NameLoc, diag::err_not_tag_in_scope)
  12166. << Kind << Name << DC << SS.getRange();
  12167. Name = nullptr;
  12168. Invalid = true;
  12169. goto CreateNewDecl;
  12170. }
  12171. } else if (Name) {
  12172. // C++14 [class.mem]p14:
  12173. // If T is the name of a class, then each of the following shall have a
  12174. // name different from T:
  12175. // -- every member of class T that is itself a type
  12176. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  12177. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  12178. return nullptr;
  12179. // If this is a named struct, check to see if there was a previous forward
  12180. // declaration or definition.
  12181. // FIXME: We're looking into outer scopes here, even when we
  12182. // shouldn't be. Doing so can result in ambiguities that we
  12183. // shouldn't be diagnosing.
  12184. LookupName(Previous, S);
  12185. // When declaring or defining a tag, ignore ambiguities introduced
  12186. // by types using'ed into this scope.
  12187. if (Previous.isAmbiguous() &&
  12188. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  12189. LookupResult::Filter F = Previous.makeFilter();
  12190. while (F.hasNext()) {
  12191. NamedDecl *ND = F.next();
  12192. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  12193. SearchDC->getRedeclContext()))
  12194. F.erase();
  12195. }
  12196. F.done();
  12197. }
  12198. // C++11 [namespace.memdef]p3:
  12199. // If the name in a friend declaration is neither qualified nor
  12200. // a template-id and the declaration is a function or an
  12201. // elaborated-type-specifier, the lookup to determine whether
  12202. // the entity has been previously declared shall not consider
  12203. // any scopes outside the innermost enclosing namespace.
  12204. //
  12205. // MSVC doesn't implement the above rule for types, so a friend tag
  12206. // declaration may be a redeclaration of a type declared in an enclosing
  12207. // scope. They do implement this rule for friend functions.
  12208. //
  12209. // Does it matter that this should be by scope instead of by
  12210. // semantic context?
  12211. if (!Previous.empty() && TUK == TUK_Friend) {
  12212. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  12213. LookupResult::Filter F = Previous.makeFilter();
  12214. bool FriendSawTagOutsideEnclosingNamespace = false;
  12215. while (F.hasNext()) {
  12216. NamedDecl *ND = F.next();
  12217. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  12218. if (DC->isFileContext() &&
  12219. !EnclosingNS->Encloses(ND->getDeclContext())) {
  12220. if (getLangOpts().MSVCCompat)
  12221. FriendSawTagOutsideEnclosingNamespace = true;
  12222. else
  12223. F.erase();
  12224. }
  12225. }
  12226. F.done();
  12227. // Diagnose this MSVC extension in the easy case where lookup would have
  12228. // unambiguously found something outside the enclosing namespace.
  12229. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  12230. NamedDecl *ND = Previous.getFoundDecl();
  12231. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  12232. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  12233. }
  12234. }
  12235. // Note: there used to be some attempt at recovery here.
  12236. if (Previous.isAmbiguous())
  12237. return nullptr;
  12238. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  12239. // FIXME: This makes sure that we ignore the contexts associated
  12240. // with C structs, unions, and enums when looking for a matching
  12241. // tag declaration or definition. See the similar lookup tweak
  12242. // in Sema::LookupName; is there a better way to deal with this?
  12243. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  12244. SearchDC = SearchDC->getParent();
  12245. }
  12246. }
  12247. if (Previous.isSingleResult() &&
  12248. Previous.getFoundDecl()->isTemplateParameter()) {
  12249. // Maybe we will complain about the shadowed template parameter.
  12250. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  12251. // Just pretend that we didn't see the previous declaration.
  12252. Previous.clear();
  12253. }
  12254. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  12255. DC->Equals(getStdNamespace())) {
  12256. if (Name->isStr("bad_alloc")) {
  12257. // This is a declaration of or a reference to "std::bad_alloc".
  12258. isStdBadAlloc = true;
  12259. // If std::bad_alloc has been implicitly declared (but made invisible to
  12260. // name lookup), fill in this implicit declaration as the previous
  12261. // declaration, so that the declarations get chained appropriately.
  12262. if (Previous.empty() && StdBadAlloc)
  12263. Previous.addDecl(getStdBadAlloc());
  12264. } else if (Name->isStr("align_val_t")) {
  12265. isStdAlignValT = true;
  12266. if (Previous.empty() && StdAlignValT)
  12267. Previous.addDecl(getStdAlignValT());
  12268. }
  12269. }
  12270. // If we didn't find a previous declaration, and this is a reference
  12271. // (or friend reference), move to the correct scope. In C++, we
  12272. // also need to do a redeclaration lookup there, just in case
  12273. // there's a shadow friend decl.
  12274. if (Name && Previous.empty() &&
  12275. (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
  12276. if (Invalid) goto CreateNewDecl;
  12277. assert(SS.isEmpty());
  12278. if (TUK == TUK_Reference || IsTemplateParamOrArg) {
  12279. // C++ [basic.scope.pdecl]p5:
  12280. // -- for an elaborated-type-specifier of the form
  12281. //
  12282. // class-key identifier
  12283. //
  12284. // if the elaborated-type-specifier is used in the
  12285. // decl-specifier-seq or parameter-declaration-clause of a
  12286. // function defined in namespace scope, the identifier is
  12287. // declared as a class-name in the namespace that contains
  12288. // the declaration; otherwise, except as a friend
  12289. // declaration, the identifier is declared in the smallest
  12290. // non-class, non-function-prototype scope that contains the
  12291. // declaration.
  12292. //
  12293. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  12294. // C structs and unions.
  12295. //
  12296. // It is an error in C++ to declare (rather than define) an enum
  12297. // type, including via an elaborated type specifier. We'll
  12298. // diagnose that later; for now, declare the enum in the same
  12299. // scope as we would have picked for any other tag type.
  12300. //
  12301. // GNU C also supports this behavior as part of its incomplete
  12302. // enum types extension, while GNU C++ does not.
  12303. //
  12304. // Find the context where we'll be declaring the tag.
  12305. // FIXME: We would like to maintain the current DeclContext as the
  12306. // lexical context,
  12307. SearchDC = getTagInjectionContext(SearchDC);
  12308. // Find the scope where we'll be declaring the tag.
  12309. S = getTagInjectionScope(S, getLangOpts());
  12310. } else {
  12311. assert(TUK == TUK_Friend);
  12312. // C++ [namespace.memdef]p3:
  12313. // If a friend declaration in a non-local class first declares a
  12314. // class or function, the friend class or function is a member of
  12315. // the innermost enclosing namespace.
  12316. SearchDC = SearchDC->getEnclosingNamespaceContext();
  12317. }
  12318. // In C++, we need to do a redeclaration lookup to properly
  12319. // diagnose some problems.
  12320. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  12321. // hidden declaration so that we don't get ambiguity errors when using a
  12322. // type declared by an elaborated-type-specifier. In C that is not correct
  12323. // and we should instead merge compatible types found by lookup.
  12324. if (getLangOpts().CPlusPlus) {
  12325. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  12326. LookupQualifiedName(Previous, SearchDC);
  12327. } else {
  12328. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  12329. LookupName(Previous, S);
  12330. }
  12331. }
  12332. // If we have a known previous declaration to use, then use it.
  12333. if (Previous.empty() && SkipBody && SkipBody->Previous)
  12334. Previous.addDecl(SkipBody->Previous);
  12335. if (!Previous.empty()) {
  12336. NamedDecl *PrevDecl = Previous.getFoundDecl();
  12337. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  12338. // It's okay to have a tag decl in the same scope as a typedef
  12339. // which hides a tag decl in the same scope. Finding this
  12340. // insanity with a redeclaration lookup can only actually happen
  12341. // in C++.
  12342. //
  12343. // This is also okay for elaborated-type-specifiers, which is
  12344. // technically forbidden by the current standard but which is
  12345. // okay according to the likely resolution of an open issue;
  12346. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  12347. if (getLangOpts().CPlusPlus) {
  12348. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  12349. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  12350. TagDecl *Tag = TT->getDecl();
  12351. if (Tag->getDeclName() == Name &&
  12352. Tag->getDeclContext()->getRedeclContext()
  12353. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  12354. PrevDecl = Tag;
  12355. Previous.clear();
  12356. Previous.addDecl(Tag);
  12357. Previous.resolveKind();
  12358. }
  12359. }
  12360. }
  12361. }
  12362. // If this is a redeclaration of a using shadow declaration, it must
  12363. // declare a tag in the same context. In MSVC mode, we allow a
  12364. // redefinition if either context is within the other.
  12365. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  12366. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  12367. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  12368. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  12369. !(OldTag && isAcceptableTagRedeclContext(
  12370. *this, OldTag->getDeclContext(), SearchDC))) {
  12371. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  12372. Diag(Shadow->getTargetDecl()->getLocation(),
  12373. diag::note_using_decl_target);
  12374. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  12375. << 0;
  12376. // Recover by ignoring the old declaration.
  12377. Previous.clear();
  12378. goto CreateNewDecl;
  12379. }
  12380. }
  12381. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  12382. // If this is a use of a previous tag, or if the tag is already declared
  12383. // in the same scope (so that the definition/declaration completes or
  12384. // rementions the tag), reuse the decl.
  12385. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  12386. isDeclInScope(DirectPrevDecl, SearchDC, S,
  12387. SS.isNotEmpty() || isMemberSpecialization)) {
  12388. // Make sure that this wasn't declared as an enum and now used as a
  12389. // struct or something similar.
  12390. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  12391. TUK == TUK_Definition, KWLoc,
  12392. Name)) {
  12393. bool SafeToContinue
  12394. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  12395. Kind != TTK_Enum);
  12396. if (SafeToContinue)
  12397. Diag(KWLoc, diag::err_use_with_wrong_tag)
  12398. << Name
  12399. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  12400. PrevTagDecl->getKindName());
  12401. else
  12402. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  12403. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  12404. if (SafeToContinue)
  12405. Kind = PrevTagDecl->getTagKind();
  12406. else {
  12407. // Recover by making this an anonymous redefinition.
  12408. Name = nullptr;
  12409. Previous.clear();
  12410. Invalid = true;
  12411. }
  12412. }
  12413. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  12414. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  12415. // If this is an elaborated-type-specifier for a scoped enumeration,
  12416. // the 'class' keyword is not necessary and not permitted.
  12417. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12418. if (ScopedEnum)
  12419. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  12420. << PrevEnum->isScoped()
  12421. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  12422. return PrevTagDecl;
  12423. }
  12424. QualType EnumUnderlyingTy;
  12425. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  12426. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  12427. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  12428. EnumUnderlyingTy = QualType(T, 0);
  12429. // All conflicts with previous declarations are recovered by
  12430. // returning the previous declaration, unless this is a definition,
  12431. // in which case we want the caller to bail out.
  12432. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  12433. ScopedEnum, EnumUnderlyingTy,
  12434. IsFixed, PrevEnum))
  12435. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  12436. }
  12437. // C++11 [class.mem]p1:
  12438. // A member shall not be declared twice in the member-specification,
  12439. // except that a nested class or member class template can be declared
  12440. // and then later defined.
  12441. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  12442. S->isDeclScope(PrevDecl)) {
  12443. Diag(NameLoc, diag::ext_member_redeclared);
  12444. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  12445. }
  12446. if (!Invalid) {
  12447. // If this is a use, just return the declaration we found, unless
  12448. // we have attributes.
  12449. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12450. if (Attr) {
  12451. // FIXME: Diagnose these attributes. For now, we create a new
  12452. // declaration to hold them.
  12453. } else if (TUK == TUK_Reference &&
  12454. (PrevTagDecl->getFriendObjectKind() ==
  12455. Decl::FOK_Undeclared ||
  12456. PrevDecl->getOwningModule() != getCurrentModule()) &&
  12457. SS.isEmpty()) {
  12458. // This declaration is a reference to an existing entity, but
  12459. // has different visibility from that entity: it either makes
  12460. // a friend visible or it makes a type visible in a new module.
  12461. // In either case, create a new declaration. We only do this if
  12462. // the declaration would have meant the same thing if no prior
  12463. // declaration were found, that is, if it was found in the same
  12464. // scope where we would have injected a declaration.
  12465. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  12466. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  12467. return PrevTagDecl;
  12468. // This is in the injected scope, create a new declaration in
  12469. // that scope.
  12470. S = getTagInjectionScope(S, getLangOpts());
  12471. } else {
  12472. return PrevTagDecl;
  12473. }
  12474. }
  12475. // Diagnose attempts to redefine a tag.
  12476. if (TUK == TUK_Definition) {
  12477. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  12478. // If we're defining a specialization and the previous definition
  12479. // is from an implicit instantiation, don't emit an error
  12480. // here; we'll catch this in the general case below.
  12481. bool IsExplicitSpecializationAfterInstantiation = false;
  12482. if (isMemberSpecialization) {
  12483. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  12484. IsExplicitSpecializationAfterInstantiation =
  12485. RD->getTemplateSpecializationKind() !=
  12486. TSK_ExplicitSpecialization;
  12487. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  12488. IsExplicitSpecializationAfterInstantiation =
  12489. ED->getTemplateSpecializationKind() !=
  12490. TSK_ExplicitSpecialization;
  12491. }
  12492. // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
  12493. // not keep more that one definition around (merge them). However,
  12494. // ensure the decl passes the structural compatibility check in
  12495. // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
  12496. NamedDecl *Hidden = nullptr;
  12497. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  12498. // There is a definition of this tag, but it is not visible. We
  12499. // explicitly make use of C++'s one definition rule here, and
  12500. // assume that this definition is identical to the hidden one
  12501. // we already have. Make the existing definition visible and
  12502. // use it in place of this one.
  12503. if (!getLangOpts().CPlusPlus) {
  12504. // Postpone making the old definition visible until after we
  12505. // complete parsing the new one and do the structural
  12506. // comparison.
  12507. SkipBody->CheckSameAsPrevious = true;
  12508. SkipBody->New = createTagFromNewDecl();
  12509. SkipBody->Previous = Hidden;
  12510. } else {
  12511. SkipBody->ShouldSkip = true;
  12512. makeMergedDefinitionVisible(Hidden);
  12513. }
  12514. return Def;
  12515. } else if (!IsExplicitSpecializationAfterInstantiation) {
  12516. // A redeclaration in function prototype scope in C isn't
  12517. // visible elsewhere, so merely issue a warning.
  12518. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  12519. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  12520. else
  12521. Diag(NameLoc, diag::err_redefinition) << Name;
  12522. notePreviousDefinition(Def,
  12523. NameLoc.isValid() ? NameLoc : KWLoc);
  12524. // If this is a redefinition, recover by making this
  12525. // struct be anonymous, which will make any later
  12526. // references get the previous definition.
  12527. Name = nullptr;
  12528. Previous.clear();
  12529. Invalid = true;
  12530. }
  12531. } else {
  12532. // If the type is currently being defined, complain
  12533. // about a nested redefinition.
  12534. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  12535. if (TD->isBeingDefined()) {
  12536. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  12537. Diag(PrevTagDecl->getLocation(),
  12538. diag::note_previous_definition);
  12539. Name = nullptr;
  12540. Previous.clear();
  12541. Invalid = true;
  12542. }
  12543. }
  12544. // Okay, this is definition of a previously declared or referenced
  12545. // tag. We're going to create a new Decl for it.
  12546. }
  12547. // Okay, we're going to make a redeclaration. If this is some kind
  12548. // of reference, make sure we build the redeclaration in the same DC
  12549. // as the original, and ignore the current access specifier.
  12550. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  12551. SearchDC = PrevTagDecl->getDeclContext();
  12552. AS = AS_none;
  12553. }
  12554. }
  12555. // If we get here we have (another) forward declaration or we
  12556. // have a definition. Just create a new decl.
  12557. } else {
  12558. // If we get here, this is a definition of a new tag type in a nested
  12559. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  12560. // new decl/type. We set PrevDecl to NULL so that the entities
  12561. // have distinct types.
  12562. Previous.clear();
  12563. }
  12564. // If we get here, we're going to create a new Decl. If PrevDecl
  12565. // is non-NULL, it's a definition of the tag declared by
  12566. // PrevDecl. If it's NULL, we have a new definition.
  12567. // Otherwise, PrevDecl is not a tag, but was found with tag
  12568. // lookup. This is only actually possible in C++, where a few
  12569. // things like templates still live in the tag namespace.
  12570. } else {
  12571. // Use a better diagnostic if an elaborated-type-specifier
  12572. // found the wrong kind of type on the first
  12573. // (non-redeclaration) lookup.
  12574. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  12575. !Previous.isForRedeclaration()) {
  12576. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  12577. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  12578. << Kind;
  12579. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  12580. Invalid = true;
  12581. // Otherwise, only diagnose if the declaration is in scope.
  12582. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  12583. SS.isNotEmpty() || isMemberSpecialization)) {
  12584. // do nothing
  12585. // Diagnose implicit declarations introduced by elaborated types.
  12586. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12587. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  12588. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  12589. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  12590. Invalid = true;
  12591. // Otherwise it's a declaration. Call out a particularly common
  12592. // case here.
  12593. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  12594. unsigned Kind = 0;
  12595. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  12596. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  12597. << Name << Kind << TND->getUnderlyingType();
  12598. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  12599. Invalid = true;
  12600. // Otherwise, diagnose.
  12601. } else {
  12602. // The tag name clashes with something else in the target scope,
  12603. // issue an error and recover by making this tag be anonymous.
  12604. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  12605. notePreviousDefinition(PrevDecl, NameLoc);
  12606. Name = nullptr;
  12607. Invalid = true;
  12608. }
  12609. // The existing declaration isn't relevant to us; we're in a
  12610. // new scope, so clear out the previous declaration.
  12611. Previous.clear();
  12612. }
  12613. }
  12614. CreateNewDecl:
  12615. TagDecl *PrevDecl = nullptr;
  12616. if (Previous.isSingleResult())
  12617. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  12618. // If there is an identifier, use the location of the identifier as the
  12619. // location of the decl, otherwise use the location of the struct/union
  12620. // keyword.
  12621. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  12622. // Otherwise, create a new declaration. If there is a previous
  12623. // declaration of the same entity, the two will be linked via
  12624. // PrevDecl.
  12625. TagDecl *New;
  12626. bool IsForwardReference = false;
  12627. if (Kind == TTK_Enum) {
  12628. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  12629. // enum X { A, B, C } D; D should chain to X.
  12630. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  12631. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  12632. ScopedEnumUsesClassTag, IsFixed);
  12633. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  12634. StdAlignValT = cast<EnumDecl>(New);
  12635. // If this is an undefined enum, warn.
  12636. if (TUK != TUK_Definition && !Invalid) {
  12637. TagDecl *Def;
  12638. if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
  12639. cast<EnumDecl>(New)->isFixed()) {
  12640. // C++0x: 7.2p2: opaque-enum-declaration.
  12641. // Conflicts are diagnosed above. Do nothing.
  12642. }
  12643. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  12644. Diag(Loc, diag::ext_forward_ref_enum_def)
  12645. << New;
  12646. Diag(Def->getLocation(), diag::note_previous_definition);
  12647. } else {
  12648. unsigned DiagID = diag::ext_forward_ref_enum;
  12649. if (getLangOpts().MSVCCompat)
  12650. DiagID = diag::ext_ms_forward_ref_enum;
  12651. else if (getLangOpts().CPlusPlus)
  12652. DiagID = diag::err_forward_ref_enum;
  12653. Diag(Loc, DiagID);
  12654. // If this is a forward-declared reference to an enumeration, make a
  12655. // note of it; we won't actually be introducing the declaration into
  12656. // the declaration context.
  12657. if (TUK == TUK_Reference)
  12658. IsForwardReference = true;
  12659. }
  12660. }
  12661. if (EnumUnderlying) {
  12662. EnumDecl *ED = cast<EnumDecl>(New);
  12663. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  12664. ED->setIntegerTypeSourceInfo(TI);
  12665. else
  12666. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  12667. ED->setPromotionType(ED->getIntegerType());
  12668. assert(ED->isComplete() && "enum with type should be complete");
  12669. }
  12670. } else {
  12671. // struct/union/class
  12672. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  12673. // struct X { int A; } D; D should chain to X.
  12674. if (getLangOpts().CPlusPlus) {
  12675. // FIXME: Look for a way to use RecordDecl for simple structs.
  12676. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12677. cast_or_null<CXXRecordDecl>(PrevDecl));
  12678. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  12679. StdBadAlloc = cast<CXXRecordDecl>(New);
  12680. } else
  12681. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12682. cast_or_null<RecordDecl>(PrevDecl));
  12683. }
  12684. // C++11 [dcl.type]p3:
  12685. // A type-specifier-seq shall not define a class or enumeration [...].
  12686. if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
  12687. TUK == TUK_Definition) {
  12688. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  12689. << Context.getTagDeclType(New);
  12690. Invalid = true;
  12691. }
  12692. if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
  12693. DC->getDeclKind() == Decl::Enum) {
  12694. Diag(New->getLocation(), diag::err_type_defined_in_enum)
  12695. << Context.getTagDeclType(New);
  12696. Invalid = true;
  12697. }
  12698. // Maybe add qualifier info.
  12699. if (SS.isNotEmpty()) {
  12700. if (SS.isSet()) {
  12701. // If this is either a declaration or a definition, check the
  12702. // nested-name-specifier against the current context.
  12703. if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
  12704. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
  12705. isMemberSpecialization))
  12706. Invalid = true;
  12707. New->setQualifierInfo(SS.getWithLocInContext(Context));
  12708. if (TemplateParameterLists.size() > 0) {
  12709. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  12710. }
  12711. }
  12712. else
  12713. Invalid = true;
  12714. }
  12715. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  12716. // Add alignment attributes if necessary; these attributes are checked when
  12717. // the ASTContext lays out the structure.
  12718. //
  12719. // It is important for implementing the correct semantics that this
  12720. // happen here (in ActOnTag). The #pragma pack stack is
  12721. // maintained as a result of parser callbacks which can occur at
  12722. // many points during the parsing of a struct declaration (because
  12723. // the #pragma tokens are effectively skipped over during the
  12724. // parsing of the struct).
  12725. if (TUK == TUK_Definition) {
  12726. AddAlignmentAttributesForRecord(RD);
  12727. AddMsStructLayoutForRecord(RD);
  12728. }
  12729. }
  12730. if (ModulePrivateLoc.isValid()) {
  12731. if (isMemberSpecialization)
  12732. Diag(New->getLocation(), diag::err_module_private_specialization)
  12733. << 2
  12734. << FixItHint::CreateRemoval(ModulePrivateLoc);
  12735. // __module_private__ does not apply to local classes. However, we only
  12736. // diagnose this as an error when the declaration specifiers are
  12737. // freestanding. Here, we just ignore the __module_private__.
  12738. else if (!SearchDC->isFunctionOrMethod())
  12739. New->setModulePrivate();
  12740. }
  12741. // If this is a specialization of a member class (of a class template),
  12742. // check the specialization.
  12743. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  12744. Invalid = true;
  12745. // If we're declaring or defining a tag in function prototype scope in C,
  12746. // note that this type can only be used within the function and add it to
  12747. // the list of decls to inject into the function definition scope.
  12748. if ((Name || Kind == TTK_Enum) &&
  12749. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  12750. if (getLangOpts().CPlusPlus) {
  12751. // C++ [dcl.fct]p6:
  12752. // Types shall not be defined in return or parameter types.
  12753. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  12754. Diag(Loc, diag::err_type_defined_in_param_type)
  12755. << Name;
  12756. Invalid = true;
  12757. }
  12758. } else if (!PrevDecl) {
  12759. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  12760. }
  12761. }
  12762. if (Invalid)
  12763. New->setInvalidDecl();
  12764. // Set the lexical context. If the tag has a C++ scope specifier, the
  12765. // lexical context will be different from the semantic context.
  12766. New->setLexicalDeclContext(CurContext);
  12767. // Mark this as a friend decl if applicable.
  12768. // In Microsoft mode, a friend declaration also acts as a forward
  12769. // declaration so we always pass true to setObjectOfFriendDecl to make
  12770. // the tag name visible.
  12771. if (TUK == TUK_Friend)
  12772. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  12773. // Set the access specifier.
  12774. if (!Invalid && SearchDC->isRecord())
  12775. SetMemberAccessSpecifier(New, PrevDecl, AS);
  12776. if (PrevDecl)
  12777. CheckRedeclarationModuleOwnership(New, PrevDecl);
  12778. if (TUK == TUK_Definition)
  12779. New->startDefinition();
  12780. if (Attr)
  12781. ProcessDeclAttributeList(S, New, Attr);
  12782. AddPragmaAttributes(S, New);
  12783. // If this has an identifier, add it to the scope stack.
  12784. if (TUK == TUK_Friend) {
  12785. // We might be replacing an existing declaration in the lookup tables;
  12786. // if so, borrow its access specifier.
  12787. if (PrevDecl)
  12788. New->setAccess(PrevDecl->getAccess());
  12789. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  12790. DC->makeDeclVisibleInContext(New);
  12791. if (Name) // can be null along some error paths
  12792. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  12793. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  12794. } else if (Name) {
  12795. S = getNonFieldDeclScope(S);
  12796. PushOnScopeChains(New, S, !IsForwardReference);
  12797. if (IsForwardReference)
  12798. SearchDC->makeDeclVisibleInContext(New);
  12799. } else {
  12800. CurContext->addDecl(New);
  12801. }
  12802. // If this is the C FILE type, notify the AST context.
  12803. if (IdentifierInfo *II = New->getIdentifier())
  12804. if (!New->isInvalidDecl() &&
  12805. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  12806. II->isStr("FILE"))
  12807. Context.setFILEDecl(New);
  12808. if (PrevDecl)
  12809. mergeDeclAttributes(New, PrevDecl);
  12810. // If there's a #pragma GCC visibility in scope, set the visibility of this
  12811. // record.
  12812. AddPushedVisibilityAttribute(New);
  12813. if (isMemberSpecialization && !New->isInvalidDecl())
  12814. CompleteMemberSpecialization(New, Previous);
  12815. OwnedDecl = true;
  12816. // In C++, don't return an invalid declaration. We can't recover well from
  12817. // the cases where we make the type anonymous.
  12818. if (Invalid && getLangOpts().CPlusPlus) {
  12819. if (New->isBeingDefined())
  12820. if (auto RD = dyn_cast<RecordDecl>(New))
  12821. RD->completeDefinition();
  12822. return nullptr;
  12823. } else {
  12824. return New;
  12825. }
  12826. }
  12827. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  12828. AdjustDeclIfTemplate(TagD);
  12829. TagDecl *Tag = cast<TagDecl>(TagD);
  12830. // Enter the tag context.
  12831. PushDeclContext(S, Tag);
  12832. ActOnDocumentableDecl(TagD);
  12833. // If there's a #pragma GCC visibility in scope, set the visibility of this
  12834. // record.
  12835. AddPushedVisibilityAttribute(Tag);
  12836. }
  12837. bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
  12838. SkipBodyInfo &SkipBody) {
  12839. if (!hasStructuralCompatLayout(Prev, SkipBody.New))
  12840. return false;
  12841. // Make the previous decl visible.
  12842. makeMergedDefinitionVisible(SkipBody.Previous);
  12843. return true;
  12844. }
  12845. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  12846. assert(isa<ObjCContainerDecl>(IDecl) &&
  12847. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  12848. DeclContext *OCD = cast<DeclContext>(IDecl);
  12849. assert(getContainingDC(OCD) == CurContext &&
  12850. "The next DeclContext should be lexically contained in the current one.");
  12851. CurContext = OCD;
  12852. return IDecl;
  12853. }
  12854. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  12855. SourceLocation FinalLoc,
  12856. bool IsFinalSpelledSealed,
  12857. SourceLocation LBraceLoc) {
  12858. AdjustDeclIfTemplate(TagD);
  12859. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  12860. FieldCollector->StartClass();
  12861. if (!Record->getIdentifier())
  12862. return;
  12863. if (FinalLoc.isValid())
  12864. Record->addAttr(new (Context)
  12865. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  12866. // C++ [class]p2:
  12867. // [...] The class-name is also inserted into the scope of the
  12868. // class itself; this is known as the injected-class-name. For
  12869. // purposes of access checking, the injected-class-name is treated
  12870. // as if it were a public member name.
  12871. CXXRecordDecl *InjectedClassName
  12872. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  12873. Record->getLocStart(), Record->getLocation(),
  12874. Record->getIdentifier(),
  12875. /*PrevDecl=*/nullptr,
  12876. /*DelayTypeCreation=*/true);
  12877. Context.getTypeDeclType(InjectedClassName, Record);
  12878. InjectedClassName->setImplicit();
  12879. InjectedClassName->setAccess(AS_public);
  12880. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  12881. InjectedClassName->setDescribedClassTemplate(Template);
  12882. PushOnScopeChains(InjectedClassName, S);
  12883. assert(InjectedClassName->isInjectedClassName() &&
  12884. "Broken injected-class-name");
  12885. }
  12886. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  12887. SourceRange BraceRange) {
  12888. AdjustDeclIfTemplate(TagD);
  12889. TagDecl *Tag = cast<TagDecl>(TagD);
  12890. Tag->setBraceRange(BraceRange);
  12891. // Make sure we "complete" the definition even it is invalid.
  12892. if (Tag->isBeingDefined()) {
  12893. assert(Tag->isInvalidDecl() && "We should already have completed it");
  12894. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  12895. RD->completeDefinition();
  12896. }
  12897. if (isa<CXXRecordDecl>(Tag)) {
  12898. FieldCollector->FinishClass();
  12899. }
  12900. // Exit this scope of this tag's definition.
  12901. PopDeclContext();
  12902. if (getCurLexicalContext()->isObjCContainer() &&
  12903. Tag->getDeclContext()->isFileContext())
  12904. Tag->setTopLevelDeclInObjCContainer();
  12905. // Notify the consumer that we've defined a tag.
  12906. if (!Tag->isInvalidDecl())
  12907. Consumer.HandleTagDeclDefinition(Tag);
  12908. }
  12909. void Sema::ActOnObjCContainerFinishDefinition() {
  12910. // Exit this scope of this interface definition.
  12911. PopDeclContext();
  12912. }
  12913. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  12914. assert(DC == CurContext && "Mismatch of container contexts");
  12915. OriginalLexicalContext = DC;
  12916. ActOnObjCContainerFinishDefinition();
  12917. }
  12918. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  12919. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  12920. OriginalLexicalContext = nullptr;
  12921. }
  12922. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  12923. AdjustDeclIfTemplate(TagD);
  12924. TagDecl *Tag = cast<TagDecl>(TagD);
  12925. Tag->setInvalidDecl();
  12926. // Make sure we "complete" the definition even it is invalid.
  12927. if (Tag->isBeingDefined()) {
  12928. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  12929. RD->completeDefinition();
  12930. }
  12931. // We're undoing ActOnTagStartDefinition here, not
  12932. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  12933. // the FieldCollector.
  12934. PopDeclContext();
  12935. }
  12936. // Note that FieldName may be null for anonymous bitfields.
  12937. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  12938. IdentifierInfo *FieldName,
  12939. QualType FieldTy, bool IsMsStruct,
  12940. Expr *BitWidth, bool *ZeroWidth) {
  12941. // Default to true; that shouldn't confuse checks for emptiness
  12942. if (ZeroWidth)
  12943. *ZeroWidth = true;
  12944. // C99 6.7.2.1p4 - verify the field type.
  12945. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  12946. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  12947. // Handle incomplete types with specific error.
  12948. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  12949. return ExprError();
  12950. if (FieldName)
  12951. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  12952. << FieldName << FieldTy << BitWidth->getSourceRange();
  12953. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  12954. << FieldTy << BitWidth->getSourceRange();
  12955. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  12956. UPPC_BitFieldWidth))
  12957. return ExprError();
  12958. // If the bit-width is type- or value-dependent, don't try to check
  12959. // it now.
  12960. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  12961. return BitWidth;
  12962. llvm::APSInt Value;
  12963. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  12964. if (ICE.isInvalid())
  12965. return ICE;
  12966. BitWidth = ICE.get();
  12967. if (Value != 0 && ZeroWidth)
  12968. *ZeroWidth = false;
  12969. // Zero-width bitfield is ok for anonymous field.
  12970. if (Value == 0 && FieldName)
  12971. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  12972. if (Value.isSigned() && Value.isNegative()) {
  12973. if (FieldName)
  12974. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  12975. << FieldName << Value.toString(10);
  12976. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  12977. << Value.toString(10);
  12978. }
  12979. if (!FieldTy->isDependentType()) {
  12980. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  12981. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  12982. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  12983. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  12984. // ABI.
  12985. bool CStdConstraintViolation =
  12986. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  12987. bool MSBitfieldViolation =
  12988. Value.ugt(TypeStorageSize) &&
  12989. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  12990. if (CStdConstraintViolation || MSBitfieldViolation) {
  12991. unsigned DiagWidth =
  12992. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  12993. if (FieldName)
  12994. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  12995. << FieldName << (unsigned)Value.getZExtValue()
  12996. << !CStdConstraintViolation << DiagWidth;
  12997. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  12998. << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
  12999. << DiagWidth;
  13000. }
  13001. // Warn on types where the user might conceivably expect to get all
  13002. // specified bits as value bits: that's all integral types other than
  13003. // 'bool'.
  13004. if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
  13005. if (FieldName)
  13006. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  13007. << FieldName << (unsigned)Value.getZExtValue()
  13008. << (unsigned)TypeWidth;
  13009. else
  13010. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  13011. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  13012. }
  13013. }
  13014. return BitWidth;
  13015. }
  13016. /// ActOnField - Each field of a C struct/union is passed into this in order
  13017. /// to create a FieldDecl object for it.
  13018. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  13019. Declarator &D, Expr *BitfieldWidth) {
  13020. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  13021. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  13022. /*InitStyle=*/ICIS_NoInit, AS_public);
  13023. return Res;
  13024. }
  13025. /// HandleField - Analyze a field of a C struct or a C++ data member.
  13026. ///
  13027. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  13028. SourceLocation DeclStart,
  13029. Declarator &D, Expr *BitWidth,
  13030. InClassInitStyle InitStyle,
  13031. AccessSpecifier AS) {
  13032. if (D.isDecompositionDeclarator()) {
  13033. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  13034. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  13035. << Decomp.getSourceRange();
  13036. return nullptr;
  13037. }
  13038. IdentifierInfo *II = D.getIdentifier();
  13039. SourceLocation Loc = DeclStart;
  13040. if (II) Loc = D.getIdentifierLoc();
  13041. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13042. QualType T = TInfo->getType();
  13043. if (getLangOpts().CPlusPlus) {
  13044. CheckExtraCXXDefaultArguments(D);
  13045. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  13046. UPPC_DataMemberType)) {
  13047. D.setInvalidType();
  13048. T = Context.IntTy;
  13049. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  13050. }
  13051. }
  13052. // TR 18037 does not allow fields to be declared with address spaces.
  13053. if (T.getQualifiers().hasAddressSpace() ||
  13054. T->isDependentAddressSpaceType() ||
  13055. T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
  13056. Diag(Loc, diag::err_field_with_address_space);
  13057. D.setInvalidType();
  13058. }
  13059. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  13060. // used as structure or union field: image, sampler, event or block types.
  13061. if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
  13062. T->isSamplerT() || T->isBlockPointerType())) {
  13063. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  13064. D.setInvalidType();
  13065. }
  13066. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  13067. if (D.getDeclSpec().isInlineSpecified())
  13068. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  13069. << getLangOpts().CPlusPlus17;
  13070. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  13071. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  13072. diag::err_invalid_thread)
  13073. << DeclSpec::getSpecifierName(TSCS);
  13074. // Check to see if this name was declared as a member previously
  13075. NamedDecl *PrevDecl = nullptr;
  13076. LookupResult Previous(*this, II, Loc, LookupMemberName,
  13077. ForVisibleRedeclaration);
  13078. LookupName(Previous, S);
  13079. switch (Previous.getResultKind()) {
  13080. case LookupResult::Found:
  13081. case LookupResult::FoundUnresolvedValue:
  13082. PrevDecl = Previous.getAsSingle<NamedDecl>();
  13083. break;
  13084. case LookupResult::FoundOverloaded:
  13085. PrevDecl = Previous.getRepresentativeDecl();
  13086. break;
  13087. case LookupResult::NotFound:
  13088. case LookupResult::NotFoundInCurrentInstantiation:
  13089. case LookupResult::Ambiguous:
  13090. break;
  13091. }
  13092. Previous.suppressDiagnostics();
  13093. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13094. // Maybe we will complain about the shadowed template parameter.
  13095. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  13096. // Just pretend that we didn't see the previous declaration.
  13097. PrevDecl = nullptr;
  13098. }
  13099. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  13100. PrevDecl = nullptr;
  13101. bool Mutable
  13102. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  13103. SourceLocation TSSL = D.getLocStart();
  13104. FieldDecl *NewFD
  13105. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  13106. TSSL, AS, PrevDecl, &D);
  13107. if (NewFD->isInvalidDecl())
  13108. Record->setInvalidDecl();
  13109. if (D.getDeclSpec().isModulePrivateSpecified())
  13110. NewFD->setModulePrivate();
  13111. if (NewFD->isInvalidDecl() && PrevDecl) {
  13112. // Don't introduce NewFD into scope; there's already something
  13113. // with the same name in the same scope.
  13114. } else if (II) {
  13115. PushOnScopeChains(NewFD, S);
  13116. } else
  13117. Record->addDecl(NewFD);
  13118. return NewFD;
  13119. }
  13120. /// \brief Build a new FieldDecl and check its well-formedness.
  13121. ///
  13122. /// This routine builds a new FieldDecl given the fields name, type,
  13123. /// record, etc. \p PrevDecl should refer to any previous declaration
  13124. /// with the same name and in the same scope as the field to be
  13125. /// created.
  13126. ///
  13127. /// \returns a new FieldDecl.
  13128. ///
  13129. /// \todo The Declarator argument is a hack. It will be removed once
  13130. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  13131. TypeSourceInfo *TInfo,
  13132. RecordDecl *Record, SourceLocation Loc,
  13133. bool Mutable, Expr *BitWidth,
  13134. InClassInitStyle InitStyle,
  13135. SourceLocation TSSL,
  13136. AccessSpecifier AS, NamedDecl *PrevDecl,
  13137. Declarator *D) {
  13138. IdentifierInfo *II = Name.getAsIdentifierInfo();
  13139. bool InvalidDecl = false;
  13140. if (D) InvalidDecl = D->isInvalidType();
  13141. // If we receive a broken type, recover by assuming 'int' and
  13142. // marking this declaration as invalid.
  13143. if (T.isNull()) {
  13144. InvalidDecl = true;
  13145. T = Context.IntTy;
  13146. }
  13147. QualType EltTy = Context.getBaseElementType(T);
  13148. if (!EltTy->isDependentType()) {
  13149. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  13150. // Fields of incomplete type force their record to be invalid.
  13151. Record->setInvalidDecl();
  13152. InvalidDecl = true;
  13153. } else {
  13154. NamedDecl *Def;
  13155. EltTy->isIncompleteType(&Def);
  13156. if (Def && Def->isInvalidDecl()) {
  13157. Record->setInvalidDecl();
  13158. InvalidDecl = true;
  13159. }
  13160. }
  13161. }
  13162. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  13163. if (BitWidth && getLangOpts().OpenCL) {
  13164. Diag(Loc, diag::err_opencl_bitfields);
  13165. InvalidDecl = true;
  13166. }
  13167. // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
  13168. if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
  13169. T.hasQualifiers()) {
  13170. InvalidDecl = true;
  13171. Diag(Loc, diag::err_anon_bitfield_qualifiers);
  13172. }
  13173. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  13174. // than a variably modified type.
  13175. if (!InvalidDecl && T->isVariablyModifiedType()) {
  13176. bool SizeIsNegative;
  13177. llvm::APSInt Oversized;
  13178. TypeSourceInfo *FixedTInfo =
  13179. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  13180. SizeIsNegative,
  13181. Oversized);
  13182. if (FixedTInfo) {
  13183. Diag(Loc, diag::warn_illegal_constant_array_size);
  13184. TInfo = FixedTInfo;
  13185. T = FixedTInfo->getType();
  13186. } else {
  13187. if (SizeIsNegative)
  13188. Diag(Loc, diag::err_typecheck_negative_array_size);
  13189. else if (Oversized.getBoolValue())
  13190. Diag(Loc, diag::err_array_too_large)
  13191. << Oversized.toString(10);
  13192. else
  13193. Diag(Loc, diag::err_typecheck_field_variable_size);
  13194. InvalidDecl = true;
  13195. }
  13196. }
  13197. // Fields can not have abstract class types
  13198. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  13199. diag::err_abstract_type_in_decl,
  13200. AbstractFieldType))
  13201. InvalidDecl = true;
  13202. bool ZeroWidth = false;
  13203. if (InvalidDecl)
  13204. BitWidth = nullptr;
  13205. // If this is declared as a bit-field, check the bit-field.
  13206. if (BitWidth) {
  13207. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  13208. &ZeroWidth).get();
  13209. if (!BitWidth) {
  13210. InvalidDecl = true;
  13211. BitWidth = nullptr;
  13212. ZeroWidth = false;
  13213. }
  13214. }
  13215. // Check that 'mutable' is consistent with the type of the declaration.
  13216. if (!InvalidDecl && Mutable) {
  13217. unsigned DiagID = 0;
  13218. if (T->isReferenceType())
  13219. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  13220. : diag::err_mutable_reference;
  13221. else if (T.isConstQualified())
  13222. DiagID = diag::err_mutable_const;
  13223. if (DiagID) {
  13224. SourceLocation ErrLoc = Loc;
  13225. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  13226. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  13227. Diag(ErrLoc, DiagID);
  13228. if (DiagID != diag::ext_mutable_reference) {
  13229. Mutable = false;
  13230. InvalidDecl = true;
  13231. }
  13232. }
  13233. }
  13234. // C++11 [class.union]p8 (DR1460):
  13235. // At most one variant member of a union may have a
  13236. // brace-or-equal-initializer.
  13237. if (InitStyle != ICIS_NoInit)
  13238. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  13239. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  13240. BitWidth, Mutable, InitStyle);
  13241. if (InvalidDecl)
  13242. NewFD->setInvalidDecl();
  13243. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  13244. Diag(Loc, diag::err_duplicate_member) << II;
  13245. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  13246. NewFD->setInvalidDecl();
  13247. }
  13248. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  13249. if (Record->isUnion()) {
  13250. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  13251. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  13252. if (RDecl->getDefinition()) {
  13253. // C++ [class.union]p1: An object of a class with a non-trivial
  13254. // constructor, a non-trivial copy constructor, a non-trivial
  13255. // destructor, or a non-trivial copy assignment operator
  13256. // cannot be a member of a union, nor can an array of such
  13257. // objects.
  13258. if (CheckNontrivialField(NewFD))
  13259. NewFD->setInvalidDecl();
  13260. }
  13261. }
  13262. // C++ [class.union]p1: If a union contains a member of reference type,
  13263. // the program is ill-formed, except when compiling with MSVC extensions
  13264. // enabled.
  13265. if (EltTy->isReferenceType()) {
  13266. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  13267. diag::ext_union_member_of_reference_type :
  13268. diag::err_union_member_of_reference_type)
  13269. << NewFD->getDeclName() << EltTy;
  13270. if (!getLangOpts().MicrosoftExt)
  13271. NewFD->setInvalidDecl();
  13272. }
  13273. }
  13274. }
  13275. // FIXME: We need to pass in the attributes given an AST
  13276. // representation, not a parser representation.
  13277. if (D) {
  13278. // FIXME: The current scope is almost... but not entirely... correct here.
  13279. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  13280. if (NewFD->hasAttrs())
  13281. CheckAlignasUnderalignment(NewFD);
  13282. }
  13283. // In auto-retain/release, infer strong retension for fields of
  13284. // retainable type.
  13285. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  13286. NewFD->setInvalidDecl();
  13287. if (T.isObjCGCWeak())
  13288. Diag(Loc, diag::warn_attribute_weak_on_field);
  13289. NewFD->setAccess(AS);
  13290. return NewFD;
  13291. }
  13292. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  13293. assert(FD);
  13294. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  13295. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  13296. return false;
  13297. QualType EltTy = Context.getBaseElementType(FD->getType());
  13298. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  13299. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  13300. if (RDecl->getDefinition()) {
  13301. // We check for copy constructors before constructors
  13302. // because otherwise we'll never get complaints about
  13303. // copy constructors.
  13304. CXXSpecialMember member = CXXInvalid;
  13305. // We're required to check for any non-trivial constructors. Since the
  13306. // implicit default constructor is suppressed if there are any
  13307. // user-declared constructors, we just need to check that there is a
  13308. // trivial default constructor and a trivial copy constructor. (We don't
  13309. // worry about move constructors here, since this is a C++98 check.)
  13310. if (RDecl->hasNonTrivialCopyConstructor())
  13311. member = CXXCopyConstructor;
  13312. else if (!RDecl->hasTrivialDefaultConstructor())
  13313. member = CXXDefaultConstructor;
  13314. else if (RDecl->hasNonTrivialCopyAssignment())
  13315. member = CXXCopyAssignment;
  13316. else if (RDecl->hasNonTrivialDestructor())
  13317. member = CXXDestructor;
  13318. if (member != CXXInvalid) {
  13319. if (!getLangOpts().CPlusPlus11 &&
  13320. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  13321. // Objective-C++ ARC: it is an error to have a non-trivial field of
  13322. // a union. However, system headers in Objective-C programs
  13323. // occasionally have Objective-C lifetime objects within unions,
  13324. // and rather than cause the program to fail, we make those
  13325. // members unavailable.
  13326. SourceLocation Loc = FD->getLocation();
  13327. if (getSourceManager().isInSystemHeader(Loc)) {
  13328. if (!FD->hasAttr<UnavailableAttr>())
  13329. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  13330. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  13331. return false;
  13332. }
  13333. }
  13334. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  13335. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  13336. diag::err_illegal_union_or_anon_struct_member)
  13337. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  13338. DiagnoseNontrivial(RDecl, member);
  13339. return !getLangOpts().CPlusPlus11;
  13340. }
  13341. }
  13342. }
  13343. return false;
  13344. }
  13345. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  13346. /// AST enum value.
  13347. static ObjCIvarDecl::AccessControl
  13348. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  13349. switch (ivarVisibility) {
  13350. default: llvm_unreachable("Unknown visitibility kind");
  13351. case tok::objc_private: return ObjCIvarDecl::Private;
  13352. case tok::objc_public: return ObjCIvarDecl::Public;
  13353. case tok::objc_protected: return ObjCIvarDecl::Protected;
  13354. case tok::objc_package: return ObjCIvarDecl::Package;
  13355. }
  13356. }
  13357. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  13358. /// in order to create an IvarDecl object for it.
  13359. Decl *Sema::ActOnIvar(Scope *S,
  13360. SourceLocation DeclStart,
  13361. Declarator &D, Expr *BitfieldWidth,
  13362. tok::ObjCKeywordKind Visibility) {
  13363. IdentifierInfo *II = D.getIdentifier();
  13364. Expr *BitWidth = (Expr*)BitfieldWidth;
  13365. SourceLocation Loc = DeclStart;
  13366. if (II) Loc = D.getIdentifierLoc();
  13367. // FIXME: Unnamed fields can be handled in various different ways, for
  13368. // example, unnamed unions inject all members into the struct namespace!
  13369. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13370. QualType T = TInfo->getType();
  13371. if (BitWidth) {
  13372. // 6.7.2.1p3, 6.7.2.1p4
  13373. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  13374. if (!BitWidth)
  13375. D.setInvalidType();
  13376. } else {
  13377. // Not a bitfield.
  13378. // validate II.
  13379. }
  13380. if (T->isReferenceType()) {
  13381. Diag(Loc, diag::err_ivar_reference_type);
  13382. D.setInvalidType();
  13383. }
  13384. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  13385. // than a variably modified type.
  13386. else if (T->isVariablyModifiedType()) {
  13387. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  13388. D.setInvalidType();
  13389. }
  13390. // Get the visibility (access control) for this ivar.
  13391. ObjCIvarDecl::AccessControl ac =
  13392. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  13393. : ObjCIvarDecl::None;
  13394. // Must set ivar's DeclContext to its enclosing interface.
  13395. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  13396. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  13397. return nullptr;
  13398. ObjCContainerDecl *EnclosingContext;
  13399. if (ObjCImplementationDecl *IMPDecl =
  13400. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  13401. if (LangOpts.ObjCRuntime.isFragile()) {
  13402. // Case of ivar declared in an implementation. Context is that of its class.
  13403. EnclosingContext = IMPDecl->getClassInterface();
  13404. assert(EnclosingContext && "Implementation has no class interface!");
  13405. }
  13406. else
  13407. EnclosingContext = EnclosingDecl;
  13408. } else {
  13409. if (ObjCCategoryDecl *CDecl =
  13410. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  13411. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  13412. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  13413. return nullptr;
  13414. }
  13415. }
  13416. EnclosingContext = EnclosingDecl;
  13417. }
  13418. // Construct the decl.
  13419. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  13420. DeclStart, Loc, II, T,
  13421. TInfo, ac, (Expr *)BitfieldWidth);
  13422. if (II) {
  13423. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  13424. ForVisibleRedeclaration);
  13425. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  13426. && !isa<TagDecl>(PrevDecl)) {
  13427. Diag(Loc, diag::err_duplicate_member) << II;
  13428. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  13429. NewID->setInvalidDecl();
  13430. }
  13431. }
  13432. // Process attributes attached to the ivar.
  13433. ProcessDeclAttributes(S, NewID, D);
  13434. if (D.isInvalidType())
  13435. NewID->setInvalidDecl();
  13436. // In ARC, infer 'retaining' for ivars of retainable type.
  13437. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  13438. NewID->setInvalidDecl();
  13439. if (D.getDeclSpec().isModulePrivateSpecified())
  13440. NewID->setModulePrivate();
  13441. if (II) {
  13442. // FIXME: When interfaces are DeclContexts, we'll need to add
  13443. // these to the interface.
  13444. S->AddDecl(NewID);
  13445. IdResolver.AddDecl(NewID);
  13446. }
  13447. if (LangOpts.ObjCRuntime.isNonFragile() &&
  13448. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  13449. Diag(Loc, diag::warn_ivars_in_interface);
  13450. return NewID;
  13451. }
  13452. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  13453. /// class and class extensions. For every class \@interface and class
  13454. /// extension \@interface, if the last ivar is a bitfield of any type,
  13455. /// then add an implicit `char :0` ivar to the end of that interface.
  13456. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  13457. SmallVectorImpl<Decl *> &AllIvarDecls) {
  13458. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  13459. return;
  13460. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  13461. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  13462. if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
  13463. return;
  13464. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  13465. if (!ID) {
  13466. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  13467. if (!CD->IsClassExtension())
  13468. return;
  13469. }
  13470. // No need to add this to end of @implementation.
  13471. else
  13472. return;
  13473. }
  13474. // All conditions are met. Add a new bitfield to the tail end of ivars.
  13475. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  13476. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  13477. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  13478. DeclLoc, DeclLoc, nullptr,
  13479. Context.CharTy,
  13480. Context.getTrivialTypeSourceInfo(Context.CharTy,
  13481. DeclLoc),
  13482. ObjCIvarDecl::Private, BW,
  13483. true);
  13484. AllIvarDecls.push_back(Ivar);
  13485. }
  13486. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  13487. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  13488. SourceLocation RBrac, AttributeList *Attr) {
  13489. assert(EnclosingDecl && "missing record or interface decl");
  13490. // If this is an Objective-C @implementation or category and we have
  13491. // new fields here we should reset the layout of the interface since
  13492. // it will now change.
  13493. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  13494. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  13495. switch (DC->getKind()) {
  13496. default: break;
  13497. case Decl::ObjCCategory:
  13498. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  13499. break;
  13500. case Decl::ObjCImplementation:
  13501. Context.
  13502. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  13503. break;
  13504. }
  13505. }
  13506. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  13507. // Start counting up the number of named members; make sure to include
  13508. // members of anonymous structs and unions in the total.
  13509. unsigned NumNamedMembers = 0;
  13510. if (Record) {
  13511. for (const auto *I : Record->decls()) {
  13512. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  13513. if (IFD->getDeclName())
  13514. ++NumNamedMembers;
  13515. }
  13516. }
  13517. // Verify that all the fields are okay.
  13518. SmallVector<FieldDecl*, 32> RecFields;
  13519. bool ObjCFieldLifetimeErrReported = false;
  13520. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  13521. i != end; ++i) {
  13522. FieldDecl *FD = cast<FieldDecl>(*i);
  13523. // Get the type for the field.
  13524. const Type *FDTy = FD->getType().getTypePtr();
  13525. if (!FD->isAnonymousStructOrUnion()) {
  13526. // Remember all fields written by the user.
  13527. RecFields.push_back(FD);
  13528. }
  13529. // If the field is already invalid for some reason, don't emit more
  13530. // diagnostics about it.
  13531. if (FD->isInvalidDecl()) {
  13532. EnclosingDecl->setInvalidDecl();
  13533. continue;
  13534. }
  13535. // C99 6.7.2.1p2:
  13536. // A structure or union shall not contain a member with
  13537. // incomplete or function type (hence, a structure shall not
  13538. // contain an instance of itself, but may contain a pointer to
  13539. // an instance of itself), except that the last member of a
  13540. // structure with more than one named member may have incomplete
  13541. // array type; such a structure (and any union containing,
  13542. // possibly recursively, a member that is such a structure)
  13543. // shall not be a member of a structure or an element of an
  13544. // array.
  13545. bool IsLastField = (i + 1 == Fields.end());
  13546. if (FDTy->isFunctionType()) {
  13547. // Field declared as a function.
  13548. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  13549. << FD->getDeclName();
  13550. FD->setInvalidDecl();
  13551. EnclosingDecl->setInvalidDecl();
  13552. continue;
  13553. } else if (FDTy->isIncompleteArrayType() &&
  13554. (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
  13555. if (Record) {
  13556. // Flexible array member.
  13557. // Microsoft and g++ is more permissive regarding flexible array.
  13558. // It will accept flexible array in union and also
  13559. // as the sole element of a struct/class.
  13560. unsigned DiagID = 0;
  13561. if (!Record->isUnion() && !IsLastField) {
  13562. Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
  13563. << FD->getDeclName() << FD->getType() << Record->getTagKind();
  13564. Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
  13565. FD->setInvalidDecl();
  13566. EnclosingDecl->setInvalidDecl();
  13567. continue;
  13568. } else if (Record->isUnion())
  13569. DiagID = getLangOpts().MicrosoftExt
  13570. ? diag::ext_flexible_array_union_ms
  13571. : getLangOpts().CPlusPlus
  13572. ? diag::ext_flexible_array_union_gnu
  13573. : diag::err_flexible_array_union;
  13574. else if (NumNamedMembers < 1)
  13575. DiagID = getLangOpts().MicrosoftExt
  13576. ? diag::ext_flexible_array_empty_aggregate_ms
  13577. : getLangOpts().CPlusPlus
  13578. ? diag::ext_flexible_array_empty_aggregate_gnu
  13579. : diag::err_flexible_array_empty_aggregate;
  13580. if (DiagID)
  13581. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  13582. << Record->getTagKind();
  13583. // While the layout of types that contain virtual bases is not specified
  13584. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  13585. // virtual bases after the derived members. This would make a flexible
  13586. // array member declared at the end of an object not adjacent to the end
  13587. // of the type.
  13588. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
  13589. if (RD->getNumVBases() != 0)
  13590. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  13591. << FD->getDeclName() << Record->getTagKind();
  13592. if (!getLangOpts().C99)
  13593. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  13594. << FD->getDeclName() << Record->getTagKind();
  13595. // If the element type has a non-trivial destructor, we would not
  13596. // implicitly destroy the elements, so disallow it for now.
  13597. //
  13598. // FIXME: GCC allows this. We should probably either implicitly delete
  13599. // the destructor of the containing class, or just allow this.
  13600. QualType BaseElem = Context.getBaseElementType(FD->getType());
  13601. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  13602. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  13603. << FD->getDeclName() << FD->getType();
  13604. FD->setInvalidDecl();
  13605. EnclosingDecl->setInvalidDecl();
  13606. continue;
  13607. }
  13608. // Okay, we have a legal flexible array member at the end of the struct.
  13609. Record->setHasFlexibleArrayMember(true);
  13610. } else {
  13611. // In ObjCContainerDecl ivars with incomplete array type are accepted,
  13612. // unless they are followed by another ivar. That check is done
  13613. // elsewhere, after synthesized ivars are known.
  13614. }
  13615. } else if (!FDTy->isDependentType() &&
  13616. RequireCompleteType(FD->getLocation(), FD->getType(),
  13617. diag::err_field_incomplete)) {
  13618. // Incomplete type
  13619. FD->setInvalidDecl();
  13620. EnclosingDecl->setInvalidDecl();
  13621. continue;
  13622. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  13623. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  13624. // A type which contains a flexible array member is considered to be a
  13625. // flexible array member.
  13626. Record->setHasFlexibleArrayMember(true);
  13627. if (!Record->isUnion()) {
  13628. // If this is a struct/class and this is not the last element, reject
  13629. // it. Note that GCC supports variable sized arrays in the middle of
  13630. // structures.
  13631. if (!IsLastField)
  13632. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  13633. << FD->getDeclName() << FD->getType();
  13634. else {
  13635. // We support flexible arrays at the end of structs in
  13636. // other structs as an extension.
  13637. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  13638. << FD->getDeclName();
  13639. }
  13640. }
  13641. }
  13642. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  13643. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  13644. diag::err_abstract_type_in_decl,
  13645. AbstractIvarType)) {
  13646. // Ivars can not have abstract class types
  13647. FD->setInvalidDecl();
  13648. }
  13649. if (Record && FDTTy->getDecl()->hasObjectMember())
  13650. Record->setHasObjectMember(true);
  13651. if (Record && FDTTy->getDecl()->hasVolatileMember())
  13652. Record->setHasVolatileMember(true);
  13653. } else if (FDTy->isObjCObjectType()) {
  13654. /// A field cannot be an Objective-c object
  13655. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  13656. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  13657. QualType T = Context.getObjCObjectPointerType(FD->getType());
  13658. FD->setType(T);
  13659. } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  13660. Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) {
  13661. // It's an error in ARC or Weak if a field has lifetime.
  13662. // We don't want to report this in a system header, though,
  13663. // so we just make the field unavailable.
  13664. // FIXME: that's really not sufficient; we need to make the type
  13665. // itself invalid to, say, initialize or copy.
  13666. QualType T = FD->getType();
  13667. if (T.hasNonTrivialObjCLifetime()) {
  13668. SourceLocation loc = FD->getLocation();
  13669. if (getSourceManager().isInSystemHeader(loc)) {
  13670. if (!FD->hasAttr<UnavailableAttr>()) {
  13671. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  13672. UnavailableAttr::IR_ARCFieldWithOwnership, loc));
  13673. }
  13674. } else {
  13675. Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
  13676. << T->isBlockPointerType() << Record->getTagKind();
  13677. }
  13678. ObjCFieldLifetimeErrReported = true;
  13679. }
  13680. } else if (getLangOpts().ObjC1 &&
  13681. getLangOpts().getGC() != LangOptions::NonGC &&
  13682. Record && !Record->hasObjectMember()) {
  13683. if (FD->getType()->isObjCObjectPointerType() ||
  13684. FD->getType().isObjCGCStrong())
  13685. Record->setHasObjectMember(true);
  13686. else if (Context.getAsArrayType(FD->getType())) {
  13687. QualType BaseType = Context.getBaseElementType(FD->getType());
  13688. if (BaseType->isRecordType() &&
  13689. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  13690. Record->setHasObjectMember(true);
  13691. else if (BaseType->isObjCObjectPointerType() ||
  13692. BaseType.isObjCGCStrong())
  13693. Record->setHasObjectMember(true);
  13694. }
  13695. }
  13696. if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
  13697. QualType FT = FD->getType();
  13698. if (FT.isNonTrivialToPrimitiveDefaultInitialize())
  13699. Record->setNonTrivialToPrimitiveDefaultInitialize(true);
  13700. QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
  13701. if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
  13702. Record->setNonTrivialToPrimitiveCopy(true);
  13703. if (FT.isDestructedType()) {
  13704. Record->setNonTrivialToPrimitiveDestroy(true);
  13705. Record->setParamDestroyedInCallee(true);
  13706. }
  13707. if (const auto *RT = FT->getAs<RecordType>()) {
  13708. if (RT->getDecl()->getArgPassingRestrictions() ==
  13709. RecordDecl::APK_CanNeverPassInRegs)
  13710. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  13711. } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
  13712. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  13713. }
  13714. if (Record && FD->getType().isVolatileQualified())
  13715. Record->setHasVolatileMember(true);
  13716. // Keep track of the number of named members.
  13717. if (FD->getIdentifier())
  13718. ++NumNamedMembers;
  13719. }
  13720. // Okay, we successfully defined 'Record'.
  13721. if (Record) {
  13722. bool Completed = false;
  13723. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  13724. if (!CXXRecord->isInvalidDecl()) {
  13725. // Set access bits correctly on the directly-declared conversions.
  13726. for (CXXRecordDecl::conversion_iterator
  13727. I = CXXRecord->conversion_begin(),
  13728. E = CXXRecord->conversion_end(); I != E; ++I)
  13729. I.setAccess((*I)->getAccess());
  13730. }
  13731. if (!CXXRecord->isDependentType()) {
  13732. if (CXXRecord->hasUserDeclaredDestructor()) {
  13733. // Adjust user-defined destructor exception spec.
  13734. if (getLangOpts().CPlusPlus11)
  13735. AdjustDestructorExceptionSpec(CXXRecord,
  13736. CXXRecord->getDestructor());
  13737. }
  13738. // Add any implicitly-declared members to this class.
  13739. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  13740. if (!CXXRecord->isInvalidDecl()) {
  13741. // If we have virtual base classes, we may end up finding multiple
  13742. // final overriders for a given virtual function. Check for this
  13743. // problem now.
  13744. if (CXXRecord->getNumVBases()) {
  13745. CXXFinalOverriderMap FinalOverriders;
  13746. CXXRecord->getFinalOverriders(FinalOverriders);
  13747. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  13748. MEnd = FinalOverriders.end();
  13749. M != MEnd; ++M) {
  13750. for (OverridingMethods::iterator SO = M->second.begin(),
  13751. SOEnd = M->second.end();
  13752. SO != SOEnd; ++SO) {
  13753. assert(SO->second.size() > 0 &&
  13754. "Virtual function without overriding functions?");
  13755. if (SO->second.size() == 1)
  13756. continue;
  13757. // C++ [class.virtual]p2:
  13758. // In a derived class, if a virtual member function of a base
  13759. // class subobject has more than one final overrider the
  13760. // program is ill-formed.
  13761. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  13762. << (const NamedDecl *)M->first << Record;
  13763. Diag(M->first->getLocation(),
  13764. diag::note_overridden_virtual_function);
  13765. for (OverridingMethods::overriding_iterator
  13766. OM = SO->second.begin(),
  13767. OMEnd = SO->second.end();
  13768. OM != OMEnd; ++OM)
  13769. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  13770. << (const NamedDecl *)M->first << OM->Method->getParent();
  13771. Record->setInvalidDecl();
  13772. }
  13773. }
  13774. CXXRecord->completeDefinition(&FinalOverriders);
  13775. Completed = true;
  13776. }
  13777. }
  13778. }
  13779. }
  13780. if (!Completed)
  13781. Record->completeDefinition();
  13782. // We may have deferred checking for a deleted destructor. Check now.
  13783. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  13784. auto *Dtor = CXXRecord->getDestructor();
  13785. if (Dtor && Dtor->isImplicit() &&
  13786. ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
  13787. CXXRecord->setImplicitDestructorIsDeleted();
  13788. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  13789. }
  13790. }
  13791. if (Record->hasAttrs()) {
  13792. CheckAlignasUnderalignment(Record);
  13793. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  13794. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  13795. IA->getRange(), IA->getBestCase(),
  13796. IA->getSemanticSpelling());
  13797. }
  13798. // Check if the structure/union declaration is a type that can have zero
  13799. // size in C. For C this is a language extension, for C++ it may cause
  13800. // compatibility problems.
  13801. bool CheckForZeroSize;
  13802. if (!getLangOpts().CPlusPlus) {
  13803. CheckForZeroSize = true;
  13804. } else {
  13805. // For C++ filter out types that cannot be referenced in C code.
  13806. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  13807. CheckForZeroSize =
  13808. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  13809. !CXXRecord->isDependentType() &&
  13810. CXXRecord->isCLike();
  13811. }
  13812. if (CheckForZeroSize) {
  13813. bool ZeroSize = true;
  13814. bool IsEmpty = true;
  13815. unsigned NonBitFields = 0;
  13816. for (RecordDecl::field_iterator I = Record->field_begin(),
  13817. E = Record->field_end();
  13818. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  13819. IsEmpty = false;
  13820. if (I->isUnnamedBitfield()) {
  13821. if (!I->isZeroLengthBitField(Context))
  13822. ZeroSize = false;
  13823. } else {
  13824. ++NonBitFields;
  13825. QualType FieldType = I->getType();
  13826. if (FieldType->isIncompleteType() ||
  13827. !Context.getTypeSizeInChars(FieldType).isZero())
  13828. ZeroSize = false;
  13829. }
  13830. }
  13831. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  13832. // allowed in C++, but warn if its declaration is inside
  13833. // extern "C" block.
  13834. if (ZeroSize) {
  13835. Diag(RecLoc, getLangOpts().CPlusPlus ?
  13836. diag::warn_zero_size_struct_union_in_extern_c :
  13837. diag::warn_zero_size_struct_union_compat)
  13838. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  13839. }
  13840. // Structs without named members are extension in C (C99 6.7.2.1p7),
  13841. // but are accepted by GCC.
  13842. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  13843. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  13844. diag::ext_no_named_members_in_struct_union)
  13845. << Record->isUnion();
  13846. }
  13847. }
  13848. } else {
  13849. ObjCIvarDecl **ClsFields =
  13850. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  13851. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  13852. ID->setEndOfDefinitionLoc(RBrac);
  13853. // Add ivar's to class's DeclContext.
  13854. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  13855. ClsFields[i]->setLexicalDeclContext(ID);
  13856. ID->addDecl(ClsFields[i]);
  13857. }
  13858. // Must enforce the rule that ivars in the base classes may not be
  13859. // duplicates.
  13860. if (ID->getSuperClass())
  13861. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  13862. } else if (ObjCImplementationDecl *IMPDecl =
  13863. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  13864. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  13865. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  13866. // Ivar declared in @implementation never belongs to the implementation.
  13867. // Only it is in implementation's lexical context.
  13868. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  13869. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  13870. IMPDecl->setIvarLBraceLoc(LBrac);
  13871. IMPDecl->setIvarRBraceLoc(RBrac);
  13872. } else if (ObjCCategoryDecl *CDecl =
  13873. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  13874. // case of ivars in class extension; all other cases have been
  13875. // reported as errors elsewhere.
  13876. // FIXME. Class extension does not have a LocEnd field.
  13877. // CDecl->setLocEnd(RBrac);
  13878. // Add ivar's to class extension's DeclContext.
  13879. // Diagnose redeclaration of private ivars.
  13880. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  13881. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  13882. if (IDecl) {
  13883. if (const ObjCIvarDecl *ClsIvar =
  13884. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  13885. Diag(ClsFields[i]->getLocation(),
  13886. diag::err_duplicate_ivar_declaration);
  13887. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  13888. continue;
  13889. }
  13890. for (const auto *Ext : IDecl->known_extensions()) {
  13891. if (const ObjCIvarDecl *ClsExtIvar
  13892. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  13893. Diag(ClsFields[i]->getLocation(),
  13894. diag::err_duplicate_ivar_declaration);
  13895. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  13896. continue;
  13897. }
  13898. }
  13899. }
  13900. ClsFields[i]->setLexicalDeclContext(CDecl);
  13901. CDecl->addDecl(ClsFields[i]);
  13902. }
  13903. CDecl->setIvarLBraceLoc(LBrac);
  13904. CDecl->setIvarRBraceLoc(RBrac);
  13905. }
  13906. }
  13907. if (Attr)
  13908. ProcessDeclAttributeList(S, Record, Attr);
  13909. }
  13910. /// \brief Determine whether the given integral value is representable within
  13911. /// the given type T.
  13912. static bool isRepresentableIntegerValue(ASTContext &Context,
  13913. llvm::APSInt &Value,
  13914. QualType T) {
  13915. assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
  13916. "Integral type required!");
  13917. unsigned BitWidth = Context.getIntWidth(T);
  13918. if (Value.isUnsigned() || Value.isNonNegative()) {
  13919. if (T->isSignedIntegerOrEnumerationType())
  13920. --BitWidth;
  13921. return Value.getActiveBits() <= BitWidth;
  13922. }
  13923. return Value.getMinSignedBits() <= BitWidth;
  13924. }
  13925. // \brief Given an integral type, return the next larger integral type
  13926. // (or a NULL type of no such type exists).
  13927. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  13928. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  13929. // enum checking below.
  13930. assert((T->isIntegralType(Context) ||
  13931. T->isEnumeralType()) && "Integral type required!");
  13932. const unsigned NumTypes = 4;
  13933. QualType SignedIntegralTypes[NumTypes] = {
  13934. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  13935. };
  13936. QualType UnsignedIntegralTypes[NumTypes] = {
  13937. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  13938. Context.UnsignedLongLongTy
  13939. };
  13940. unsigned BitWidth = Context.getTypeSize(T);
  13941. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  13942. : UnsignedIntegralTypes;
  13943. for (unsigned I = 0; I != NumTypes; ++I)
  13944. if (Context.getTypeSize(Types[I]) > BitWidth)
  13945. return Types[I];
  13946. return QualType();
  13947. }
  13948. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  13949. EnumConstantDecl *LastEnumConst,
  13950. SourceLocation IdLoc,
  13951. IdentifierInfo *Id,
  13952. Expr *Val) {
  13953. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  13954. llvm::APSInt EnumVal(IntWidth);
  13955. QualType EltTy;
  13956. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  13957. Val = nullptr;
  13958. if (Val)
  13959. Val = DefaultLvalueConversion(Val).get();
  13960. if (Val) {
  13961. if (Enum->isDependentType() || Val->isTypeDependent())
  13962. EltTy = Context.DependentTy;
  13963. else {
  13964. if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
  13965. !getLangOpts().MSVCCompat) {
  13966. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  13967. // constant-expression in the enumerator-definition shall be a converted
  13968. // constant expression of the underlying type.
  13969. EltTy = Enum->getIntegerType();
  13970. ExprResult Converted =
  13971. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  13972. CCEK_Enumerator);
  13973. if (Converted.isInvalid())
  13974. Val = nullptr;
  13975. else
  13976. Val = Converted.get();
  13977. } else if (!Val->isValueDependent() &&
  13978. !(Val = VerifyIntegerConstantExpression(Val,
  13979. &EnumVal).get())) {
  13980. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  13981. } else {
  13982. if (Enum->isComplete()) {
  13983. EltTy = Enum->getIntegerType();
  13984. // In Obj-C and Microsoft mode, require the enumeration value to be
  13985. // representable in the underlying type of the enumeration. In C++11,
  13986. // we perform a non-narrowing conversion as part of converted constant
  13987. // expression checking.
  13988. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  13989. if (getLangOpts().MSVCCompat) {
  13990. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  13991. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  13992. } else
  13993. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  13994. } else
  13995. Val = ImpCastExprToType(Val, EltTy,
  13996. EltTy->isBooleanType() ?
  13997. CK_IntegralToBoolean : CK_IntegralCast)
  13998. .get();
  13999. } else if (getLangOpts().CPlusPlus) {
  14000. // C++11 [dcl.enum]p5:
  14001. // If the underlying type is not fixed, the type of each enumerator
  14002. // is the type of its initializing value:
  14003. // - If an initializer is specified for an enumerator, the
  14004. // initializing value has the same type as the expression.
  14005. EltTy = Val->getType();
  14006. } else {
  14007. // C99 6.7.2.2p2:
  14008. // The expression that defines the value of an enumeration constant
  14009. // shall be an integer constant expression that has a value
  14010. // representable as an int.
  14011. // Complain if the value is not representable in an int.
  14012. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  14013. Diag(IdLoc, diag::ext_enum_value_not_int)
  14014. << EnumVal.toString(10) << Val->getSourceRange()
  14015. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  14016. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  14017. // Force the type of the expression to 'int'.
  14018. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  14019. }
  14020. EltTy = Val->getType();
  14021. }
  14022. }
  14023. }
  14024. }
  14025. if (!Val) {
  14026. if (Enum->isDependentType())
  14027. EltTy = Context.DependentTy;
  14028. else if (!LastEnumConst) {
  14029. // C++0x [dcl.enum]p5:
  14030. // If the underlying type is not fixed, the type of each enumerator
  14031. // is the type of its initializing value:
  14032. // - If no initializer is specified for the first enumerator, the
  14033. // initializing value has an unspecified integral type.
  14034. //
  14035. // GCC uses 'int' for its unspecified integral type, as does
  14036. // C99 6.7.2.2p3.
  14037. if (Enum->isFixed()) {
  14038. EltTy = Enum->getIntegerType();
  14039. }
  14040. else {
  14041. EltTy = Context.IntTy;
  14042. }
  14043. } else {
  14044. // Assign the last value + 1.
  14045. EnumVal = LastEnumConst->getInitVal();
  14046. ++EnumVal;
  14047. EltTy = LastEnumConst->getType();
  14048. // Check for overflow on increment.
  14049. if (EnumVal < LastEnumConst->getInitVal()) {
  14050. // C++0x [dcl.enum]p5:
  14051. // If the underlying type is not fixed, the type of each enumerator
  14052. // is the type of its initializing value:
  14053. //
  14054. // - Otherwise the type of the initializing value is the same as
  14055. // the type of the initializing value of the preceding enumerator
  14056. // unless the incremented value is not representable in that type,
  14057. // in which case the type is an unspecified integral type
  14058. // sufficient to contain the incremented value. If no such type
  14059. // exists, the program is ill-formed.
  14060. QualType T = getNextLargerIntegralType(Context, EltTy);
  14061. if (T.isNull() || Enum->isFixed()) {
  14062. // There is no integral type larger enough to represent this
  14063. // value. Complain, then allow the value to wrap around.
  14064. EnumVal = LastEnumConst->getInitVal();
  14065. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  14066. ++EnumVal;
  14067. if (Enum->isFixed())
  14068. // When the underlying type is fixed, this is ill-formed.
  14069. Diag(IdLoc, diag::err_enumerator_wrapped)
  14070. << EnumVal.toString(10)
  14071. << EltTy;
  14072. else
  14073. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  14074. << EnumVal.toString(10);
  14075. } else {
  14076. EltTy = T;
  14077. }
  14078. // Retrieve the last enumerator's value, extent that type to the
  14079. // type that is supposed to be large enough to represent the incremented
  14080. // value, then increment.
  14081. EnumVal = LastEnumConst->getInitVal();
  14082. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  14083. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  14084. ++EnumVal;
  14085. // If we're not in C++, diagnose the overflow of enumerator values,
  14086. // which in C99 means that the enumerator value is not representable in
  14087. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  14088. // permits enumerator values that are representable in some larger
  14089. // integral type.
  14090. if (!getLangOpts().CPlusPlus && !T.isNull())
  14091. Diag(IdLoc, diag::warn_enum_value_overflow);
  14092. } else if (!getLangOpts().CPlusPlus &&
  14093. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14094. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  14095. Diag(IdLoc, diag::ext_enum_value_not_int)
  14096. << EnumVal.toString(10) << 1;
  14097. }
  14098. }
  14099. }
  14100. if (!EltTy->isDependentType()) {
  14101. // Make the enumerator value match the signedness and size of the
  14102. // enumerator's type.
  14103. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  14104. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  14105. }
  14106. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  14107. Val, EnumVal);
  14108. }
  14109. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  14110. SourceLocation IILoc) {
  14111. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  14112. !getLangOpts().CPlusPlus)
  14113. return SkipBodyInfo();
  14114. // We have an anonymous enum definition. Look up the first enumerator to
  14115. // determine if we should merge the definition with an existing one and
  14116. // skip the body.
  14117. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  14118. forRedeclarationInCurContext());
  14119. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  14120. if (!PrevECD)
  14121. return SkipBodyInfo();
  14122. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  14123. NamedDecl *Hidden;
  14124. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  14125. SkipBodyInfo Skip;
  14126. Skip.Previous = Hidden;
  14127. return Skip;
  14128. }
  14129. return SkipBodyInfo();
  14130. }
  14131. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  14132. SourceLocation IdLoc, IdentifierInfo *Id,
  14133. AttributeList *Attr,
  14134. SourceLocation EqualLoc, Expr *Val) {
  14135. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  14136. EnumConstantDecl *LastEnumConst =
  14137. cast_or_null<EnumConstantDecl>(lastEnumConst);
  14138. // The scope passed in may not be a decl scope. Zip up the scope tree until
  14139. // we find one that is.
  14140. S = getNonFieldDeclScope(S);
  14141. // Verify that there isn't already something declared with this name in this
  14142. // scope.
  14143. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  14144. ForVisibleRedeclaration);
  14145. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  14146. // Maybe we will complain about the shadowed template parameter.
  14147. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  14148. // Just pretend that we didn't see the previous declaration.
  14149. PrevDecl = nullptr;
  14150. }
  14151. // C++ [class.mem]p15:
  14152. // If T is the name of a class, then each of the following shall have a name
  14153. // different from T:
  14154. // - every enumerator of every member of class T that is an unscoped
  14155. // enumerated type
  14156. if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
  14157. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  14158. DeclarationNameInfo(Id, IdLoc));
  14159. EnumConstantDecl *New =
  14160. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  14161. if (!New)
  14162. return nullptr;
  14163. if (PrevDecl) {
  14164. // When in C++, we may get a TagDecl with the same name; in this case the
  14165. // enum constant will 'hide' the tag.
  14166. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  14167. "Received TagDecl when not in C++!");
  14168. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  14169. if (isa<EnumConstantDecl>(PrevDecl))
  14170. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  14171. else
  14172. Diag(IdLoc, diag::err_redefinition) << Id;
  14173. notePreviousDefinition(PrevDecl, IdLoc);
  14174. return nullptr;
  14175. }
  14176. }
  14177. // Process attributes.
  14178. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  14179. AddPragmaAttributes(S, New);
  14180. // Register this decl in the current scope stack.
  14181. New->setAccess(TheEnumDecl->getAccess());
  14182. PushOnScopeChains(New, S);
  14183. ActOnDocumentableDecl(New);
  14184. return New;
  14185. }
  14186. // Returns true when the enum initial expression does not trigger the
  14187. // duplicate enum warning. A few common cases are exempted as follows:
  14188. // Element2 = Element1
  14189. // Element2 = Element1 + 1
  14190. // Element2 = Element1 - 1
  14191. // Where Element2 and Element1 are from the same enum.
  14192. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  14193. Expr *InitExpr = ECD->getInitExpr();
  14194. if (!InitExpr)
  14195. return true;
  14196. InitExpr = InitExpr->IgnoreImpCasts();
  14197. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  14198. if (!BO->isAdditiveOp())
  14199. return true;
  14200. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  14201. if (!IL)
  14202. return true;
  14203. if (IL->getValue() != 1)
  14204. return true;
  14205. InitExpr = BO->getLHS();
  14206. }
  14207. // This checks if the elements are from the same enum.
  14208. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  14209. if (!DRE)
  14210. return true;
  14211. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  14212. if (!EnumConstant)
  14213. return true;
  14214. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  14215. Enum)
  14216. return true;
  14217. return false;
  14218. }
  14219. // Emits a warning when an element is implicitly set a value that
  14220. // a previous element has already been set to.
  14221. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  14222. EnumDecl *Enum, QualType EnumType) {
  14223. // Avoid anonymous enums
  14224. if (!Enum->getIdentifier())
  14225. return;
  14226. // Only check for small enums.
  14227. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  14228. return;
  14229. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  14230. return;
  14231. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  14232. typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
  14233. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  14234. typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap;
  14235. // Use int64_t as a key to avoid needing special handling for DenseMap keys.
  14236. auto EnumConstantToKey = [](const EnumConstantDecl *D) {
  14237. llvm::APSInt Val = D->getInitVal();
  14238. return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
  14239. };
  14240. DuplicatesVector DupVector;
  14241. ValueToVectorMap EnumMap;
  14242. // Populate the EnumMap with all values represented by enum constants without
  14243. // an initializer.
  14244. for (auto *Element : Elements) {
  14245. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
  14246. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  14247. // this constant. Skip this enum since it may be ill-formed.
  14248. if (!ECD) {
  14249. return;
  14250. }
  14251. // Constants with initalizers are handled in the next loop.
  14252. if (ECD->getInitExpr())
  14253. continue;
  14254. // Duplicate values are handled in the next loop.
  14255. EnumMap.insert({EnumConstantToKey(ECD), ECD});
  14256. }
  14257. if (EnumMap.size() == 0)
  14258. return;
  14259. // Create vectors for any values that has duplicates.
  14260. for (auto *Element : Elements) {
  14261. // The last loop returned if any constant was null.
  14262. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
  14263. if (!ValidDuplicateEnum(ECD, Enum))
  14264. continue;
  14265. auto Iter = EnumMap.find(EnumConstantToKey(ECD));
  14266. if (Iter == EnumMap.end())
  14267. continue;
  14268. DeclOrVector& Entry = Iter->second;
  14269. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  14270. // Ensure constants are different.
  14271. if (D == ECD)
  14272. continue;
  14273. // Create new vector and push values onto it.
  14274. auto Vec = llvm::make_unique<ECDVector>();
  14275. Vec->push_back(D);
  14276. Vec->push_back(ECD);
  14277. // Update entry to point to the duplicates vector.
  14278. Entry = Vec.get();
  14279. // Store the vector somewhere we can consult later for quick emission of
  14280. // diagnostics.
  14281. DupVector.emplace_back(std::move(Vec));
  14282. continue;
  14283. }
  14284. ECDVector *Vec = Entry.get<ECDVector*>();
  14285. // Make sure constants are not added more than once.
  14286. if (*Vec->begin() == ECD)
  14287. continue;
  14288. Vec->push_back(ECD);
  14289. }
  14290. // Emit diagnostics.
  14291. for (const auto &Vec : DupVector) {
  14292. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  14293. // Emit warning for one enum constant.
  14294. auto *FirstECD = Vec->front();
  14295. S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
  14296. << FirstECD << FirstECD->getInitVal().toString(10)
  14297. << FirstECD->getSourceRange();
  14298. // Emit one note for each of the remaining enum constants with
  14299. // the same value.
  14300. for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
  14301. S.Diag(ECD->getLocation(), diag::note_duplicate_element)
  14302. << ECD << ECD->getInitVal().toString(10)
  14303. << ECD->getSourceRange();
  14304. }
  14305. }
  14306. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  14307. bool AllowMask) const {
  14308. assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
  14309. assert(ED->isCompleteDefinition() && "expected enum definition");
  14310. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  14311. llvm::APInt &FlagBits = R.first->second;
  14312. if (R.second) {
  14313. for (auto *E : ED->enumerators()) {
  14314. const auto &EVal = E->getInitVal();
  14315. // Only single-bit enumerators introduce new flag values.
  14316. if (EVal.isPowerOf2())
  14317. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  14318. }
  14319. }
  14320. // A value is in a flag enum if either its bits are a subset of the enum's
  14321. // flag bits (the first condition) or we are allowing masks and the same is
  14322. // true of its complement (the second condition). When masks are allowed, we
  14323. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  14324. //
  14325. // While it's true that any value could be used as a mask, the assumption is
  14326. // that a mask will have all of the insignificant bits set. Anything else is
  14327. // likely a logic error.
  14328. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  14329. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  14330. }
  14331. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  14332. Decl *EnumDeclX,
  14333. ArrayRef<Decl *> Elements,
  14334. Scope *S, AttributeList *Attr) {
  14335. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  14336. QualType EnumType = Context.getTypeDeclType(Enum);
  14337. if (Attr)
  14338. ProcessDeclAttributeList(S, Enum, Attr);
  14339. if (Enum->isDependentType()) {
  14340. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  14341. EnumConstantDecl *ECD =
  14342. cast_or_null<EnumConstantDecl>(Elements[i]);
  14343. if (!ECD) continue;
  14344. ECD->setType(EnumType);
  14345. }
  14346. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  14347. return;
  14348. }
  14349. // TODO: If the result value doesn't fit in an int, it must be a long or long
  14350. // long value. ISO C does not support this, but GCC does as an extension,
  14351. // emit a warning.
  14352. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  14353. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  14354. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  14355. // Verify that all the values are okay, compute the size of the values, and
  14356. // reverse the list.
  14357. unsigned NumNegativeBits = 0;
  14358. unsigned NumPositiveBits = 0;
  14359. // Keep track of whether all elements have type int.
  14360. bool AllElementsInt = true;
  14361. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  14362. EnumConstantDecl *ECD =
  14363. cast_or_null<EnumConstantDecl>(Elements[i]);
  14364. if (!ECD) continue; // Already issued a diagnostic.
  14365. const llvm::APSInt &InitVal = ECD->getInitVal();
  14366. // Keep track of the size of positive and negative values.
  14367. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  14368. NumPositiveBits = std::max(NumPositiveBits,
  14369. (unsigned)InitVal.getActiveBits());
  14370. else
  14371. NumNegativeBits = std::max(NumNegativeBits,
  14372. (unsigned)InitVal.getMinSignedBits());
  14373. // Keep track of whether every enum element has type int (very commmon).
  14374. if (AllElementsInt)
  14375. AllElementsInt = ECD->getType() == Context.IntTy;
  14376. }
  14377. // Figure out the type that should be used for this enum.
  14378. QualType BestType;
  14379. unsigned BestWidth;
  14380. // C++0x N3000 [conv.prom]p3:
  14381. // An rvalue of an unscoped enumeration type whose underlying
  14382. // type is not fixed can be converted to an rvalue of the first
  14383. // of the following types that can represent all the values of
  14384. // the enumeration: int, unsigned int, long int, unsigned long
  14385. // int, long long int, or unsigned long long int.
  14386. // C99 6.4.4.3p2:
  14387. // An identifier declared as an enumeration constant has type int.
  14388. // The C99 rule is modified by a gcc extension
  14389. QualType BestPromotionType;
  14390. bool Packed = Enum->hasAttr<PackedAttr>();
  14391. // -fshort-enums is the equivalent to specifying the packed attribute on all
  14392. // enum definitions.
  14393. if (LangOpts.ShortEnums)
  14394. Packed = true;
  14395. // If the enum already has a type because it is fixed or dictated by the
  14396. // target, promote that type instead of analyzing the enumerators.
  14397. if (Enum->isComplete()) {
  14398. BestType = Enum->getIntegerType();
  14399. if (BestType->isPromotableIntegerType())
  14400. BestPromotionType = Context.getPromotedIntegerType(BestType);
  14401. else
  14402. BestPromotionType = BestType;
  14403. BestWidth = Context.getIntWidth(BestType);
  14404. }
  14405. else if (NumNegativeBits) {
  14406. // If there is a negative value, figure out the smallest integer type (of
  14407. // int/long/longlong) that fits.
  14408. // If it's packed, check also if it fits a char or a short.
  14409. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  14410. BestType = Context.SignedCharTy;
  14411. BestWidth = CharWidth;
  14412. } else if (Packed && NumNegativeBits <= ShortWidth &&
  14413. NumPositiveBits < ShortWidth) {
  14414. BestType = Context.ShortTy;
  14415. BestWidth = ShortWidth;
  14416. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  14417. BestType = Context.IntTy;
  14418. BestWidth = IntWidth;
  14419. } else {
  14420. BestWidth = Context.getTargetInfo().getLongWidth();
  14421. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  14422. BestType = Context.LongTy;
  14423. } else {
  14424. BestWidth = Context.getTargetInfo().getLongLongWidth();
  14425. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  14426. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  14427. BestType = Context.LongLongTy;
  14428. }
  14429. }
  14430. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  14431. } else {
  14432. // If there is no negative value, figure out the smallest type that fits
  14433. // all of the enumerator values.
  14434. // If it's packed, check also if it fits a char or a short.
  14435. if (Packed && NumPositiveBits <= CharWidth) {
  14436. BestType = Context.UnsignedCharTy;
  14437. BestPromotionType = Context.IntTy;
  14438. BestWidth = CharWidth;
  14439. } else if (Packed && NumPositiveBits <= ShortWidth) {
  14440. BestType = Context.UnsignedShortTy;
  14441. BestPromotionType = Context.IntTy;
  14442. BestWidth = ShortWidth;
  14443. } else if (NumPositiveBits <= IntWidth) {
  14444. BestType = Context.UnsignedIntTy;
  14445. BestWidth = IntWidth;
  14446. BestPromotionType
  14447. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14448. ? Context.UnsignedIntTy : Context.IntTy;
  14449. } else if (NumPositiveBits <=
  14450. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  14451. BestType = Context.UnsignedLongTy;
  14452. BestPromotionType
  14453. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14454. ? Context.UnsignedLongTy : Context.LongTy;
  14455. } else {
  14456. BestWidth = Context.getTargetInfo().getLongLongWidth();
  14457. assert(NumPositiveBits <= BestWidth &&
  14458. "How could an initializer get larger than ULL?");
  14459. BestType = Context.UnsignedLongLongTy;
  14460. BestPromotionType
  14461. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14462. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  14463. }
  14464. }
  14465. // Loop over all of the enumerator constants, changing their types to match
  14466. // the type of the enum if needed.
  14467. for (auto *D : Elements) {
  14468. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  14469. if (!ECD) continue; // Already issued a diagnostic.
  14470. // Standard C says the enumerators have int type, but we allow, as an
  14471. // extension, the enumerators to be larger than int size. If each
  14472. // enumerator value fits in an int, type it as an int, otherwise type it the
  14473. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  14474. // that X has type 'int', not 'unsigned'.
  14475. // Determine whether the value fits into an int.
  14476. llvm::APSInt InitVal = ECD->getInitVal();
  14477. // If it fits into an integer type, force it. Otherwise force it to match
  14478. // the enum decl type.
  14479. QualType NewTy;
  14480. unsigned NewWidth;
  14481. bool NewSign;
  14482. if (!getLangOpts().CPlusPlus &&
  14483. !Enum->isFixed() &&
  14484. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  14485. NewTy = Context.IntTy;
  14486. NewWidth = IntWidth;
  14487. NewSign = true;
  14488. } else if (ECD->getType() == BestType) {
  14489. // Already the right type!
  14490. if (getLangOpts().CPlusPlus)
  14491. // C++ [dcl.enum]p4: Following the closing brace of an
  14492. // enum-specifier, each enumerator has the type of its
  14493. // enumeration.
  14494. ECD->setType(EnumType);
  14495. continue;
  14496. } else {
  14497. NewTy = BestType;
  14498. NewWidth = BestWidth;
  14499. NewSign = BestType->isSignedIntegerOrEnumerationType();
  14500. }
  14501. // Adjust the APSInt value.
  14502. InitVal = InitVal.extOrTrunc(NewWidth);
  14503. InitVal.setIsSigned(NewSign);
  14504. ECD->setInitVal(InitVal);
  14505. // Adjust the Expr initializer and type.
  14506. if (ECD->getInitExpr() &&
  14507. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  14508. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  14509. CK_IntegralCast,
  14510. ECD->getInitExpr(),
  14511. /*base paths*/ nullptr,
  14512. VK_RValue));
  14513. if (getLangOpts().CPlusPlus)
  14514. // C++ [dcl.enum]p4: Following the closing brace of an
  14515. // enum-specifier, each enumerator has the type of its
  14516. // enumeration.
  14517. ECD->setType(EnumType);
  14518. else
  14519. ECD->setType(NewTy);
  14520. }
  14521. Enum->completeDefinition(BestType, BestPromotionType,
  14522. NumPositiveBits, NumNegativeBits);
  14523. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  14524. if (Enum->isClosedFlag()) {
  14525. for (Decl *D : Elements) {
  14526. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  14527. if (!ECD) continue; // Already issued a diagnostic.
  14528. llvm::APSInt InitVal = ECD->getInitVal();
  14529. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  14530. !IsValueInFlagEnum(Enum, InitVal, true))
  14531. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  14532. << ECD << Enum;
  14533. }
  14534. }
  14535. // Now that the enum type is defined, ensure it's not been underaligned.
  14536. if (Enum->hasAttrs())
  14537. CheckAlignasUnderalignment(Enum);
  14538. }
  14539. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  14540. SourceLocation StartLoc,
  14541. SourceLocation EndLoc) {
  14542. StringLiteral *AsmString = cast<StringLiteral>(expr);
  14543. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  14544. AsmString, StartLoc,
  14545. EndLoc);
  14546. CurContext->addDecl(New);
  14547. return New;
  14548. }
  14549. static void checkModuleImportContext(Sema &S, Module *M,
  14550. SourceLocation ImportLoc, DeclContext *DC,
  14551. bool FromInclude = false) {
  14552. SourceLocation ExternCLoc;
  14553. if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
  14554. switch (LSD->getLanguage()) {
  14555. case LinkageSpecDecl::lang_c:
  14556. if (ExternCLoc.isInvalid())
  14557. ExternCLoc = LSD->getLocStart();
  14558. break;
  14559. case LinkageSpecDecl::lang_cxx:
  14560. break;
  14561. }
  14562. DC = LSD->getParent();
  14563. }
  14564. while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
  14565. DC = DC->getParent();
  14566. if (!isa<TranslationUnitDecl>(DC)) {
  14567. S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
  14568. ? diag::ext_module_import_not_at_top_level_noop
  14569. : diag::err_module_import_not_at_top_level_fatal)
  14570. << M->getFullModuleName() << DC;
  14571. S.Diag(cast<Decl>(DC)->getLocStart(),
  14572. diag::note_module_import_not_at_top_level) << DC;
  14573. } else if (!M->IsExternC && ExternCLoc.isValid()) {
  14574. S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
  14575. << M->getFullModuleName();
  14576. S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
  14577. }
  14578. }
  14579. Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
  14580. SourceLocation ModuleLoc,
  14581. ModuleDeclKind MDK,
  14582. ModuleIdPath Path) {
  14583. assert(getLangOpts().ModulesTS &&
  14584. "should only have module decl in modules TS");
  14585. // A module implementation unit requires that we are not compiling a module
  14586. // of any kind. A module interface unit requires that we are not compiling a
  14587. // module map.
  14588. switch (getLangOpts().getCompilingModule()) {
  14589. case LangOptions::CMK_None:
  14590. // It's OK to compile a module interface as a normal translation unit.
  14591. break;
  14592. case LangOptions::CMK_ModuleInterface:
  14593. if (MDK != ModuleDeclKind::Implementation)
  14594. break;
  14595. // We were asked to compile a module interface unit but this is a module
  14596. // implementation unit. That indicates the 'export' is missing.
  14597. Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
  14598. << FixItHint::CreateInsertion(ModuleLoc, "export ");
  14599. MDK = ModuleDeclKind::Interface;
  14600. break;
  14601. case LangOptions::CMK_ModuleMap:
  14602. Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
  14603. return nullptr;
  14604. }
  14605. assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
  14606. // FIXME: Most of this work should be done by the preprocessor rather than
  14607. // here, in order to support macro import.
  14608. // Only one module-declaration is permitted per source file.
  14609. if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
  14610. Diag(ModuleLoc, diag::err_module_redeclaration);
  14611. Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
  14612. diag::note_prev_module_declaration);
  14613. return nullptr;
  14614. }
  14615. // Flatten the dots in a module name. Unlike Clang's hierarchical module map
  14616. // modules, the dots here are just another character that can appear in a
  14617. // module name.
  14618. std::string ModuleName;
  14619. for (auto &Piece : Path) {
  14620. if (!ModuleName.empty())
  14621. ModuleName += ".";
  14622. ModuleName += Piece.first->getName();
  14623. }
  14624. // If a module name was explicitly specified on the command line, it must be
  14625. // correct.
  14626. if (!getLangOpts().CurrentModule.empty() &&
  14627. getLangOpts().CurrentModule != ModuleName) {
  14628. Diag(Path.front().second, diag::err_current_module_name_mismatch)
  14629. << SourceRange(Path.front().second, Path.back().second)
  14630. << getLangOpts().CurrentModule;
  14631. return nullptr;
  14632. }
  14633. const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
  14634. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  14635. Module *Mod;
  14636. switch (MDK) {
  14637. case ModuleDeclKind::Interface: {
  14638. // We can't have parsed or imported a definition of this module or parsed a
  14639. // module map defining it already.
  14640. if (auto *M = Map.findModule(ModuleName)) {
  14641. Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
  14642. if (M->DefinitionLoc.isValid())
  14643. Diag(M->DefinitionLoc, diag::note_prev_module_definition);
  14644. else if (const auto *FE = M->getASTFile())
  14645. Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
  14646. << FE->getName();
  14647. Mod = M;
  14648. break;
  14649. }
  14650. // Create a Module for the module that we're defining.
  14651. Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
  14652. ModuleScopes.front().Module);
  14653. assert(Mod && "module creation should not fail");
  14654. break;
  14655. }
  14656. case ModuleDeclKind::Partition:
  14657. // FIXME: Check we are in a submodule of the named module.
  14658. return nullptr;
  14659. case ModuleDeclKind::Implementation:
  14660. std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
  14661. PP.getIdentifierInfo(ModuleName), Path[0].second);
  14662. Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
  14663. /*IsIncludeDirective=*/false);
  14664. if (!Mod) {
  14665. Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
  14666. // Create an empty module interface unit for error recovery.
  14667. Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
  14668. ModuleScopes.front().Module);
  14669. }
  14670. break;
  14671. }
  14672. // Switch from the global module to the named module.
  14673. ModuleScopes.back().Module = Mod;
  14674. ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
  14675. VisibleModules.setVisible(Mod, ModuleLoc);
  14676. // From now on, we have an owning module for all declarations we see.
  14677. // However, those declarations are module-private unless explicitly
  14678. // exported.
  14679. auto *TU = Context.getTranslationUnitDecl();
  14680. TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
  14681. TU->setLocalOwningModule(Mod);
  14682. // FIXME: Create a ModuleDecl.
  14683. return nullptr;
  14684. }
  14685. DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
  14686. SourceLocation ImportLoc,
  14687. ModuleIdPath Path) {
  14688. Module *Mod =
  14689. getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
  14690. /*IsIncludeDirective=*/false);
  14691. if (!Mod)
  14692. return true;
  14693. VisibleModules.setVisible(Mod, ImportLoc);
  14694. checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
  14695. // FIXME: we should support importing a submodule within a different submodule
  14696. // of the same top-level module. Until we do, make it an error rather than
  14697. // silently ignoring the import.
  14698. // Import-from-implementation is valid in the Modules TS. FIXME: Should we
  14699. // warn on a redundant import of the current module?
  14700. if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  14701. (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
  14702. Diag(ImportLoc, getLangOpts().isCompilingModule()
  14703. ? diag::err_module_self_import
  14704. : diag::err_module_import_in_implementation)
  14705. << Mod->getFullModuleName() << getLangOpts().CurrentModule;
  14706. SmallVector<SourceLocation, 2> IdentifierLocs;
  14707. Module *ModCheck = Mod;
  14708. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  14709. // If we've run out of module parents, just drop the remaining identifiers.
  14710. // We need the length to be consistent.
  14711. if (!ModCheck)
  14712. break;
  14713. ModCheck = ModCheck->Parent;
  14714. IdentifierLocs.push_back(Path[I].second);
  14715. }
  14716. ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
  14717. Mod, IdentifierLocs);
  14718. if (!ModuleScopes.empty())
  14719. Context.addModuleInitializer(ModuleScopes.back().Module, Import);
  14720. CurContext->addDecl(Import);
  14721. // Re-export the module if needed.
  14722. if (Import->isExported() &&
  14723. !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
  14724. getCurrentModule()->Exports.emplace_back(Mod, false);
  14725. return Import;
  14726. }
  14727. void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  14728. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  14729. BuildModuleInclude(DirectiveLoc, Mod);
  14730. }
  14731. void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  14732. // Determine whether we're in the #include buffer for a module. The #includes
  14733. // in that buffer do not qualify as module imports; they're just an
  14734. // implementation detail of us building the module.
  14735. //
  14736. // FIXME: Should we even get ActOnModuleInclude calls for those?
  14737. bool IsInModuleIncludes =
  14738. TUKind == TU_Module &&
  14739. getSourceManager().isWrittenInMainFile(DirectiveLoc);
  14740. bool ShouldAddImport = !IsInModuleIncludes;
  14741. // If this module import was due to an inclusion directive, create an
  14742. // implicit import declaration to capture it in the AST.
  14743. if (ShouldAddImport) {
  14744. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  14745. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  14746. DirectiveLoc, Mod,
  14747. DirectiveLoc);
  14748. if (!ModuleScopes.empty())
  14749. Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
  14750. TU->addDecl(ImportD);
  14751. Consumer.HandleImplicitImportDecl(ImportD);
  14752. }
  14753. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
  14754. VisibleModules.setVisible(Mod, DirectiveLoc);
  14755. }
  14756. void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
  14757. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  14758. ModuleScopes.push_back({});
  14759. ModuleScopes.back().Module = Mod;
  14760. if (getLangOpts().ModulesLocalVisibility)
  14761. ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
  14762. VisibleModules.setVisible(Mod, DirectiveLoc);
  14763. // The enclosing context is now part of this module.
  14764. // FIXME: Consider creating a child DeclContext to hold the entities
  14765. // lexically within the module.
  14766. if (getLangOpts().trackLocalOwningModule()) {
  14767. for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
  14768. cast<Decl>(DC)->setModuleOwnershipKind(
  14769. getLangOpts().ModulesLocalVisibility
  14770. ? Decl::ModuleOwnershipKind::VisibleWhenImported
  14771. : Decl::ModuleOwnershipKind::Visible);
  14772. cast<Decl>(DC)->setLocalOwningModule(Mod);
  14773. }
  14774. }
  14775. }
  14776. void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
  14777. if (getLangOpts().ModulesLocalVisibility) {
  14778. VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
  14779. // Leaving a module hides namespace names, so our visible namespace cache
  14780. // is now out of date.
  14781. VisibleNamespaceCache.clear();
  14782. }
  14783. assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
  14784. "left the wrong module scope");
  14785. ModuleScopes.pop_back();
  14786. // We got to the end of processing a local module. Create an
  14787. // ImportDecl as we would for an imported module.
  14788. FileID File = getSourceManager().getFileID(EomLoc);
  14789. SourceLocation DirectiveLoc;
  14790. if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
  14791. // We reached the end of a #included module header. Use the #include loc.
  14792. assert(File != getSourceManager().getMainFileID() &&
  14793. "end of submodule in main source file");
  14794. DirectiveLoc = getSourceManager().getIncludeLoc(File);
  14795. } else {
  14796. // We reached an EOM pragma. Use the pragma location.
  14797. DirectiveLoc = EomLoc;
  14798. }
  14799. BuildModuleInclude(DirectiveLoc, Mod);
  14800. // Any further declarations are in whatever module we returned to.
  14801. if (getLangOpts().trackLocalOwningModule()) {
  14802. // The parser guarantees that this is the same context that we entered
  14803. // the module within.
  14804. for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
  14805. cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
  14806. if (!getCurrentModule())
  14807. cast<Decl>(DC)->setModuleOwnershipKind(
  14808. Decl::ModuleOwnershipKind::Unowned);
  14809. }
  14810. }
  14811. }
  14812. void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
  14813. Module *Mod) {
  14814. // Bail if we're not allowed to implicitly import a module here.
  14815. if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
  14816. VisibleModules.isVisible(Mod))
  14817. return;
  14818. // Create the implicit import declaration.
  14819. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  14820. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  14821. Loc, Mod, Loc);
  14822. TU->addDecl(ImportD);
  14823. Consumer.HandleImplicitImportDecl(ImportD);
  14824. // Make the module visible.
  14825. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
  14826. VisibleModules.setVisible(Mod, Loc);
  14827. }
  14828. /// We have parsed the start of an export declaration, including the '{'
  14829. /// (if present).
  14830. Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
  14831. SourceLocation LBraceLoc) {
  14832. ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
  14833. // C++ Modules TS draft:
  14834. // An export-declaration shall appear in the purview of a module other than
  14835. // the global module.
  14836. if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
  14837. Diag(ExportLoc, diag::err_export_not_in_module_interface);
  14838. // An export-declaration [...] shall not contain more than one
  14839. // export keyword.
  14840. //
  14841. // The intent here is that an export-declaration cannot appear within another
  14842. // export-declaration.
  14843. if (D->isExported())
  14844. Diag(ExportLoc, diag::err_export_within_export);
  14845. CurContext->addDecl(D);
  14846. PushDeclContext(S, D);
  14847. D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
  14848. return D;
  14849. }
  14850. /// Complete the definition of an export declaration.
  14851. Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
  14852. auto *ED = cast<ExportDecl>(D);
  14853. if (RBraceLoc.isValid())
  14854. ED->setRBraceLoc(RBraceLoc);
  14855. // FIXME: Diagnose export of internal-linkage declaration (including
  14856. // anonymous namespace).
  14857. PopDeclContext();
  14858. return D;
  14859. }
  14860. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  14861. IdentifierInfo* AliasName,
  14862. SourceLocation PragmaLoc,
  14863. SourceLocation NameLoc,
  14864. SourceLocation AliasNameLoc) {
  14865. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  14866. LookupOrdinaryName);
  14867. AsmLabelAttr *Attr =
  14868. AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
  14869. // If a declaration that:
  14870. // 1) declares a function or a variable
  14871. // 2) has external linkage
  14872. // already exists, add a label attribute to it.
  14873. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  14874. if (isDeclExternC(PrevDecl))
  14875. PrevDecl->addAttr(Attr);
  14876. else
  14877. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  14878. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  14879. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  14880. } else
  14881. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  14882. }
  14883. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  14884. SourceLocation PragmaLoc,
  14885. SourceLocation NameLoc) {
  14886. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  14887. if (PrevDecl) {
  14888. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  14889. } else {
  14890. (void)WeakUndeclaredIdentifiers.insert(
  14891. std::pair<IdentifierInfo*,WeakInfo>
  14892. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  14893. }
  14894. }
  14895. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  14896. IdentifierInfo* AliasName,
  14897. SourceLocation PragmaLoc,
  14898. SourceLocation NameLoc,
  14899. SourceLocation AliasNameLoc) {
  14900. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  14901. LookupOrdinaryName);
  14902. WeakInfo W = WeakInfo(Name, NameLoc);
  14903. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  14904. if (!PrevDecl->hasAttr<AliasAttr>())
  14905. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  14906. DeclApplyPragmaWeak(TUScope, ND, W);
  14907. } else {
  14908. (void)WeakUndeclaredIdentifiers.insert(
  14909. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  14910. }
  14911. }
  14912. Decl *Sema::getObjCDeclContext() const {
  14913. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  14914. }