SemaDecl.cpp 559 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564
  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 "clang/Sema/SemaInternal.h"
  14. #include "TypeLocBuilder.h"
  15. #include "clang/AST/ASTConsumer.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/ASTLambda.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/CharUnits.h"
  20. #include "clang/AST/CommentDiagnostic.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/EvaluatedExprVisitor.h"
  25. #include "clang/AST/ExprCXX.h"
  26. #include "clang/AST/StmtCXX.h"
  27. #include "clang/Basic/Builtins.h"
  28. #include "clang/Basic/PartialDiagnostic.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  32. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  33. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  34. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  35. #include "clang/Parse/ParseDiagnostic.h"
  36. #include "clang/Sema/CXXFieldCollector.h"
  37. #include "clang/Sema/DeclSpec.h"
  38. #include "clang/Sema/DelayedDiagnostic.h"
  39. #include "clang/Sema/Initialization.h"
  40. #include "clang/Sema/Lookup.h"
  41. #include "clang/Sema/ParsedTemplate.h"
  42. #include "clang/Sema/Scope.h"
  43. #include "clang/Sema/ScopeInfo.h"
  44. #include "clang/Sema/Template.h"
  45. #include "llvm/ADT/SmallString.h"
  46. #include "llvm/ADT/Triple.h"
  47. #include <algorithm>
  48. #include <cstring>
  49. #include <functional>
  50. using namespace clang;
  51. using namespace sema;
  52. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  53. if (OwnedType) {
  54. Decl *Group[2] = { OwnedType, Ptr };
  55. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  56. }
  57. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  58. }
  59. namespace {
  60. class TypeNameValidatorCCC : public CorrectionCandidateCallback {
  61. public:
  62. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
  63. bool AllowTemplates=false)
  64. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  65. AllowClassTemplates(AllowTemplates) {
  66. WantExpressionKeywords = false;
  67. WantCXXNamedCasts = false;
  68. WantRemainingKeywords = false;
  69. }
  70. bool ValidateCandidate(const TypoCorrection &candidate) override {
  71. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  72. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  73. bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
  74. return (IsType || AllowedTemplate) &&
  75. (AllowInvalidDecl || !ND->isInvalidDecl());
  76. }
  77. return !WantClassName && candidate.isKeyword();
  78. }
  79. private:
  80. bool AllowInvalidDecl;
  81. bool WantClassName;
  82. bool AllowClassTemplates;
  83. };
  84. }
  85. /// \brief Determine whether the token kind starts a simple-type-specifier.
  86. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  87. switch (Kind) {
  88. // FIXME: Take into account the current language when deciding whether a
  89. // token kind is a valid type specifier
  90. case tok::kw_short:
  91. case tok::kw_long:
  92. case tok::kw___int64:
  93. case tok::kw___int128:
  94. case tok::kw_signed:
  95. case tok::kw_unsigned:
  96. case tok::kw_void:
  97. case tok::kw_char:
  98. case tok::kw_int:
  99. case tok::kw_half:
  100. case tok::kw_float:
  101. case tok::kw_double:
  102. case tok::kw_wchar_t:
  103. case tok::kw_bool:
  104. case tok::kw___underlying_type:
  105. return true;
  106. case tok::annot_typename:
  107. case tok::kw_char16_t:
  108. case tok::kw_char32_t:
  109. case tok::kw_typeof:
  110. case tok::annot_decltype:
  111. case tok::kw_decltype:
  112. return getLangOpts().CPlusPlus;
  113. default:
  114. break;
  115. }
  116. return false;
  117. }
  118. namespace {
  119. enum class UnqualifiedTypeNameLookupResult {
  120. NotFound,
  121. FoundNonType,
  122. FoundType
  123. };
  124. } // namespace
  125. /// \brief Tries to perform unqualified lookup of the type decls in bases for
  126. /// dependent class.
  127. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  128. /// type decl, \a FoundType if only type decls are found.
  129. static UnqualifiedTypeNameLookupResult
  130. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  131. SourceLocation NameLoc,
  132. const CXXRecordDecl *RD) {
  133. if (!RD->hasDefinition())
  134. return UnqualifiedTypeNameLookupResult::NotFound;
  135. // Look for type decls in base classes.
  136. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  137. UnqualifiedTypeNameLookupResult::NotFound;
  138. for (const auto &Base : RD->bases()) {
  139. const CXXRecordDecl *BaseRD = nullptr;
  140. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  141. BaseRD = BaseTT->getAsCXXRecordDecl();
  142. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  143. // Look for type decls in dependent base classes that have known primary
  144. // templates.
  145. if (!TST || !TST->isDependentType())
  146. continue;
  147. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  148. if (!TD)
  149. continue;
  150. auto *BasePrimaryTemplate =
  151. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
  152. if (!BasePrimaryTemplate)
  153. continue;
  154. BaseRD = BasePrimaryTemplate;
  155. }
  156. if (BaseRD) {
  157. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  158. if (!isa<TypeDecl>(ND))
  159. return UnqualifiedTypeNameLookupResult::FoundNonType;
  160. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  161. }
  162. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  163. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  164. case UnqualifiedTypeNameLookupResult::FoundNonType:
  165. return UnqualifiedTypeNameLookupResult::FoundNonType;
  166. case UnqualifiedTypeNameLookupResult::FoundType:
  167. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  168. break;
  169. case UnqualifiedTypeNameLookupResult::NotFound:
  170. break;
  171. }
  172. }
  173. }
  174. }
  175. return FoundTypeDecl;
  176. }
  177. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  178. const IdentifierInfo &II,
  179. SourceLocation NameLoc) {
  180. // Lookup in the parent class template context, if any.
  181. const CXXRecordDecl *RD = nullptr;
  182. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  183. UnqualifiedTypeNameLookupResult::NotFound;
  184. for (DeclContext *DC = S.CurContext;
  185. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  186. DC = DC->getParent()) {
  187. // Look for type decls in dependent base classes that have known primary
  188. // templates.
  189. RD = dyn_cast<CXXRecordDecl>(DC);
  190. if (RD && RD->getDescribedClassTemplate())
  191. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  192. }
  193. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  194. return ParsedType();
  195. // We found some types in dependent base classes. Recover as if the user
  196. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  197. // lookup during template instantiation.
  198. S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
  199. ASTContext &Context = S.Context;
  200. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  201. cast<Type>(Context.getRecordType(RD)));
  202. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  203. CXXScopeSpec SS;
  204. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  205. TypeLocBuilder Builder;
  206. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  207. DepTL.setNameLoc(NameLoc);
  208. DepTL.setElaboratedKeywordLoc(SourceLocation());
  209. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  210. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  211. }
  212. /// \brief If the identifier refers to a type name within this scope,
  213. /// return the declaration of that type.
  214. ///
  215. /// This routine performs ordinary name lookup of the identifier II
  216. /// within the given scope, with optional C++ scope specifier SS, to
  217. /// determine whether the name refers to a type. If so, returns an
  218. /// opaque pointer (actually a QualType) corresponding to that
  219. /// type. Otherwise, returns NULL.
  220. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  221. Scope *S, CXXScopeSpec *SS,
  222. bool isClassName, bool HasTrailingDot,
  223. ParsedType ObjectTypePtr,
  224. bool IsCtorOrDtorName,
  225. bool WantNontrivialTypeSourceInfo,
  226. IdentifierInfo **CorrectedII) {
  227. // Determine where we will perform name lookup.
  228. DeclContext *LookupCtx = nullptr;
  229. if (ObjectTypePtr) {
  230. QualType ObjectType = ObjectTypePtr.get();
  231. if (ObjectType->isRecordType())
  232. LookupCtx = computeDeclContext(ObjectType);
  233. } else if (SS && SS->isNotEmpty()) {
  234. LookupCtx = computeDeclContext(*SS, false);
  235. if (!LookupCtx) {
  236. if (isDependentScopeSpecifier(*SS)) {
  237. // C++ [temp.res]p3:
  238. // A qualified-id that refers to a type and in which the
  239. // nested-name-specifier depends on a template-parameter (14.6.2)
  240. // shall be prefixed by the keyword typename to indicate that the
  241. // qualified-id denotes a type, forming an
  242. // elaborated-type-specifier (7.1.5.3).
  243. //
  244. // We therefore do not perform any name lookup if the result would
  245. // refer to a member of an unknown specialization.
  246. if (!isClassName && !IsCtorOrDtorName)
  247. return ParsedType();
  248. // We know from the grammar that this name refers to a type,
  249. // so build a dependent node to describe the type.
  250. if (WantNontrivialTypeSourceInfo)
  251. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  252. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  253. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  254. II, NameLoc);
  255. return ParsedType::make(T);
  256. }
  257. return ParsedType();
  258. }
  259. if (!LookupCtx->isDependentContext() &&
  260. RequireCompleteDeclContext(*SS, LookupCtx))
  261. return ParsedType();
  262. }
  263. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  264. // lookup for class-names.
  265. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  266. LookupOrdinaryName;
  267. LookupResult Result(*this, &II, NameLoc, Kind);
  268. if (LookupCtx) {
  269. // Perform "qualified" name lookup into the declaration context we
  270. // computed, which is either the type of the base of a member access
  271. // expression or the declaration context associated with a prior
  272. // nested-name-specifier.
  273. LookupQualifiedName(Result, LookupCtx);
  274. if (ObjectTypePtr && Result.empty()) {
  275. // C++ [basic.lookup.classref]p3:
  276. // If the unqualified-id is ~type-name, the type-name is looked up
  277. // in the context of the entire postfix-expression. If the type T of
  278. // the object expression is of a class type C, the type-name is also
  279. // looked up in the scope of class C. At least one of the lookups shall
  280. // find a name that refers to (possibly cv-qualified) T.
  281. LookupName(Result, S);
  282. }
  283. } else {
  284. // Perform unqualified name lookup.
  285. LookupName(Result, S);
  286. // For unqualified lookup in a class template in MSVC mode, look into
  287. // dependent base classes where the primary class template is known.
  288. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  289. if (ParsedType TypeInBase =
  290. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  291. return TypeInBase;
  292. }
  293. }
  294. NamedDecl *IIDecl = nullptr;
  295. switch (Result.getResultKind()) {
  296. case LookupResult::NotFound:
  297. case LookupResult::NotFoundInCurrentInstantiation:
  298. if (CorrectedII) {
  299. TypoCorrection Correction = CorrectTypo(
  300. Result.getLookupNameInfo(), Kind, S, SS,
  301. llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
  302. CTK_ErrorRecovery);
  303. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  304. TemplateTy Template;
  305. bool MemberOfUnknownSpecialization;
  306. UnqualifiedId TemplateName;
  307. TemplateName.setIdentifier(NewII, NameLoc);
  308. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  309. CXXScopeSpec NewSS, *NewSSPtr = SS;
  310. if (SS && NNS) {
  311. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  312. NewSSPtr = &NewSS;
  313. }
  314. if (Correction && (NNS || NewII != &II) &&
  315. // Ignore a correction to a template type as the to-be-corrected
  316. // identifier is not a template (typo correction for template names
  317. // is handled elsewhere).
  318. !(getLangOpts().CPlusPlus && NewSSPtr &&
  319. isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
  320. false, Template, MemberOfUnknownSpecialization))) {
  321. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  322. isClassName, HasTrailingDot, ObjectTypePtr,
  323. IsCtorOrDtorName,
  324. WantNontrivialTypeSourceInfo);
  325. if (Ty) {
  326. diagnoseTypo(Correction,
  327. PDiag(diag::err_unknown_type_or_class_name_suggest)
  328. << Result.getLookupName() << isClassName);
  329. if (SS && NNS)
  330. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  331. *CorrectedII = NewII;
  332. return Ty;
  333. }
  334. }
  335. }
  336. // If typo correction failed or was not performed, fall through
  337. case LookupResult::FoundOverloaded:
  338. case LookupResult::FoundUnresolvedValue:
  339. Result.suppressDiagnostics();
  340. return ParsedType();
  341. case LookupResult::Ambiguous:
  342. // Recover from type-hiding ambiguities by hiding the type. We'll
  343. // do the lookup again when looking for an object, and we can
  344. // diagnose the error then. If we don't do this, then the error
  345. // about hiding the type will be immediately followed by an error
  346. // that only makes sense if the identifier was treated like a type.
  347. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  348. Result.suppressDiagnostics();
  349. return ParsedType();
  350. }
  351. // Look to see if we have a type anywhere in the list of results.
  352. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  353. Res != ResEnd; ++Res) {
  354. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
  355. if (!IIDecl ||
  356. (*Res)->getLocation().getRawEncoding() <
  357. IIDecl->getLocation().getRawEncoding())
  358. IIDecl = *Res;
  359. }
  360. }
  361. if (!IIDecl) {
  362. // None of the entities we found is a type, so there is no way
  363. // to even assume that the result is a type. In this case, don't
  364. // complain about the ambiguity. The parser will either try to
  365. // perform this lookup again (e.g., as an object name), which
  366. // will produce the ambiguity, or will complain that it expected
  367. // a type name.
  368. Result.suppressDiagnostics();
  369. return ParsedType();
  370. }
  371. // We found a type within the ambiguous lookup; diagnose the
  372. // ambiguity and then return that type. This might be the right
  373. // answer, or it might not be, but it suppresses any attempt to
  374. // perform the name lookup again.
  375. break;
  376. case LookupResult::Found:
  377. IIDecl = Result.getFoundDecl();
  378. break;
  379. }
  380. assert(IIDecl && "Didn't find decl");
  381. QualType T;
  382. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  383. DiagnoseUseOfDecl(IIDecl, NameLoc);
  384. T = Context.getTypeDeclType(TD);
  385. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  386. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  387. // constructor or destructor name (in such a case, the scope specifier
  388. // will be attached to the enclosing Expr or Decl node).
  389. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
  390. if (WantNontrivialTypeSourceInfo) {
  391. // Construct a type with type-source information.
  392. TypeLocBuilder Builder;
  393. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  394. T = getElaboratedType(ETK_None, *SS, T);
  395. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  396. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  397. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  398. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  399. } else {
  400. T = getElaboratedType(ETK_None, *SS, T);
  401. }
  402. }
  403. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  404. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  405. if (!HasTrailingDot)
  406. T = Context.getObjCInterfaceType(IDecl);
  407. }
  408. if (T.isNull()) {
  409. // If it's not plausibly a type, suppress diagnostics.
  410. Result.suppressDiagnostics();
  411. return ParsedType();
  412. }
  413. return ParsedType::make(T);
  414. }
  415. // Builds a fake NNS for the given decl context.
  416. static NestedNameSpecifier *
  417. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  418. for (;; DC = DC->getLookupParent()) {
  419. DC = DC->getPrimaryContext();
  420. auto *ND = dyn_cast<NamespaceDecl>(DC);
  421. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  422. return NestedNameSpecifier::Create(Context, nullptr, ND);
  423. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  424. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  425. RD->getTypeForDecl());
  426. else if (isa<TranslationUnitDecl>(DC))
  427. return NestedNameSpecifier::GlobalSpecifier(Context);
  428. }
  429. llvm_unreachable("something isn't in TU scope?");
  430. }
  431. ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
  432. SourceLocation NameLoc) {
  433. // Accepting an undeclared identifier as a default argument for a template
  434. // type parameter is a Microsoft extension.
  435. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  436. // Build a fake DependentNameType that will perform lookup into CurContext at
  437. // instantiation time. The name specifier isn't dependent, so template
  438. // instantiation won't transform it. It will retry the lookup, however.
  439. NestedNameSpecifier *NNS =
  440. synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  441. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  442. // Build type location information. We synthesized the qualifier, so we have
  443. // to build a fake NestedNameSpecifierLoc.
  444. NestedNameSpecifierLocBuilder NNSLocBuilder;
  445. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  446. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  447. TypeLocBuilder Builder;
  448. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  449. DepTL.setNameLoc(NameLoc);
  450. DepTL.setElaboratedKeywordLoc(SourceLocation());
  451. DepTL.setQualifierLoc(QualifierLoc);
  452. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  453. }
  454. /// isTagName() - This method is called *for error recovery purposes only*
  455. /// to determine if the specified name is a valid tag name ("struct foo"). If
  456. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  457. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  458. /// cases in C where the user forgot to specify the tag.
  459. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  460. // Do a tag name lookup in this scope.
  461. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  462. LookupName(R, S, false);
  463. R.suppressDiagnostics();
  464. if (R.getResultKind() == LookupResult::Found)
  465. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  466. switch (TD->getTagKind()) {
  467. case TTK_Struct: return DeclSpec::TST_struct;
  468. case TTK_Interface: return DeclSpec::TST_interface;
  469. case TTK_Union: return DeclSpec::TST_union;
  470. case TTK_Class: return DeclSpec::TST_class;
  471. case TTK_Enum: return DeclSpec::TST_enum;
  472. }
  473. }
  474. return DeclSpec::TST_unspecified;
  475. }
  476. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  477. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  478. /// then downgrade the missing typename error to a warning.
  479. /// This is needed for MSVC compatibility; Example:
  480. /// @code
  481. /// template<class T> class A {
  482. /// public:
  483. /// typedef int TYPE;
  484. /// };
  485. /// template<class T> class B : public A<T> {
  486. /// public:
  487. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  488. /// };
  489. /// @endcode
  490. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  491. if (CurContext->isRecord()) {
  492. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  493. return true;
  494. const Type *Ty = SS->getScopeRep()->getAsType();
  495. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  496. for (const auto &Base : RD->bases())
  497. if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  498. return true;
  499. return S->isFunctionPrototypeScope();
  500. }
  501. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  502. }
  503. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  504. SourceLocation IILoc,
  505. Scope *S,
  506. CXXScopeSpec *SS,
  507. ParsedType &SuggestedType,
  508. bool AllowClassTemplates) {
  509. // We don't have anything to suggest (yet).
  510. SuggestedType = ParsedType();
  511. // There may have been a typo in the name of the type. Look up typo
  512. // results, in case we have something that we can suggest.
  513. if (TypoCorrection Corrected =
  514. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  515. llvm::make_unique<TypeNameValidatorCCC>(
  516. false, false, AllowClassTemplates),
  517. CTK_ErrorRecovery)) {
  518. if (Corrected.isKeyword()) {
  519. // We corrected to a keyword.
  520. diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
  521. II = Corrected.getCorrectionAsIdentifierInfo();
  522. } else {
  523. // We found a similarly-named type or interface; suggest that.
  524. if (!SS || !SS->isSet()) {
  525. diagnoseTypo(Corrected,
  526. PDiag(diag::err_unknown_typename_suggest) << II);
  527. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  528. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  529. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  530. II->getName().equals(CorrectedStr);
  531. diagnoseTypo(Corrected,
  532. PDiag(diag::err_unknown_nested_typename_suggest)
  533. << II << DC << DroppedSpecifier << SS->getRange());
  534. } else {
  535. llvm_unreachable("could not have corrected a typo here");
  536. }
  537. CXXScopeSpec tmpSS;
  538. if (Corrected.getCorrectionSpecifier())
  539. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  540. SourceRange(IILoc));
  541. SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
  542. IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
  543. false, ParsedType(),
  544. /*IsCtorOrDtorName=*/false,
  545. /*NonTrivialTypeSourceInfo=*/true);
  546. }
  547. return;
  548. }
  549. if (getLangOpts().CPlusPlus) {
  550. // See if II is a class template that the user forgot to pass arguments to.
  551. UnqualifiedId Name;
  552. Name.setIdentifier(II, IILoc);
  553. CXXScopeSpec EmptySS;
  554. TemplateTy TemplateResult;
  555. bool MemberOfUnknownSpecialization;
  556. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  557. Name, ParsedType(), true, TemplateResult,
  558. MemberOfUnknownSpecialization) == TNK_Type_template) {
  559. TemplateName TplName = TemplateResult.get();
  560. Diag(IILoc, diag::err_template_missing_args) << TplName;
  561. if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
  562. Diag(TplDecl->getLocation(), diag::note_template_decl_here)
  563. << TplDecl->getTemplateParameters()->getSourceRange();
  564. }
  565. return;
  566. }
  567. }
  568. // FIXME: Should we move the logic that tries to recover from a missing tag
  569. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  570. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  571. Diag(IILoc, diag::err_unknown_typename) << II;
  572. else if (DeclContext *DC = computeDeclContext(*SS, false))
  573. Diag(IILoc, diag::err_typename_nested_not_found)
  574. << II << DC << SS->getRange();
  575. else if (isDependentScopeSpecifier(*SS)) {
  576. unsigned DiagID = diag::err_typename_missing;
  577. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  578. DiagID = diag::ext_typename_missing;
  579. Diag(SS->getRange().getBegin(), DiagID)
  580. << SS->getScopeRep() << II->getName()
  581. << SourceRange(SS->getRange().getBegin(), IILoc)
  582. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  583. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  584. *SS, *II, IILoc).get();
  585. } else {
  586. assert(SS && SS->isInvalid() &&
  587. "Invalid scope specifier has already been diagnosed");
  588. }
  589. }
  590. /// \brief Determine whether the given result set contains either a type name
  591. /// or
  592. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  593. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  594. NextToken.is(tok::less);
  595. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  596. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  597. return true;
  598. if (CheckTemplate && isa<TemplateDecl>(*I))
  599. return true;
  600. }
  601. return false;
  602. }
  603. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  604. Scope *S, CXXScopeSpec &SS,
  605. IdentifierInfo *&Name,
  606. SourceLocation NameLoc) {
  607. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  608. SemaRef.LookupParsedName(R, S, &SS);
  609. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  610. StringRef FixItTagName;
  611. switch (Tag->getTagKind()) {
  612. case TTK_Class:
  613. FixItTagName = "class ";
  614. break;
  615. case TTK_Enum:
  616. FixItTagName = "enum ";
  617. break;
  618. case TTK_Struct:
  619. FixItTagName = "struct ";
  620. break;
  621. case TTK_Interface:
  622. FixItTagName = "__interface ";
  623. break;
  624. case TTK_Union:
  625. FixItTagName = "union ";
  626. break;
  627. }
  628. StringRef TagName = FixItTagName.drop_back();
  629. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  630. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  631. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  632. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  633. I != IEnd; ++I)
  634. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  635. << Name << TagName;
  636. // Replace lookup results with just the tag decl.
  637. Result.clear(Sema::LookupTagName);
  638. SemaRef.LookupParsedName(Result, S, &SS);
  639. return true;
  640. }
  641. return false;
  642. }
  643. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  644. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  645. QualType T, SourceLocation NameLoc) {
  646. ASTContext &Context = S.Context;
  647. TypeLocBuilder Builder;
  648. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  649. T = S.getElaboratedType(ETK_None, SS, T);
  650. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  651. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  652. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  653. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  654. }
  655. Sema::NameClassification
  656. Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
  657. SourceLocation NameLoc, const Token &NextToken,
  658. bool IsAddressOfOperand,
  659. std::unique_ptr<CorrectionCandidateCallback> CCC) {
  660. DeclarationNameInfo NameInfo(Name, NameLoc);
  661. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  662. if (NextToken.is(tok::coloncolon)) {
  663. BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
  664. QualType(), false, SS, nullptr, false);
  665. }
  666. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  667. LookupParsedName(Result, S, &SS, !CurMethod);
  668. // For unqualified lookup in a class template in MSVC mode, look into
  669. // dependent base classes where the primary class template is known.
  670. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  671. if (ParsedType TypeInBase =
  672. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  673. return TypeInBase;
  674. }
  675. // Perform lookup for Objective-C instance variables (including automatically
  676. // synthesized instance variables), if we're in an Objective-C method.
  677. // FIXME: This lookup really, really needs to be folded in to the normal
  678. // unqualified lookup mechanism.
  679. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  680. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  681. if (E.get() || E.isInvalid())
  682. return E;
  683. }
  684. bool SecondTry = false;
  685. bool IsFilteredTemplateName = false;
  686. Corrected:
  687. switch (Result.getResultKind()) {
  688. case LookupResult::NotFound:
  689. // If an unqualified-id is followed by a '(', then we have a function
  690. // call.
  691. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  692. // In C++, this is an ADL-only call.
  693. // FIXME: Reference?
  694. if (getLangOpts().CPlusPlus)
  695. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  696. // C90 6.3.2.2:
  697. // If the expression that precedes the parenthesized argument list in a
  698. // function call consists solely of an identifier, and if no
  699. // declaration is visible for this identifier, the identifier is
  700. // implicitly declared exactly as if, in the innermost block containing
  701. // the function call, the declaration
  702. //
  703. // extern int identifier ();
  704. //
  705. // appeared.
  706. //
  707. // We also allow this in C99 as an extension.
  708. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  709. Result.addDecl(D);
  710. Result.resolveKind();
  711. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  712. }
  713. }
  714. // In C, we first see whether there is a tag type by the same name, in
  715. // which case it's likely that the user just forget to write "enum",
  716. // "struct", or "union".
  717. if (!getLangOpts().CPlusPlus && !SecondTry &&
  718. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  719. break;
  720. }
  721. // Perform typo correction to determine if there is another name that is
  722. // close to this name.
  723. if (!SecondTry && CCC) {
  724. SecondTry = true;
  725. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  726. Result.getLookupKind(), S,
  727. &SS, std::move(CCC),
  728. CTK_ErrorRecovery)) {
  729. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  730. unsigned QualifiedDiag = diag::err_no_member_suggest;
  731. NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
  732. NamedDecl *UnderlyingFirstDecl
  733. = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
  734. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  735. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  736. UnqualifiedDiag = diag::err_no_template_suggest;
  737. QualifiedDiag = diag::err_no_member_template_suggest;
  738. } else if (UnderlyingFirstDecl &&
  739. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  740. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  741. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  742. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  743. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  744. }
  745. if (SS.isEmpty()) {
  746. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  747. } else {// FIXME: is this even reachable? Test it.
  748. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  749. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  750. Name->getName().equals(CorrectedStr);
  751. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  752. << Name << computeDeclContext(SS, false)
  753. << DroppedSpecifier << SS.getRange());
  754. }
  755. // Update the name, so that the caller has the new name.
  756. Name = Corrected.getCorrectionAsIdentifierInfo();
  757. // Typo correction corrected to a keyword.
  758. if (Corrected.isKeyword())
  759. return Name;
  760. // Also update the LookupResult...
  761. // FIXME: This should probably go away at some point
  762. Result.clear();
  763. Result.setLookupName(Corrected.getCorrection());
  764. if (FirstDecl)
  765. Result.addDecl(FirstDecl);
  766. // If we found an Objective-C instance variable, let
  767. // LookupInObjCMethod build the appropriate expression to
  768. // reference the ivar.
  769. // FIXME: This is a gross hack.
  770. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  771. Result.clear();
  772. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  773. return E;
  774. }
  775. goto Corrected;
  776. }
  777. }
  778. // We failed to correct; just fall through and let the parser deal with it.
  779. Result.suppressDiagnostics();
  780. return NameClassification::Unknown();
  781. case LookupResult::NotFoundInCurrentInstantiation: {
  782. // We performed name lookup into the current instantiation, and there were
  783. // dependent bases, so we treat this result the same way as any other
  784. // dependent nested-name-specifier.
  785. // C++ [temp.res]p2:
  786. // A name used in a template declaration or definition and that is
  787. // dependent on a template-parameter is assumed not to name a type
  788. // unless the applicable name lookup finds a type name or the name is
  789. // qualified by the keyword typename.
  790. //
  791. // FIXME: If the next token is '<', we might want to ask the parser to
  792. // perform some heroics to see if we actually have a
  793. // template-argument-list, which would indicate a missing 'template'
  794. // keyword here.
  795. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  796. NameInfo, IsAddressOfOperand,
  797. /*TemplateArgs=*/nullptr);
  798. }
  799. case LookupResult::Found:
  800. case LookupResult::FoundOverloaded:
  801. case LookupResult::FoundUnresolvedValue:
  802. break;
  803. case LookupResult::Ambiguous:
  804. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  805. hasAnyAcceptableTemplateNames(Result)) {
  806. // C++ [temp.local]p3:
  807. // A lookup that finds an injected-class-name (10.2) can result in an
  808. // ambiguity in certain cases (for example, if it is found in more than
  809. // one base class). If all of the injected-class-names that are found
  810. // refer to specializations of the same class template, and if the name
  811. // is followed by a template-argument-list, the reference refers to the
  812. // class template itself and not a specialization thereof, and is not
  813. // ambiguous.
  814. //
  815. // This filtering can make an ambiguous result into an unambiguous one,
  816. // so try again after filtering out template names.
  817. FilterAcceptableTemplateNames(Result);
  818. if (!Result.isAmbiguous()) {
  819. IsFilteredTemplateName = true;
  820. break;
  821. }
  822. }
  823. // Diagnose the ambiguity and return an error.
  824. return NameClassification::Error();
  825. }
  826. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  827. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  828. // C++ [temp.names]p3:
  829. // After name lookup (3.4) finds that a name is a template-name or that
  830. // an operator-function-id or a literal- operator-id refers to a set of
  831. // overloaded functions any member of which is a function template if
  832. // this is followed by a <, the < is always taken as the delimiter of a
  833. // template-argument-list and never as the less-than operator.
  834. if (!IsFilteredTemplateName)
  835. FilterAcceptableTemplateNames(Result);
  836. if (!Result.empty()) {
  837. bool IsFunctionTemplate;
  838. bool IsVarTemplate;
  839. TemplateName Template;
  840. if (Result.end() - Result.begin() > 1) {
  841. IsFunctionTemplate = true;
  842. Template = Context.getOverloadedTemplateName(Result.begin(),
  843. Result.end());
  844. } else {
  845. TemplateDecl *TD
  846. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  847. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  848. IsVarTemplate = isa<VarTemplateDecl>(TD);
  849. if (SS.isSet() && !SS.isInvalid())
  850. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  851. /*TemplateKeyword=*/false,
  852. TD);
  853. else
  854. Template = TemplateName(TD);
  855. }
  856. if (IsFunctionTemplate) {
  857. // Function templates always go through overload resolution, at which
  858. // point we'll perform the various checks (e.g., accessibility) we need
  859. // to based on which function we selected.
  860. Result.suppressDiagnostics();
  861. return NameClassification::FunctionTemplate(Template);
  862. }
  863. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  864. : NameClassification::TypeTemplate(Template);
  865. }
  866. }
  867. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  868. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  869. DiagnoseUseOfDecl(Type, NameLoc);
  870. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  871. QualType T = Context.getTypeDeclType(Type);
  872. if (SS.isNotEmpty())
  873. return buildNestedType(*this, SS, T, NameLoc);
  874. return ParsedType::make(T);
  875. }
  876. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  877. if (!Class) {
  878. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  879. if (ObjCCompatibleAliasDecl *Alias =
  880. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  881. Class = Alias->getClassInterface();
  882. }
  883. if (Class) {
  884. DiagnoseUseOfDecl(Class, NameLoc);
  885. if (NextToken.is(tok::period)) {
  886. // Interface. <something> is parsed as a property reference expression.
  887. // Just return "unknown" as a fall-through for now.
  888. Result.suppressDiagnostics();
  889. return NameClassification::Unknown();
  890. }
  891. QualType T = Context.getObjCInterfaceType(Class);
  892. return ParsedType::make(T);
  893. }
  894. // We can have a type template here if we're classifying a template argument.
  895. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
  896. return NameClassification::TypeTemplate(
  897. TemplateName(cast<TemplateDecl>(FirstDecl)));
  898. // Check for a tag type hidden by a non-type decl in a few cases where it
  899. // seems likely a type is wanted instead of the non-type that was found.
  900. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  901. if ((NextToken.is(tok::identifier) ||
  902. (NextIsOp &&
  903. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  904. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  905. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  906. DiagnoseUseOfDecl(Type, NameLoc);
  907. QualType T = Context.getTypeDeclType(Type);
  908. if (SS.isNotEmpty())
  909. return buildNestedType(*this, SS, T, NameLoc);
  910. return ParsedType::make(T);
  911. }
  912. if (FirstDecl->isCXXClassMember())
  913. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  914. nullptr, S);
  915. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  916. return BuildDeclarationNameExpr(SS, Result, ADL);
  917. }
  918. // Determines the context to return to after temporarily entering a
  919. // context. This depends in an unnecessarily complicated way on the
  920. // exact ordering of callbacks from the parser.
  921. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  922. // Functions defined inline within classes aren't parsed until we've
  923. // finished parsing the top-level class, so the top-level class is
  924. // the context we'll need to return to.
  925. // A Lambda call operator whose parent is a class must not be treated
  926. // as an inline member function. A Lambda can be used legally
  927. // either as an in-class member initializer or a default argument. These
  928. // are parsed once the class has been marked complete and so the containing
  929. // context would be the nested class (when the lambda is defined in one);
  930. // If the class is not complete, then the lambda is being used in an
  931. // ill-formed fashion (such as to specify the width of a bit-field, or
  932. // in an array-bound) - in which case we still want to return the
  933. // lexically containing DC (which could be a nested class).
  934. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  935. DC = DC->getLexicalParent();
  936. // A function not defined within a class will always return to its
  937. // lexical context.
  938. if (!isa<CXXRecordDecl>(DC))
  939. return DC;
  940. // A C++ inline method/friend is parsed *after* the topmost class
  941. // it was declared in is fully parsed ("complete"); the topmost
  942. // class is the context we need to return to.
  943. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  944. DC = RD;
  945. // Return the declaration context of the topmost class the inline method is
  946. // declared in.
  947. return DC;
  948. }
  949. return DC->getLexicalParent();
  950. }
  951. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  952. assert(getContainingDC(DC) == CurContext &&
  953. "The next DeclContext should be lexically contained in the current one.");
  954. CurContext = DC;
  955. S->setEntity(DC);
  956. }
  957. void Sema::PopDeclContext() {
  958. assert(CurContext && "DeclContext imbalance!");
  959. CurContext = getContainingDC(CurContext);
  960. assert(CurContext && "Popped translation unit!");
  961. }
  962. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  963. Decl *D) {
  964. // Unlike PushDeclContext, the context to which we return is not necessarily
  965. // the containing DC of TD, because the new context will be some pre-existing
  966. // TagDecl definition instead of a fresh one.
  967. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  968. CurContext = cast<TagDecl>(D)->getDefinition();
  969. assert(CurContext && "skipping definition of undefined tag");
  970. // Start lookups from the parent of the current context; we don't want to look
  971. // into the pre-existing complete definition.
  972. S->setEntity(CurContext->getLookupParent());
  973. return Result;
  974. }
  975. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  976. CurContext = static_cast<decltype(CurContext)>(Context);
  977. }
  978. /// EnterDeclaratorContext - Used when we must lookup names in the context
  979. /// of a declarator's nested name specifier.
  980. ///
  981. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  982. // C++0x [basic.lookup.unqual]p13:
  983. // A name used in the definition of a static data member of class
  984. // X (after the qualified-id of the static member) is looked up as
  985. // if the name was used in a member function of X.
  986. // C++0x [basic.lookup.unqual]p14:
  987. // If a variable member of a namespace is defined outside of the
  988. // scope of its namespace then any name used in the definition of
  989. // the variable member (after the declarator-id) is looked up as
  990. // if the definition of the variable member occurred in its
  991. // namespace.
  992. // Both of these imply that we should push a scope whose context
  993. // is the semantic context of the declaration. We can't use
  994. // PushDeclContext here because that context is not necessarily
  995. // lexically contained in the current context. Fortunately,
  996. // the containing scope should have the appropriate information.
  997. assert(!S->getEntity() && "scope already has entity");
  998. #ifndef NDEBUG
  999. Scope *Ancestor = S->getParent();
  1000. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1001. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1002. #endif
  1003. CurContext = DC;
  1004. S->setEntity(DC);
  1005. }
  1006. void Sema::ExitDeclaratorContext(Scope *S) {
  1007. assert(S->getEntity() == CurContext && "Context imbalance!");
  1008. // Switch back to the lexical context. The safety of this is
  1009. // enforced by an assert in EnterDeclaratorContext.
  1010. Scope *Ancestor = S->getParent();
  1011. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1012. CurContext = Ancestor->getEntity();
  1013. // We don't need to do anything with the scope, which is going to
  1014. // disappear.
  1015. }
  1016. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1017. // We assume that the caller has already called
  1018. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1019. FunctionDecl *FD = D->getAsFunction();
  1020. if (!FD)
  1021. return;
  1022. // Same implementation as PushDeclContext, but enters the context
  1023. // from the lexical parent, rather than the top-level class.
  1024. assert(CurContext == FD->getLexicalParent() &&
  1025. "The next DeclContext should be lexically contained in the current one.");
  1026. CurContext = FD;
  1027. S->setEntity(CurContext);
  1028. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1029. ParmVarDecl *Param = FD->getParamDecl(P);
  1030. // If the parameter has an identifier, then add it to the scope
  1031. if (Param->getIdentifier()) {
  1032. S->AddDecl(Param);
  1033. IdResolver.AddDecl(Param);
  1034. }
  1035. }
  1036. }
  1037. void Sema::ActOnExitFunctionContext() {
  1038. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1039. // rather than the top-level class.
  1040. assert(CurContext && "DeclContext imbalance!");
  1041. CurContext = CurContext->getLexicalParent();
  1042. assert(CurContext && "Popped translation unit!");
  1043. }
  1044. /// \brief Determine whether we allow overloading of the function
  1045. /// PrevDecl with another declaration.
  1046. ///
  1047. /// This routine determines whether overloading is possible, not
  1048. /// whether some new function is actually an overload. It will return
  1049. /// true in C++ (where we can always provide overloads) or, as an
  1050. /// extension, in C when the previous function is already an
  1051. /// overloaded function declaration or has the "overloadable"
  1052. /// attribute.
  1053. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1054. ASTContext &Context) {
  1055. if (Context.getLangOpts().CPlusPlus)
  1056. return true;
  1057. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1058. return true;
  1059. return (Previous.getResultKind() == LookupResult::Found
  1060. && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
  1061. }
  1062. /// Add this decl to the scope shadowed decl chains.
  1063. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1064. // Move up the scope chain until we find the nearest enclosing
  1065. // non-transparent context. The declaration will be introduced into this
  1066. // scope.
  1067. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1068. S = S->getParent();
  1069. // Add scoped declarations into their context, so that they can be
  1070. // found later. Declarations without a context won't be inserted
  1071. // into any context.
  1072. if (AddToContext)
  1073. CurContext->addDecl(D);
  1074. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1075. // are function-local declarations.
  1076. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1077. !D->getDeclContext()->getRedeclContext()->Equals(
  1078. D->getLexicalDeclContext()->getRedeclContext()) &&
  1079. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1080. return;
  1081. // Template instantiations should also not be pushed into scope.
  1082. if (isa<FunctionDecl>(D) &&
  1083. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1084. return;
  1085. // If this replaces anything in the current scope,
  1086. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1087. IEnd = IdResolver.end();
  1088. for (; I != IEnd; ++I) {
  1089. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1090. S->RemoveDecl(*I);
  1091. IdResolver.RemoveDecl(*I);
  1092. // Should only need to replace one decl.
  1093. break;
  1094. }
  1095. }
  1096. S->AddDecl(D);
  1097. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1098. // Implicitly-generated labels may end up getting generated in an order that
  1099. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1100. // the label at the appropriate place in the identifier chain.
  1101. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1102. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1103. if (IDC == CurContext) {
  1104. if (!S->isDeclScope(*I))
  1105. continue;
  1106. } else if (IDC->Encloses(CurContext))
  1107. break;
  1108. }
  1109. IdResolver.InsertDeclAfter(I, D);
  1110. } else {
  1111. IdResolver.AddDecl(D);
  1112. }
  1113. }
  1114. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  1115. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  1116. TUScope->AddDecl(D);
  1117. }
  1118. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1119. bool AllowInlineNamespace) {
  1120. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1121. }
  1122. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1123. DeclContext *TargetDC = DC->getPrimaryContext();
  1124. do {
  1125. if (DeclContext *ScopeDC = S->getEntity())
  1126. if (ScopeDC->getPrimaryContext() == TargetDC)
  1127. return S;
  1128. } while ((S = S->getParent()));
  1129. return nullptr;
  1130. }
  1131. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1132. DeclContext*,
  1133. ASTContext&);
  1134. /// Filters out lookup results that don't fall within the given scope
  1135. /// as determined by isDeclInScope.
  1136. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1137. bool ConsiderLinkage,
  1138. bool AllowInlineNamespace) {
  1139. LookupResult::Filter F = R.makeFilter();
  1140. while (F.hasNext()) {
  1141. NamedDecl *D = F.next();
  1142. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1143. continue;
  1144. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1145. continue;
  1146. F.erase();
  1147. }
  1148. F.done();
  1149. }
  1150. static bool isUsingDecl(NamedDecl *D) {
  1151. return isa<UsingShadowDecl>(D) ||
  1152. isa<UnresolvedUsingTypenameDecl>(D) ||
  1153. isa<UnresolvedUsingValueDecl>(D);
  1154. }
  1155. /// Removes using shadow declarations from the lookup results.
  1156. static void RemoveUsingDecls(LookupResult &R) {
  1157. LookupResult::Filter F = R.makeFilter();
  1158. while (F.hasNext())
  1159. if (isUsingDecl(F.next()))
  1160. F.erase();
  1161. F.done();
  1162. }
  1163. /// \brief Check for this common pattern:
  1164. /// @code
  1165. /// class S {
  1166. /// S(const S&); // DO NOT IMPLEMENT
  1167. /// void operator=(const S&); // DO NOT IMPLEMENT
  1168. /// };
  1169. /// @endcode
  1170. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1171. // FIXME: Should check for private access too but access is set after we get
  1172. // the decl here.
  1173. if (D->doesThisDeclarationHaveABody())
  1174. return false;
  1175. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1176. return CD->isCopyConstructor();
  1177. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  1178. return Method->isCopyAssignmentOperator();
  1179. return false;
  1180. }
  1181. // We need this to handle
  1182. //
  1183. // typedef struct {
  1184. // void *foo() { return 0; }
  1185. // } A;
  1186. //
  1187. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1188. // for example. If 'A', foo will have external linkage. If we have '*A',
  1189. // foo will have no linkage. Since we can't know until we get to the end
  1190. // of the typedef, this function finds out if D might have non-external linkage.
  1191. // Callers should verify at the end of the TU if it D has external linkage or
  1192. // not.
  1193. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1194. const DeclContext *DC = D->getDeclContext();
  1195. while (!DC->isTranslationUnit()) {
  1196. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1197. if (!RD->hasNameForLinkage())
  1198. return true;
  1199. }
  1200. DC = DC->getParent();
  1201. }
  1202. return !D->isExternallyVisible();
  1203. }
  1204. // FIXME: This needs to be refactored; some other isInMainFile users want
  1205. // these semantics.
  1206. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1207. if (S.TUKind != TU_Complete)
  1208. return false;
  1209. return S.SourceMgr.isInMainFile(Loc);
  1210. }
  1211. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1212. assert(D);
  1213. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1214. return false;
  1215. // Ignore all entities declared within templates, and out-of-line definitions
  1216. // of members of class templates.
  1217. if (D->getDeclContext()->isDependentContext() ||
  1218. D->getLexicalDeclContext()->isDependentContext())
  1219. return false;
  1220. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1221. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1222. return false;
  1223. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1224. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1225. return false;
  1226. } else {
  1227. // 'static inline' functions are defined in headers; don't warn.
  1228. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1229. return false;
  1230. }
  1231. if (FD->doesThisDeclarationHaveABody() &&
  1232. Context.DeclMustBeEmitted(FD))
  1233. return false;
  1234. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1235. // Constants and utility variables are defined in headers with internal
  1236. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1237. // like "inline".)
  1238. if (!isMainFileLoc(*this, VD->getLocation()))
  1239. return false;
  1240. if (Context.DeclMustBeEmitted(VD))
  1241. return false;
  1242. if (VD->isStaticDataMember() &&
  1243. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1244. return false;
  1245. } else {
  1246. return false;
  1247. }
  1248. // Only warn for unused decls internal to the translation unit.
  1249. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1250. // for inline functions defined in the main source file, for instance.
  1251. return mightHaveNonExternalLinkage(D);
  1252. }
  1253. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1254. if (!D)
  1255. return;
  1256. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1257. const FunctionDecl *First = FD->getFirstDecl();
  1258. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1259. return; // First should already be in the vector.
  1260. }
  1261. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1262. const VarDecl *First = VD->getFirstDecl();
  1263. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1264. return; // First should already be in the vector.
  1265. }
  1266. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1267. UnusedFileScopedDecls.push_back(D);
  1268. }
  1269. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1270. if (D->isInvalidDecl())
  1271. return false;
  1272. if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
  1273. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1274. return false;
  1275. if (isa<LabelDecl>(D))
  1276. return true;
  1277. // Except for labels, we only care about unused decls that are local to
  1278. // functions.
  1279. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1280. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1281. // For dependent types, the diagnostic is deferred.
  1282. WithinFunction =
  1283. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1284. if (!WithinFunction)
  1285. return false;
  1286. if (isa<TypedefNameDecl>(D))
  1287. return true;
  1288. // White-list anything that isn't a local variable.
  1289. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1290. return false;
  1291. // Types of valid local variables should be complete, so this should succeed.
  1292. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1293. // White-list anything with an __attribute__((unused)) type.
  1294. QualType Ty = VD->getType();
  1295. // Only look at the outermost level of typedef.
  1296. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1297. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1298. return false;
  1299. }
  1300. // If we failed to complete the type for some reason, or if the type is
  1301. // dependent, don't diagnose the variable.
  1302. if (Ty->isIncompleteType() || Ty->isDependentType())
  1303. return false;
  1304. if (const TagType *TT = Ty->getAs<TagType>()) {
  1305. const TagDecl *Tag = TT->getDecl();
  1306. if (Tag->hasAttr<UnusedAttr>())
  1307. return false;
  1308. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1309. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1310. return false;
  1311. if (const Expr *Init = VD->getInit()) {
  1312. if (const ExprWithCleanups *Cleanups =
  1313. dyn_cast<ExprWithCleanups>(Init))
  1314. Init = Cleanups->getSubExpr();
  1315. const CXXConstructExpr *Construct =
  1316. dyn_cast<CXXConstructExpr>(Init);
  1317. if (Construct && !Construct->isElidable()) {
  1318. CXXConstructorDecl *CD = Construct->getConstructor();
  1319. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
  1320. return false;
  1321. }
  1322. }
  1323. }
  1324. }
  1325. // TODO: __attribute__((unused)) templates?
  1326. }
  1327. return true;
  1328. }
  1329. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1330. FixItHint &Hint) {
  1331. if (isa<LabelDecl>(D)) {
  1332. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1333. tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
  1334. if (AfterColon.isInvalid())
  1335. return;
  1336. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1337. getCharRange(D->getLocStart(), AfterColon));
  1338. }
  1339. return;
  1340. }
  1341. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1342. if (D->getTypeForDecl()->isDependentType())
  1343. return;
  1344. for (auto *TmpD : D->decls()) {
  1345. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1346. DiagnoseUnusedDecl(T);
  1347. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1348. DiagnoseUnusedNestedTypedefs(R);
  1349. }
  1350. }
  1351. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1352. /// unless they are marked attr(unused).
  1353. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1354. if (!ShouldDiagnoseUnusedDecl(D))
  1355. return;
  1356. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1357. // typedefs can be referenced later on, so the diagnostics are emitted
  1358. // at end-of-translation-unit.
  1359. UnusedLocalTypedefNameCandidates.insert(TD);
  1360. return;
  1361. }
  1362. FixItHint Hint;
  1363. GenerateFixForUnusedDecl(D, Context, Hint);
  1364. unsigned DiagID;
  1365. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1366. DiagID = diag::warn_unused_exception_param;
  1367. else if (isa<LabelDecl>(D))
  1368. DiagID = diag::warn_unused_label;
  1369. else
  1370. DiagID = diag::warn_unused_variable;
  1371. Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
  1372. }
  1373. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1374. // Verify that we have no forward references left. If so, there was a goto
  1375. // or address of a label taken, but no definition of it. Label fwd
  1376. // definitions are indicated with a null substmt which is also not a resolved
  1377. // MS inline assembly label name.
  1378. bool Diagnose = false;
  1379. if (L->isMSAsmLabel())
  1380. Diagnose = !L->isResolvedMSAsmLabel();
  1381. else
  1382. Diagnose = L->getStmt() == nullptr;
  1383. if (Diagnose)
  1384. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1385. }
  1386. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1387. S->mergeNRVOIntoParent();
  1388. if (S->decl_empty()) return;
  1389. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1390. "Scope shouldn't contain decls!");
  1391. for (auto *TmpD : S->decls()) {
  1392. assert(TmpD && "This decl didn't get pushed??");
  1393. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1394. NamedDecl *D = cast<NamedDecl>(TmpD);
  1395. if (!D->getDeclName()) continue;
  1396. // Diagnose unused variables in this scope.
  1397. if (!S->hasUnrecoverableErrorOccurred()) {
  1398. DiagnoseUnusedDecl(D);
  1399. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1400. DiagnoseUnusedNestedTypedefs(RD);
  1401. }
  1402. // If this was a forward reference to a label, verify it was defined.
  1403. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1404. CheckPoppedLabel(LD, *this);
  1405. // Remove this name from our lexical scope.
  1406. IdResolver.RemoveDecl(D);
  1407. }
  1408. }
  1409. /// \brief Look for an Objective-C class in the translation unit.
  1410. ///
  1411. /// \param Id The name of the Objective-C class we're looking for. If
  1412. /// typo-correction fixes this name, the Id will be updated
  1413. /// to the fixed name.
  1414. ///
  1415. /// \param IdLoc The location of the name in the translation unit.
  1416. ///
  1417. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1418. /// if there is no class with the given name.
  1419. ///
  1420. /// \returns The declaration of the named Objective-C class, or NULL if the
  1421. /// class could not be found.
  1422. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1423. SourceLocation IdLoc,
  1424. bool DoTypoCorrection) {
  1425. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1426. // creation from this context.
  1427. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1428. if (!IDecl && DoTypoCorrection) {
  1429. // Perform typo correction at the given location, but only if we
  1430. // find an Objective-C class name.
  1431. if (TypoCorrection C = CorrectTypo(
  1432. DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
  1433. llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
  1434. CTK_ErrorRecovery)) {
  1435. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1436. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1437. Id = IDecl->getIdentifier();
  1438. }
  1439. }
  1440. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1441. // This routine must always return a class definition, if any.
  1442. if (Def && Def->getDefinition())
  1443. Def = Def->getDefinition();
  1444. return Def;
  1445. }
  1446. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1447. /// from S, where a non-field would be declared. This routine copes
  1448. /// with the difference between C and C++ scoping rules in structs and
  1449. /// unions. For example, the following code is well-formed in C but
  1450. /// ill-formed in C++:
  1451. /// @code
  1452. /// struct S6 {
  1453. /// enum { BAR } e;
  1454. /// };
  1455. ///
  1456. /// void test_S6() {
  1457. /// struct S6 a;
  1458. /// a.e = BAR;
  1459. /// }
  1460. /// @endcode
  1461. /// For the declaration of BAR, this routine will return a different
  1462. /// scope. The scope S will be the scope of the unnamed enumeration
  1463. /// within S6. In C++, this routine will return the scope associated
  1464. /// with S6, because the enumeration's scope is a transparent
  1465. /// context but structures can contain non-field names. In C, this
  1466. /// routine will return the translation unit scope, since the
  1467. /// enumeration's scope is a transparent context and structures cannot
  1468. /// contain non-field names.
  1469. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1470. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1471. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1472. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1473. S = S->getParent();
  1474. return S;
  1475. }
  1476. /// \brief Looks up the declaration of "struct objc_super" and
  1477. /// saves it for later use in building builtin declaration of
  1478. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1479. /// pre-existing declaration exists no action takes place.
  1480. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1481. IdentifierInfo *II) {
  1482. if (!II->isStr("objc_msgSendSuper"))
  1483. return;
  1484. ASTContext &Context = ThisSema.Context;
  1485. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1486. SourceLocation(), Sema::LookupTagName);
  1487. ThisSema.LookupName(Result, S);
  1488. if (Result.getResultKind() == LookupResult::Found)
  1489. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1490. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1491. }
  1492. static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
  1493. switch (Error) {
  1494. case ASTContext::GE_None:
  1495. return "";
  1496. case ASTContext::GE_Missing_stdio:
  1497. return "stdio.h";
  1498. case ASTContext::GE_Missing_setjmp:
  1499. return "setjmp.h";
  1500. case ASTContext::GE_Missing_ucontext:
  1501. return "ucontext.h";
  1502. }
  1503. llvm_unreachable("unhandled error kind");
  1504. }
  1505. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1506. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1507. /// if we're creating this built-in in anticipation of redeclaring the
  1508. /// built-in.
  1509. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1510. Scope *S, bool ForRedeclaration,
  1511. SourceLocation Loc) {
  1512. LookupPredefedObjCSuperType(*this, S, II);
  1513. ASTContext::GetBuiltinTypeError Error;
  1514. QualType R = Context.GetBuiltinType(ID, Error);
  1515. if (Error) {
  1516. if (ForRedeclaration)
  1517. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1518. << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
  1519. return nullptr;
  1520. }
  1521. if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
  1522. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1523. << Context.BuiltinInfo.getName(ID) << R;
  1524. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1525. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1526. Diag(Loc, diag::note_include_header_or_declare)
  1527. << Context.BuiltinInfo.getHeaderName(ID)
  1528. << Context.BuiltinInfo.getName(ID);
  1529. }
  1530. DeclContext *Parent = Context.getTranslationUnitDecl();
  1531. if (getLangOpts().CPlusPlus) {
  1532. LinkageSpecDecl *CLinkageDecl =
  1533. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1534. LinkageSpecDecl::lang_c, false);
  1535. CLinkageDecl->setImplicit();
  1536. Parent->addDecl(CLinkageDecl);
  1537. Parent = CLinkageDecl;
  1538. }
  1539. FunctionDecl *New = FunctionDecl::Create(Context,
  1540. Parent,
  1541. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1542. SC_Extern,
  1543. false,
  1544. R->isFunctionProtoType());
  1545. New->setImplicit();
  1546. // Create Decl objects for each parameter, adding them to the
  1547. // FunctionDecl.
  1548. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1549. SmallVector<ParmVarDecl*, 16> Params;
  1550. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1551. ParmVarDecl *parm =
  1552. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1553. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1554. SC_None, nullptr);
  1555. parm->setScopeInfo(0, i);
  1556. Params.push_back(parm);
  1557. }
  1558. New->setParams(Params);
  1559. }
  1560. AddKnownFunctionAttributes(New);
  1561. RegisterLocallyScopedExternCDecl(New, S);
  1562. // TUScope is the translation-unit scope to insert this function into.
  1563. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1564. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1565. // entirely, but we're not there yet.
  1566. DeclContext *SavedContext = CurContext;
  1567. CurContext = Parent;
  1568. PushOnScopeChains(New, TUScope);
  1569. CurContext = SavedContext;
  1570. return New;
  1571. }
  1572. /// Typedef declarations don't have linkage, but they still denote the same
  1573. /// entity if their types are the same.
  1574. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1575. /// isSameEntity.
  1576. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1577. TypedefNameDecl *Decl,
  1578. LookupResult &Previous) {
  1579. // This is only interesting when modules are enabled.
  1580. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1581. return;
  1582. // Empty sets are uninteresting.
  1583. if (Previous.empty())
  1584. return;
  1585. LookupResult::Filter Filter = Previous.makeFilter();
  1586. while (Filter.hasNext()) {
  1587. NamedDecl *Old = Filter.next();
  1588. // Non-hidden declarations are never ignored.
  1589. if (S.isVisible(Old))
  1590. continue;
  1591. // Declarations of the same entity are not ignored, even if they have
  1592. // different linkages.
  1593. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1594. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1595. Decl->getUnderlyingType()))
  1596. continue;
  1597. // If both declarations give a tag declaration a typedef name for linkage
  1598. // purposes, then they declare the same entity.
  1599. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1600. Decl->getAnonDeclWithTypedefName())
  1601. continue;
  1602. }
  1603. if (!Old->isExternallyVisible())
  1604. Filter.erase();
  1605. }
  1606. Filter.done();
  1607. }
  1608. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1609. QualType OldType;
  1610. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1611. OldType = OldTypedef->getUnderlyingType();
  1612. else
  1613. OldType = Context.getTypeDeclType(Old);
  1614. QualType NewType = New->getUnderlyingType();
  1615. if (NewType->isVariablyModifiedType()) {
  1616. // Must not redefine a typedef with a variably-modified type.
  1617. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1618. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1619. << Kind << NewType;
  1620. if (Old->getLocation().isValid())
  1621. Diag(Old->getLocation(), diag::note_previous_definition);
  1622. New->setInvalidDecl();
  1623. return true;
  1624. }
  1625. if (OldType != NewType &&
  1626. !OldType->isDependentType() &&
  1627. !NewType->isDependentType() &&
  1628. !Context.hasSameType(OldType, NewType)) {
  1629. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1630. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1631. << Kind << NewType << OldType;
  1632. if (Old->getLocation().isValid())
  1633. Diag(Old->getLocation(), diag::note_previous_definition);
  1634. New->setInvalidDecl();
  1635. return true;
  1636. }
  1637. return false;
  1638. }
  1639. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1640. /// same name and scope as a previous declaration 'Old'. Figure out
  1641. /// how to resolve this situation, merging decls or emitting
  1642. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1643. ///
  1644. void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
  1645. // If the new decl is known invalid already, don't bother doing any
  1646. // merging checks.
  1647. if (New->isInvalidDecl()) return;
  1648. // Allow multiple definitions for ObjC built-in typedefs.
  1649. // FIXME: Verify the underlying types are equivalent!
  1650. if (getLangOpts().ObjC1) {
  1651. const IdentifierInfo *TypeID = New->getIdentifier();
  1652. switch (TypeID->getLength()) {
  1653. default: break;
  1654. case 2:
  1655. {
  1656. if (!TypeID->isStr("id"))
  1657. break;
  1658. QualType T = New->getUnderlyingType();
  1659. if (!T->isPointerType())
  1660. break;
  1661. if (!T->isVoidPointerType()) {
  1662. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1663. if (!PT->isStructureType())
  1664. break;
  1665. }
  1666. Context.setObjCIdRedefinitionType(T);
  1667. // Install the built-in type for 'id', ignoring the current definition.
  1668. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1669. return;
  1670. }
  1671. case 5:
  1672. if (!TypeID->isStr("Class"))
  1673. break;
  1674. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1675. // Install the built-in type for 'Class', ignoring the current definition.
  1676. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1677. return;
  1678. case 3:
  1679. if (!TypeID->isStr("SEL"))
  1680. break;
  1681. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1682. // Install the built-in type for 'SEL', ignoring the current definition.
  1683. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1684. return;
  1685. }
  1686. // Fall through - the typedef name was not a builtin type.
  1687. }
  1688. // Verify the old decl was also a type.
  1689. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1690. if (!Old) {
  1691. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1692. << New->getDeclName();
  1693. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1694. if (OldD->getLocation().isValid())
  1695. Diag(OldD->getLocation(), diag::note_previous_definition);
  1696. return New->setInvalidDecl();
  1697. }
  1698. // If the old declaration is invalid, just give up here.
  1699. if (Old->isInvalidDecl())
  1700. return New->setInvalidDecl();
  1701. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1702. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1703. auto *NewTag = New->getAnonDeclWithTypedefName();
  1704. NamedDecl *Hidden = nullptr;
  1705. if (getLangOpts().CPlusPlus && OldTag && NewTag &&
  1706. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1707. !hasVisibleDefinition(OldTag, &Hidden)) {
  1708. // There is a definition of this tag, but it is not visible. Use it
  1709. // instead of our tag.
  1710. New->setTypeForDecl(OldTD->getTypeForDecl());
  1711. if (OldTD->isModed())
  1712. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1713. OldTD->getUnderlyingType());
  1714. else
  1715. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1716. // Make the old tag definition visible.
  1717. makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
  1718. }
  1719. }
  1720. // If the typedef types are not identical, reject them in all languages and
  1721. // with any extensions enabled.
  1722. if (isIncompatibleTypedef(Old, New))
  1723. return;
  1724. // The types match. Link up the redeclaration chain and merge attributes if
  1725. // the old declaration was a typedef.
  1726. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1727. New->setPreviousDecl(Typedef);
  1728. mergeDeclAttributes(New, Old);
  1729. }
  1730. if (getLangOpts().MicrosoftExt)
  1731. return;
  1732. if (getLangOpts().CPlusPlus) {
  1733. // C++ [dcl.typedef]p2:
  1734. // In a given non-class scope, a typedef specifier can be used to
  1735. // redefine the name of any type declared in that scope to refer
  1736. // to the type to which it already refers.
  1737. if (!isa<CXXRecordDecl>(CurContext))
  1738. return;
  1739. // C++0x [dcl.typedef]p4:
  1740. // In a given class scope, a typedef specifier can be used to redefine
  1741. // any class-name declared in that scope that is not also a typedef-name
  1742. // to refer to the type to which it already refers.
  1743. //
  1744. // This wording came in via DR424, which was a correction to the
  1745. // wording in DR56, which accidentally banned code like:
  1746. //
  1747. // struct S {
  1748. // typedef struct A { } A;
  1749. // };
  1750. //
  1751. // in the C++03 standard. We implement the C++0x semantics, which
  1752. // allow the above but disallow
  1753. //
  1754. // struct S {
  1755. // typedef int I;
  1756. // typedef int I;
  1757. // };
  1758. //
  1759. // since that was the intent of DR56.
  1760. if (!isa<TypedefNameDecl>(Old))
  1761. return;
  1762. Diag(New->getLocation(), diag::err_redefinition)
  1763. << New->getDeclName();
  1764. Diag(Old->getLocation(), diag::note_previous_definition);
  1765. return New->setInvalidDecl();
  1766. }
  1767. // Modules always permit redefinition of typedefs, as does C11.
  1768. if (getLangOpts().Modules || getLangOpts().C11)
  1769. return;
  1770. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1771. // is normally mapped to an error, but can be controlled with
  1772. // -Wtypedef-redefinition. If either the original or the redefinition is
  1773. // in a system header, don't emit this for compatibility with GCC.
  1774. if (getDiagnostics().getSuppressSystemWarnings() &&
  1775. (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1776. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1777. return;
  1778. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  1779. << New->getDeclName();
  1780. Diag(Old->getLocation(), diag::note_previous_definition);
  1781. }
  1782. /// DeclhasAttr - returns true if decl Declaration already has the target
  1783. /// attribute.
  1784. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  1785. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  1786. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  1787. for (const auto *i : D->attrs())
  1788. if (i->getKind() == A->getKind()) {
  1789. if (Ann) {
  1790. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  1791. return true;
  1792. continue;
  1793. }
  1794. // FIXME: Don't hardcode this check
  1795. if (OA && isa<OwnershipAttr>(i))
  1796. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  1797. return true;
  1798. }
  1799. return false;
  1800. }
  1801. static bool isAttributeTargetADefinition(Decl *D) {
  1802. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  1803. return VD->isThisDeclarationADefinition();
  1804. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  1805. return TD->isCompleteDefinition() || TD->isBeingDefined();
  1806. return true;
  1807. }
  1808. /// Merge alignment attributes from \p Old to \p New, taking into account the
  1809. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  1810. ///
  1811. /// \return \c true if any attributes were added to \p New.
  1812. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  1813. // Look for alignas attributes on Old, and pick out whichever attribute
  1814. // specifies the strictest alignment requirement.
  1815. AlignedAttr *OldAlignasAttr = nullptr;
  1816. AlignedAttr *OldStrictestAlignAttr = nullptr;
  1817. unsigned OldAlign = 0;
  1818. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  1819. // FIXME: We have no way of representing inherited dependent alignments
  1820. // in a case like:
  1821. // template<int A, int B> struct alignas(A) X;
  1822. // template<int A, int B> struct alignas(B) X {};
  1823. // For now, we just ignore any alignas attributes which are not on the
  1824. // definition in such a case.
  1825. if (I->isAlignmentDependent())
  1826. return false;
  1827. if (I->isAlignas())
  1828. OldAlignasAttr = I;
  1829. unsigned Align = I->getAlignment(S.Context);
  1830. if (Align > OldAlign) {
  1831. OldAlign = Align;
  1832. OldStrictestAlignAttr = I;
  1833. }
  1834. }
  1835. // Look for alignas attributes on New.
  1836. AlignedAttr *NewAlignasAttr = nullptr;
  1837. unsigned NewAlign = 0;
  1838. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  1839. if (I->isAlignmentDependent())
  1840. return false;
  1841. if (I->isAlignas())
  1842. NewAlignasAttr = I;
  1843. unsigned Align = I->getAlignment(S.Context);
  1844. if (Align > NewAlign)
  1845. NewAlign = Align;
  1846. }
  1847. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  1848. // Both declarations have 'alignas' attributes. We require them to match.
  1849. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  1850. // fall short. (If two declarations both have alignas, they must both match
  1851. // every definition, and so must match each other if there is a definition.)
  1852. // If either declaration only contains 'alignas(0)' specifiers, then it
  1853. // specifies the natural alignment for the type.
  1854. if (OldAlign == 0 || NewAlign == 0) {
  1855. QualType Ty;
  1856. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  1857. Ty = VD->getType();
  1858. else
  1859. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  1860. if (OldAlign == 0)
  1861. OldAlign = S.Context.getTypeAlign(Ty);
  1862. if (NewAlign == 0)
  1863. NewAlign = S.Context.getTypeAlign(Ty);
  1864. }
  1865. if (OldAlign != NewAlign) {
  1866. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  1867. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  1868. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  1869. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  1870. }
  1871. }
  1872. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  1873. // C++11 [dcl.align]p6:
  1874. // if any declaration of an entity has an alignment-specifier,
  1875. // every defining declaration of that entity shall specify an
  1876. // equivalent alignment.
  1877. // C11 6.7.5/7:
  1878. // If the definition of an object does not have an alignment
  1879. // specifier, any other declaration of that object shall also
  1880. // have no alignment specifier.
  1881. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  1882. << OldAlignasAttr;
  1883. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  1884. << OldAlignasAttr;
  1885. }
  1886. bool AnyAdded = false;
  1887. // Ensure we have an attribute representing the strictest alignment.
  1888. if (OldAlign > NewAlign) {
  1889. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  1890. Clone->setInherited(true);
  1891. New->addAttr(Clone);
  1892. AnyAdded = true;
  1893. }
  1894. // Ensure we have an alignas attribute if the old declaration had one.
  1895. if (OldAlignasAttr && !NewAlignasAttr &&
  1896. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  1897. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  1898. Clone->setInherited(true);
  1899. New->addAttr(Clone);
  1900. AnyAdded = true;
  1901. }
  1902. return AnyAdded;
  1903. }
  1904. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  1905. const InheritableAttr *Attr, bool Override) {
  1906. InheritableAttr *NewAttr = nullptr;
  1907. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  1908. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  1909. NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
  1910. AA->getIntroduced(), AA->getDeprecated(),
  1911. AA->getObsoleted(), AA->getUnavailable(),
  1912. AA->getMessage(), Override,
  1913. AttrSpellingListIndex);
  1914. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  1915. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  1916. AttrSpellingListIndex);
  1917. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  1918. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  1919. AttrSpellingListIndex);
  1920. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  1921. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  1922. AttrSpellingListIndex);
  1923. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  1924. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  1925. AttrSpellingListIndex);
  1926. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  1927. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  1928. FA->getFormatIdx(), FA->getFirstArg(),
  1929. AttrSpellingListIndex);
  1930. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  1931. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  1932. AttrSpellingListIndex);
  1933. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  1934. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  1935. AttrSpellingListIndex,
  1936. IA->getSemanticSpelling());
  1937. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  1938. NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
  1939. &S.Context.Idents.get(AA->getSpelling()),
  1940. AttrSpellingListIndex);
  1941. else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  1942. NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
  1943. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  1944. NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
  1945. else if (isa<AlignedAttr>(Attr))
  1946. // AlignedAttrs are handled separately, because we need to handle all
  1947. // such attributes on a declaration at the same time.
  1948. NewAttr = nullptr;
  1949. else if (isa<DeprecatedAttr>(Attr) && Override)
  1950. NewAttr = nullptr;
  1951. else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
  1952. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  1953. if (NewAttr) {
  1954. NewAttr->setInherited(true);
  1955. D->addAttr(NewAttr);
  1956. return true;
  1957. }
  1958. return false;
  1959. }
  1960. static const Decl *getDefinition(const Decl *D) {
  1961. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  1962. return TD->getDefinition();
  1963. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1964. const VarDecl *Def = VD->getDefinition();
  1965. if (Def)
  1966. return Def;
  1967. return VD->getActingDefinition();
  1968. }
  1969. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1970. const FunctionDecl* Def;
  1971. if (FD->isDefined(Def))
  1972. return Def;
  1973. }
  1974. return nullptr;
  1975. }
  1976. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  1977. for (const auto *Attribute : D->attrs())
  1978. if (Attribute->getKind() == Kind)
  1979. return true;
  1980. return false;
  1981. }
  1982. /// checkNewAttributesAfterDef - If we already have a definition, check that
  1983. /// there are no new attributes in this declaration.
  1984. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  1985. if (!New->hasAttrs())
  1986. return;
  1987. const Decl *Def = getDefinition(Old);
  1988. if (!Def || Def == New)
  1989. return;
  1990. AttrVec &NewAttributes = New->getAttrs();
  1991. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  1992. const Attr *NewAttribute = NewAttributes[I];
  1993. if (isa<AliasAttr>(NewAttribute)) {
  1994. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  1995. Sema::SkipBodyInfo SkipBody;
  1996. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  1997. // If we're skipping this definition, drop the "alias" attribute.
  1998. if (SkipBody.ShouldSkip) {
  1999. NewAttributes.erase(NewAttributes.begin() + I);
  2000. --E;
  2001. continue;
  2002. }
  2003. } else {
  2004. VarDecl *VD = cast<VarDecl>(New);
  2005. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2006. VarDecl::TentativeDefinition
  2007. ? diag::err_alias_after_tentative
  2008. : diag::err_redefinition;
  2009. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2010. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2011. VD->setInvalidDecl();
  2012. }
  2013. ++I;
  2014. continue;
  2015. }
  2016. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2017. // Tentative definitions are only interesting for the alias check above.
  2018. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2019. ++I;
  2020. continue;
  2021. }
  2022. }
  2023. if (hasAttribute(Def, NewAttribute->getKind())) {
  2024. ++I;
  2025. continue; // regular attr merging will take care of validating this.
  2026. }
  2027. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2028. // C's _Noreturn is allowed to be added to a function after it is defined.
  2029. ++I;
  2030. continue;
  2031. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2032. if (AA->isAlignas()) {
  2033. // C++11 [dcl.align]p6:
  2034. // if any declaration of an entity has an alignment-specifier,
  2035. // every defining declaration of that entity shall specify an
  2036. // equivalent alignment.
  2037. // C11 6.7.5/7:
  2038. // If the definition of an object does not have an alignment
  2039. // specifier, any other declaration of that object shall also
  2040. // have no alignment specifier.
  2041. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2042. << AA;
  2043. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2044. << AA;
  2045. NewAttributes.erase(NewAttributes.begin() + I);
  2046. --E;
  2047. continue;
  2048. }
  2049. }
  2050. S.Diag(NewAttribute->getLocation(),
  2051. diag::warn_attribute_precede_definition);
  2052. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2053. NewAttributes.erase(NewAttributes.begin() + I);
  2054. --E;
  2055. }
  2056. }
  2057. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2058. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2059. AvailabilityMergeKind AMK) {
  2060. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2061. UsedAttr *NewAttr = OldAttr->clone(Context);
  2062. NewAttr->setInherited(true);
  2063. New->addAttr(NewAttr);
  2064. }
  2065. if (!Old->hasAttrs() && !New->hasAttrs())
  2066. return;
  2067. // attributes declared post-definition are currently ignored
  2068. checkNewAttributesAfterDef(*this, New, Old);
  2069. if (!Old->hasAttrs())
  2070. return;
  2071. bool foundAny = New->hasAttrs();
  2072. // Ensure that any moving of objects within the allocated map is done before
  2073. // we process them.
  2074. if (!foundAny) New->setAttrs(AttrVec());
  2075. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2076. bool Override = false;
  2077. // Ignore deprecated/unavailable/availability attributes if requested.
  2078. if (isa<DeprecatedAttr>(I) ||
  2079. isa<UnavailableAttr>(I) ||
  2080. isa<AvailabilityAttr>(I)) {
  2081. switch (AMK) {
  2082. case AMK_None:
  2083. continue;
  2084. case AMK_Redeclaration:
  2085. break;
  2086. case AMK_Override:
  2087. Override = true;
  2088. break;
  2089. }
  2090. }
  2091. // Already handled.
  2092. if (isa<UsedAttr>(I))
  2093. continue;
  2094. if (mergeDeclAttribute(*this, New, I, Override))
  2095. foundAny = true;
  2096. }
  2097. if (mergeAlignedAttrs(*this, New, Old))
  2098. foundAny = true;
  2099. if (!foundAny) New->dropAttrs();
  2100. }
  2101. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2102. /// to the new one.
  2103. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2104. const ParmVarDecl *oldDecl,
  2105. Sema &S) {
  2106. // C++11 [dcl.attr.depend]p2:
  2107. // The first declaration of a function shall specify the
  2108. // carries_dependency attribute for its declarator-id if any declaration
  2109. // of the function specifies the carries_dependency attribute.
  2110. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2111. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2112. S.Diag(CDA->getLocation(),
  2113. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2114. // Find the first declaration of the parameter.
  2115. // FIXME: Should we build redeclaration chains for function parameters?
  2116. const FunctionDecl *FirstFD =
  2117. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2118. const ParmVarDecl *FirstVD =
  2119. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2120. S.Diag(FirstVD->getLocation(),
  2121. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2122. }
  2123. if (!oldDecl->hasAttrs())
  2124. return;
  2125. bool foundAny = newDecl->hasAttrs();
  2126. // Ensure that any moving of objects within the allocated map is
  2127. // done before we process them.
  2128. if (!foundAny) newDecl->setAttrs(AttrVec());
  2129. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2130. if (!DeclHasAttr(newDecl, I)) {
  2131. InheritableAttr *newAttr =
  2132. cast<InheritableParamAttr>(I->clone(S.Context));
  2133. newAttr->setInherited(true);
  2134. newDecl->addAttr(newAttr);
  2135. foundAny = true;
  2136. }
  2137. }
  2138. if (!foundAny) newDecl->dropAttrs();
  2139. }
  2140. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2141. const ParmVarDecl *OldParam,
  2142. Sema &S) {
  2143. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2144. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2145. if (*Oldnullability != *Newnullability) {
  2146. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2147. << DiagNullabilityKind(
  2148. *Newnullability,
  2149. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2150. != 0))
  2151. << DiagNullabilityKind(
  2152. *Oldnullability,
  2153. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2154. != 0));
  2155. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2156. }
  2157. } else {
  2158. QualType NewT = NewParam->getType();
  2159. NewT = S.Context.getAttributedType(
  2160. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2161. NewT, NewT);
  2162. NewParam->setType(NewT);
  2163. }
  2164. }
  2165. }
  2166. namespace {
  2167. /// Used in MergeFunctionDecl to keep track of function parameters in
  2168. /// C.
  2169. struct GNUCompatibleParamWarning {
  2170. ParmVarDecl *OldParm;
  2171. ParmVarDecl *NewParm;
  2172. QualType PromotedType;
  2173. };
  2174. }
  2175. /// getSpecialMember - get the special member enum for a method.
  2176. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2177. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2178. if (Ctor->isDefaultConstructor())
  2179. return Sema::CXXDefaultConstructor;
  2180. if (Ctor->isCopyConstructor())
  2181. return Sema::CXXCopyConstructor;
  2182. if (Ctor->isMoveConstructor())
  2183. return Sema::CXXMoveConstructor;
  2184. } else if (isa<CXXDestructorDecl>(MD)) {
  2185. return Sema::CXXDestructor;
  2186. } else if (MD->isCopyAssignmentOperator()) {
  2187. return Sema::CXXCopyAssignment;
  2188. } else if (MD->isMoveAssignmentOperator()) {
  2189. return Sema::CXXMoveAssignment;
  2190. }
  2191. return Sema::CXXInvalid;
  2192. }
  2193. // Determine whether the previous declaration was a definition, implicit
  2194. // declaration, or a declaration.
  2195. template <typename T>
  2196. static std::pair<diag::kind, SourceLocation>
  2197. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2198. diag::kind PrevDiag;
  2199. SourceLocation OldLocation = Old->getLocation();
  2200. if (Old->isThisDeclarationADefinition())
  2201. PrevDiag = diag::note_previous_definition;
  2202. else if (Old->isImplicit()) {
  2203. PrevDiag = diag::note_previous_implicit_declaration;
  2204. if (OldLocation.isInvalid())
  2205. OldLocation = New->getLocation();
  2206. } else
  2207. PrevDiag = diag::note_previous_declaration;
  2208. return std::make_pair(PrevDiag, OldLocation);
  2209. }
  2210. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2211. /// only extern inline functions can be redefined, and even then only in
  2212. /// GNU89 mode.
  2213. static bool canRedefineFunction(const FunctionDecl *FD,
  2214. const LangOptions& LangOpts) {
  2215. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2216. !LangOpts.CPlusPlus &&
  2217. FD->isInlineSpecified() &&
  2218. FD->getStorageClass() == SC_Extern);
  2219. }
  2220. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2221. const AttributedType *AT = T->getAs<AttributedType>();
  2222. while (AT && !AT->isCallingConv())
  2223. AT = AT->getModifiedType()->getAs<AttributedType>();
  2224. return AT;
  2225. }
  2226. template <typename T>
  2227. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2228. const DeclContext *DC = Old->getDeclContext();
  2229. if (DC->isRecord())
  2230. return false;
  2231. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2232. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2233. return true;
  2234. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2235. return true;
  2236. return false;
  2237. }
  2238. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2239. static bool isExternC(VarTemplateDecl *) { return false; }
  2240. /// \brief Check whether a redeclaration of an entity introduced by a
  2241. /// using-declaration is valid, given that we know it's not an overload
  2242. /// (nor a hidden tag declaration).
  2243. template<typename ExpectedDecl>
  2244. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2245. ExpectedDecl *New) {
  2246. // C++11 [basic.scope.declarative]p4:
  2247. // Given a set of declarations in a single declarative region, each of
  2248. // which specifies the same unqualified name,
  2249. // -- they shall all refer to the same entity, or all refer to functions
  2250. // and function templates; or
  2251. // -- exactly one declaration shall declare a class name or enumeration
  2252. // name that is not a typedef name and the other declarations shall all
  2253. // refer to the same variable or enumerator, or all refer to functions
  2254. // and function templates; in this case the class name or enumeration
  2255. // name is hidden (3.3.10).
  2256. // C++11 [namespace.udecl]p14:
  2257. // If a function declaration in namespace scope or block scope has the
  2258. // same name and the same parameter-type-list as a function introduced
  2259. // by a using-declaration, and the declarations do not declare the same
  2260. // function, the program is ill-formed.
  2261. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2262. if (Old &&
  2263. !Old->getDeclContext()->getRedeclContext()->Equals(
  2264. New->getDeclContext()->getRedeclContext()) &&
  2265. !(isExternC(Old) && isExternC(New)))
  2266. Old = nullptr;
  2267. if (!Old) {
  2268. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2269. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2270. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2271. return true;
  2272. }
  2273. return false;
  2274. }
  2275. /// MergeFunctionDecl - We just parsed a function 'New' from
  2276. /// declarator D which has the same name and scope as a previous
  2277. /// declaration 'Old'. Figure out how to resolve this situation,
  2278. /// merging decls or emitting diagnostics as appropriate.
  2279. ///
  2280. /// In C++, New and Old must be declarations that are not
  2281. /// overloaded. Use IsOverload to determine whether New and Old are
  2282. /// overloaded, and to select the Old declaration that New should be
  2283. /// merged with.
  2284. ///
  2285. /// Returns true if there was an error, false otherwise.
  2286. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2287. Scope *S, bool MergeTypeWithOld) {
  2288. // Verify the old decl was also a function.
  2289. FunctionDecl *Old = OldD->getAsFunction();
  2290. if (!Old) {
  2291. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2292. if (New->getFriendObjectKind()) {
  2293. Diag(New->getLocation(), diag::err_using_decl_friend);
  2294. Diag(Shadow->getTargetDecl()->getLocation(),
  2295. diag::note_using_decl_target);
  2296. Diag(Shadow->getUsingDecl()->getLocation(),
  2297. diag::note_using_decl) << 0;
  2298. return true;
  2299. }
  2300. // Check whether the two declarations might declare the same function.
  2301. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2302. return true;
  2303. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2304. } else {
  2305. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2306. << New->getDeclName();
  2307. Diag(OldD->getLocation(), diag::note_previous_definition);
  2308. return true;
  2309. }
  2310. }
  2311. // If the old declaration is invalid, just give up here.
  2312. if (Old->isInvalidDecl())
  2313. return true;
  2314. diag::kind PrevDiag;
  2315. SourceLocation OldLocation;
  2316. std::tie(PrevDiag, OldLocation) =
  2317. getNoteDiagForInvalidRedeclaration(Old, New);
  2318. // Don't complain about this if we're in GNU89 mode and the old function
  2319. // is an extern inline function.
  2320. // Don't complain about specializations. They are not supposed to have
  2321. // storage classes.
  2322. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2323. New->getStorageClass() == SC_Static &&
  2324. Old->hasExternalFormalLinkage() &&
  2325. !New->getTemplateSpecializationInfo() &&
  2326. !canRedefineFunction(Old, getLangOpts())) {
  2327. if (getLangOpts().MicrosoftExt) {
  2328. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2329. Diag(OldLocation, PrevDiag);
  2330. } else {
  2331. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2332. Diag(OldLocation, PrevDiag);
  2333. return true;
  2334. }
  2335. }
  2336. // If a function is first declared with a calling convention, but is later
  2337. // declared or defined without one, all following decls assume the calling
  2338. // convention of the first.
  2339. //
  2340. // It's OK if a function is first declared without a calling convention,
  2341. // but is later declared or defined with the default calling convention.
  2342. //
  2343. // To test if either decl has an explicit calling convention, we look for
  2344. // AttributedType sugar nodes on the type as written. If they are missing or
  2345. // were canonicalized away, we assume the calling convention was implicit.
  2346. //
  2347. // Note also that we DO NOT return at this point, because we still have
  2348. // other tests to run.
  2349. QualType OldQType = Context.getCanonicalType(Old->getType());
  2350. QualType NewQType = Context.getCanonicalType(New->getType());
  2351. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2352. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2353. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2354. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2355. bool RequiresAdjustment = false;
  2356. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2357. FunctionDecl *First = Old->getFirstDecl();
  2358. const FunctionType *FT =
  2359. First->getType().getCanonicalType()->castAs<FunctionType>();
  2360. FunctionType::ExtInfo FI = FT->getExtInfo();
  2361. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2362. if (!NewCCExplicit) {
  2363. // Inherit the CC from the previous declaration if it was specified
  2364. // there but not here.
  2365. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2366. RequiresAdjustment = true;
  2367. } else {
  2368. // Calling conventions aren't compatible, so complain.
  2369. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2370. Diag(New->getLocation(), diag::err_cconv_change)
  2371. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2372. << !FirstCCExplicit
  2373. << (!FirstCCExplicit ? "" :
  2374. FunctionType::getNameForCallConv(FI.getCC()));
  2375. // Put the note on the first decl, since it is the one that matters.
  2376. Diag(First->getLocation(), diag::note_previous_declaration);
  2377. return true;
  2378. }
  2379. }
  2380. // FIXME: diagnose the other way around?
  2381. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2382. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2383. RequiresAdjustment = true;
  2384. }
  2385. // Merge regparm attribute.
  2386. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2387. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2388. if (NewTypeInfo.getHasRegParm()) {
  2389. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2390. << NewType->getRegParmType()
  2391. << OldType->getRegParmType();
  2392. Diag(OldLocation, diag::note_previous_declaration);
  2393. return true;
  2394. }
  2395. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2396. RequiresAdjustment = true;
  2397. }
  2398. // Merge ns_returns_retained attribute.
  2399. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2400. if (NewTypeInfo.getProducesResult()) {
  2401. Diag(New->getLocation(), diag::err_returns_retained_mismatch);
  2402. Diag(OldLocation, diag::note_previous_declaration);
  2403. return true;
  2404. }
  2405. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2406. RequiresAdjustment = true;
  2407. }
  2408. if (RequiresAdjustment) {
  2409. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2410. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2411. New->setType(QualType(AdjustedType, 0));
  2412. NewQType = Context.getCanonicalType(New->getType());
  2413. NewType = cast<FunctionType>(NewQType);
  2414. }
  2415. // If this redeclaration makes the function inline, we may need to add it to
  2416. // UndefinedButUsed.
  2417. if (!Old->isInlined() && New->isInlined() &&
  2418. !New->hasAttr<GNUInlineAttr>() &&
  2419. !getLangOpts().GNUInline &&
  2420. Old->isUsed(false) &&
  2421. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2422. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2423. SourceLocation()));
  2424. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2425. // about it.
  2426. if (New->hasAttr<GNUInlineAttr>() &&
  2427. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2428. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2429. }
  2430. if (getLangOpts().CPlusPlus) {
  2431. // (C++98 13.1p2):
  2432. // Certain function declarations cannot be overloaded:
  2433. // -- Function declarations that differ only in the return type
  2434. // cannot be overloaded.
  2435. // Go back to the type source info to compare the declared return types,
  2436. // per C++1y [dcl.type.auto]p13:
  2437. // Redeclarations or specializations of a function or function template
  2438. // with a declared return type that uses a placeholder type shall also
  2439. // use that placeholder, not a deduced type.
  2440. QualType OldDeclaredReturnType =
  2441. (Old->getTypeSourceInfo()
  2442. ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2443. : OldType)->getReturnType();
  2444. QualType NewDeclaredReturnType =
  2445. (New->getTypeSourceInfo()
  2446. ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2447. : NewType)->getReturnType();
  2448. QualType ResQT;
  2449. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  2450. !((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2451. New->isLocalExternDecl())) {
  2452. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  2453. OldDeclaredReturnType->isObjCObjectPointerType())
  2454. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  2455. if (ResQT.isNull()) {
  2456. if (New->isCXXClassMember() && New->isOutOfLine())
  2457. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  2458. << New << New->getReturnTypeSourceRange();
  2459. else
  2460. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  2461. << New->getReturnTypeSourceRange();
  2462. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  2463. << Old->getReturnTypeSourceRange();
  2464. return true;
  2465. }
  2466. else
  2467. NewQType = ResQT;
  2468. }
  2469. QualType OldReturnType = OldType->getReturnType();
  2470. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  2471. if (OldReturnType != NewReturnType) {
  2472. // If this function has a deduced return type and has already been
  2473. // defined, copy the deduced value from the old declaration.
  2474. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  2475. if (OldAT && OldAT->isDeduced()) {
  2476. New->setType(
  2477. SubstAutoType(New->getType(),
  2478. OldAT->isDependentType() ? Context.DependentTy
  2479. : OldAT->getDeducedType()));
  2480. NewQType = Context.getCanonicalType(
  2481. SubstAutoType(NewQType,
  2482. OldAT->isDependentType() ? Context.DependentTy
  2483. : OldAT->getDeducedType()));
  2484. }
  2485. }
  2486. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  2487. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  2488. if (OldMethod && NewMethod) {
  2489. // Preserve triviality.
  2490. NewMethod->setTrivial(OldMethod->isTrivial());
  2491. // MSVC allows explicit template specialization at class scope:
  2492. // 2 CXXMethodDecls referring to the same function will be injected.
  2493. // We don't want a redeclaration error.
  2494. bool IsClassScopeExplicitSpecialization =
  2495. OldMethod->isFunctionTemplateSpecialization() &&
  2496. NewMethod->isFunctionTemplateSpecialization();
  2497. bool isFriend = NewMethod->getFriendObjectKind();
  2498. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  2499. !IsClassScopeExplicitSpecialization) {
  2500. // -- Member function declarations with the same name and the
  2501. // same parameter types cannot be overloaded if any of them
  2502. // is a static member function declaration.
  2503. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  2504. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  2505. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2506. return true;
  2507. }
  2508. // C++ [class.mem]p1:
  2509. // [...] A member shall not be declared twice in the
  2510. // member-specification, except that a nested class or member
  2511. // class template can be declared and then later defined.
  2512. if (ActiveTemplateInstantiations.empty()) {
  2513. unsigned NewDiag;
  2514. if (isa<CXXConstructorDecl>(OldMethod))
  2515. NewDiag = diag::err_constructor_redeclared;
  2516. else if (isa<CXXDestructorDecl>(NewMethod))
  2517. NewDiag = diag::err_destructor_redeclared;
  2518. else if (isa<CXXConversionDecl>(NewMethod))
  2519. NewDiag = diag::err_conv_function_redeclared;
  2520. else
  2521. NewDiag = diag::err_member_redeclared;
  2522. Diag(New->getLocation(), NewDiag);
  2523. } else {
  2524. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2525. << New << New->getType();
  2526. }
  2527. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2528. return true;
  2529. // Complain if this is an explicit declaration of a special
  2530. // member that was initially declared implicitly.
  2531. //
  2532. // As an exception, it's okay to befriend such methods in order
  2533. // to permit the implicit constructor/destructor/operator calls.
  2534. } else if (OldMethod->isImplicit()) {
  2535. if (isFriend) {
  2536. NewMethod->setImplicit();
  2537. } else {
  2538. Diag(NewMethod->getLocation(),
  2539. diag::err_definition_of_implicitly_declared_member)
  2540. << New << getSpecialMember(OldMethod);
  2541. return true;
  2542. }
  2543. } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
  2544. Diag(NewMethod->getLocation(),
  2545. diag::err_definition_of_explicitly_defaulted_member)
  2546. << getSpecialMember(OldMethod);
  2547. return true;
  2548. }
  2549. }
  2550. // C++11 [dcl.attr.noreturn]p1:
  2551. // The first declaration of a function shall specify the noreturn
  2552. // attribute if any declaration of that function specifies the noreturn
  2553. // attribute.
  2554. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  2555. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  2556. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  2557. Diag(Old->getFirstDecl()->getLocation(),
  2558. diag::note_noreturn_missing_first_decl);
  2559. }
  2560. // C++11 [dcl.attr.depend]p2:
  2561. // The first declaration of a function shall specify the
  2562. // carries_dependency attribute for its declarator-id if any declaration
  2563. // of the function specifies the carries_dependency attribute.
  2564. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  2565. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  2566. Diag(CDA->getLocation(),
  2567. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  2568. Diag(Old->getFirstDecl()->getLocation(),
  2569. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  2570. }
  2571. // (C++98 8.3.5p3):
  2572. // All declarations for a function shall agree exactly in both the
  2573. // return type and the parameter-type-list.
  2574. // We also want to respect all the extended bits except noreturn.
  2575. // noreturn should now match unless the old type info didn't have it.
  2576. QualType OldQTypeForComparison = OldQType;
  2577. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  2578. assert(OldQType == QualType(OldType, 0));
  2579. const FunctionType *OldTypeForComparison
  2580. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  2581. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  2582. assert(OldQTypeForComparison.isCanonical());
  2583. }
  2584. if (haveIncompatibleLanguageLinkages(Old, New)) {
  2585. // As a special case, retain the language linkage from previous
  2586. // declarations of a friend function as an extension.
  2587. //
  2588. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  2589. // and is useful because there's otherwise no way to specify language
  2590. // linkage within class scope.
  2591. //
  2592. // Check cautiously as the friend object kind isn't yet complete.
  2593. if (New->getFriendObjectKind() != Decl::FOK_None) {
  2594. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  2595. Diag(OldLocation, PrevDiag);
  2596. } else {
  2597. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  2598. Diag(OldLocation, PrevDiag);
  2599. return true;
  2600. }
  2601. }
  2602. if (OldQTypeForComparison == NewQType)
  2603. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2604. if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2605. New->isLocalExternDecl()) {
  2606. // It's OK if we couldn't merge types for a local function declaraton
  2607. // if either the old or new type is dependent. We'll merge the types
  2608. // when we instantiate the function.
  2609. return false;
  2610. }
  2611. // Fall through for conflicting redeclarations and redefinitions.
  2612. }
  2613. // C: Function types need to be compatible, not identical. This handles
  2614. // duplicate function decls like "void f(int); void f(enum X);" properly.
  2615. if (!getLangOpts().CPlusPlus &&
  2616. Context.typesAreCompatible(OldQType, NewQType)) {
  2617. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  2618. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  2619. const FunctionProtoType *OldProto = nullptr;
  2620. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  2621. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  2622. // The old declaration provided a function prototype, but the
  2623. // new declaration does not. Merge in the prototype.
  2624. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  2625. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  2626. NewQType =
  2627. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  2628. OldProto->getExtProtoInfo());
  2629. New->setType(NewQType);
  2630. New->setHasInheritedPrototype();
  2631. // Synthesize parameters with the same types.
  2632. SmallVector<ParmVarDecl*, 16> Params;
  2633. for (const auto &ParamType : OldProto->param_types()) {
  2634. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  2635. SourceLocation(), nullptr,
  2636. ParamType, /*TInfo=*/nullptr,
  2637. SC_None, nullptr);
  2638. Param->setScopeInfo(0, Params.size());
  2639. Param->setImplicit();
  2640. Params.push_back(Param);
  2641. }
  2642. New->setParams(Params);
  2643. }
  2644. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2645. }
  2646. // GNU C permits a K&R definition to follow a prototype declaration
  2647. // if the declared types of the parameters in the K&R definition
  2648. // match the types in the prototype declaration, even when the
  2649. // promoted types of the parameters from the K&R definition differ
  2650. // from the types in the prototype. GCC then keeps the types from
  2651. // the prototype.
  2652. //
  2653. // If a variadic prototype is followed by a non-variadic K&R definition,
  2654. // the K&R definition becomes variadic. This is sort of an edge case, but
  2655. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  2656. // C99 6.9.1p8.
  2657. if (!getLangOpts().CPlusPlus &&
  2658. Old->hasPrototype() && !New->hasPrototype() &&
  2659. New->getType()->getAs<FunctionProtoType>() &&
  2660. Old->getNumParams() == New->getNumParams()) {
  2661. SmallVector<QualType, 16> ArgTypes;
  2662. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  2663. const FunctionProtoType *OldProto
  2664. = Old->getType()->getAs<FunctionProtoType>();
  2665. const FunctionProtoType *NewProto
  2666. = New->getType()->getAs<FunctionProtoType>();
  2667. // Determine whether this is the GNU C extension.
  2668. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  2669. NewProto->getReturnType());
  2670. bool LooseCompatible = !MergedReturn.isNull();
  2671. for (unsigned Idx = 0, End = Old->getNumParams();
  2672. LooseCompatible && Idx != End; ++Idx) {
  2673. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  2674. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  2675. if (Context.typesAreCompatible(OldParm->getType(),
  2676. NewProto->getParamType(Idx))) {
  2677. ArgTypes.push_back(NewParm->getType());
  2678. } else if (Context.typesAreCompatible(OldParm->getType(),
  2679. NewParm->getType(),
  2680. /*CompareUnqualified=*/true)) {
  2681. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  2682. NewProto->getParamType(Idx) };
  2683. Warnings.push_back(Warn);
  2684. ArgTypes.push_back(NewParm->getType());
  2685. } else
  2686. LooseCompatible = false;
  2687. }
  2688. if (LooseCompatible) {
  2689. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  2690. Diag(Warnings[Warn].NewParm->getLocation(),
  2691. diag::ext_param_promoted_not_compatible_with_prototype)
  2692. << Warnings[Warn].PromotedType
  2693. << Warnings[Warn].OldParm->getType();
  2694. if (Warnings[Warn].OldParm->getLocation().isValid())
  2695. Diag(Warnings[Warn].OldParm->getLocation(),
  2696. diag::note_previous_declaration);
  2697. }
  2698. if (MergeTypeWithOld)
  2699. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  2700. OldProto->getExtProtoInfo()));
  2701. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2702. }
  2703. // Fall through to diagnose conflicting types.
  2704. }
  2705. // A function that has already been declared has been redeclared or
  2706. // defined with a different type; show an appropriate diagnostic.
  2707. // If the previous declaration was an implicitly-generated builtin
  2708. // declaration, then at the very least we should use a specialized note.
  2709. unsigned BuiltinID;
  2710. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  2711. // If it's actually a library-defined builtin function like 'malloc'
  2712. // or 'printf', just warn about the incompatible redeclaration.
  2713. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  2714. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  2715. Diag(OldLocation, diag::note_previous_builtin_declaration)
  2716. << Old << Old->getType();
  2717. // If this is a global redeclaration, just forget hereafter
  2718. // about the "builtin-ness" of the function.
  2719. //
  2720. // Doing this for local extern declarations is problematic. If
  2721. // the builtin declaration remains visible, a second invalid
  2722. // local declaration will produce a hard error; if it doesn't
  2723. // remain visible, a single bogus local redeclaration (which is
  2724. // actually only a warning) could break all the downstream code.
  2725. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  2726. New->getIdentifier()->revertBuiltin();
  2727. return false;
  2728. }
  2729. PrevDiag = diag::note_previous_builtin_declaration;
  2730. }
  2731. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  2732. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2733. return true;
  2734. }
  2735. /// \brief Completes the merge of two function declarations that are
  2736. /// known to be compatible.
  2737. ///
  2738. /// This routine handles the merging of attributes and other
  2739. /// properties of function declarations from the old declaration to
  2740. /// the new declaration, once we know that New is in fact a
  2741. /// redeclaration of Old.
  2742. ///
  2743. /// \returns false
  2744. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  2745. Scope *S, bool MergeTypeWithOld) {
  2746. // Merge the attributes
  2747. mergeDeclAttributes(New, Old);
  2748. // Merge "pure" flag.
  2749. if (Old->isPure())
  2750. New->setPure();
  2751. // Merge "used" flag.
  2752. if (Old->getMostRecentDecl()->isUsed(false))
  2753. New->setIsUsed();
  2754. // Merge attributes from the parameters. These can mismatch with K&R
  2755. // declarations.
  2756. if (New->getNumParams() == Old->getNumParams())
  2757. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  2758. ParmVarDecl *NewParam = New->getParamDecl(i);
  2759. ParmVarDecl *OldParam = Old->getParamDecl(i);
  2760. mergeParamDeclAttributes(NewParam, OldParam, *this);
  2761. mergeParamDeclTypes(NewParam, OldParam, *this);
  2762. }
  2763. if (getLangOpts().CPlusPlus)
  2764. return MergeCXXFunctionDecl(New, Old, S);
  2765. // Merge the function types so the we get the composite types for the return
  2766. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  2767. // was visible.
  2768. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  2769. if (!Merged.isNull() && MergeTypeWithOld)
  2770. New->setType(Merged);
  2771. return false;
  2772. }
  2773. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  2774. ObjCMethodDecl *oldMethod) {
  2775. // Merge the attributes, including deprecated/unavailable
  2776. AvailabilityMergeKind MergeKind =
  2777. isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  2778. : AMK_Override;
  2779. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  2780. // Merge attributes from the parameters.
  2781. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  2782. oe = oldMethod->param_end();
  2783. for (ObjCMethodDecl::param_iterator
  2784. ni = newMethod->param_begin(), ne = newMethod->param_end();
  2785. ni != ne && oi != oe; ++ni, ++oi)
  2786. mergeParamDeclAttributes(*ni, *oi, *this);
  2787. CheckObjCMethodOverride(newMethod, oldMethod);
  2788. }
  2789. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  2790. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  2791. /// emitting diagnostics as appropriate.
  2792. ///
  2793. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  2794. /// to here in AddInitializerToDecl. We can't check them before the initializer
  2795. /// is attached.
  2796. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  2797. bool MergeTypeWithOld) {
  2798. if (New->isInvalidDecl() || Old->isInvalidDecl())
  2799. return;
  2800. QualType MergedT;
  2801. if (getLangOpts().CPlusPlus) {
  2802. if (New->getType()->isUndeducedType()) {
  2803. // We don't know what the new type is until the initializer is attached.
  2804. return;
  2805. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  2806. // These could still be something that needs exception specs checked.
  2807. return MergeVarDeclExceptionSpecs(New, Old);
  2808. }
  2809. // C++ [basic.link]p10:
  2810. // [...] the types specified by all declarations referring to a given
  2811. // object or function shall be identical, except that declarations for an
  2812. // array object can specify array types that differ by the presence or
  2813. // absence of a major array bound (8.3.4).
  2814. else if (Old->getType()->isIncompleteArrayType() &&
  2815. New->getType()->isArrayType()) {
  2816. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  2817. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  2818. if (Context.hasSameType(OldArray->getElementType(),
  2819. NewArray->getElementType()))
  2820. MergedT = New->getType();
  2821. } else if (Old->getType()->isArrayType() &&
  2822. New->getType()->isIncompleteArrayType()) {
  2823. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  2824. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  2825. if (Context.hasSameType(OldArray->getElementType(),
  2826. NewArray->getElementType()))
  2827. MergedT = Old->getType();
  2828. } else if (New->getType()->isObjCObjectPointerType() &&
  2829. Old->getType()->isObjCObjectPointerType()) {
  2830. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  2831. Old->getType());
  2832. }
  2833. } else {
  2834. // C 6.2.7p2:
  2835. // All declarations that refer to the same object or function shall have
  2836. // compatible type.
  2837. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  2838. }
  2839. if (MergedT.isNull()) {
  2840. // It's OK if we couldn't merge types if either type is dependent, for a
  2841. // block-scope variable. In other cases (static data members of class
  2842. // templates, variable templates, ...), we require the types to be
  2843. // equivalent.
  2844. // FIXME: The C++ standard doesn't say anything about this.
  2845. if ((New->getType()->isDependentType() ||
  2846. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  2847. // If the old type was dependent, we can't merge with it, so the new type
  2848. // becomes dependent for now. We'll reproduce the original type when we
  2849. // instantiate the TypeSourceInfo for the variable.
  2850. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  2851. New->setType(Context.DependentTy);
  2852. return;
  2853. }
  2854. // FIXME: Even if this merging succeeds, some other non-visible declaration
  2855. // of this variable might have an incompatible type. For instance:
  2856. //
  2857. // extern int arr[];
  2858. // void f() { extern int arr[2]; }
  2859. // void g() { extern int arr[3]; }
  2860. //
  2861. // Neither C nor C++ requires a diagnostic for this, but we should still try
  2862. // to diagnose it.
  2863. Diag(New->getLocation(), New->isThisDeclarationADefinition()
  2864. ? diag::err_redefinition_different_type
  2865. : diag::err_redeclaration_different_type)
  2866. << New->getDeclName() << New->getType() << Old->getType();
  2867. diag::kind PrevDiag;
  2868. SourceLocation OldLocation;
  2869. std::tie(PrevDiag, OldLocation) =
  2870. getNoteDiagForInvalidRedeclaration(Old, New);
  2871. Diag(OldLocation, PrevDiag);
  2872. return New->setInvalidDecl();
  2873. }
  2874. // Don't actually update the type on the new declaration if the old
  2875. // declaration was an extern declaration in a different scope.
  2876. if (MergeTypeWithOld)
  2877. New->setType(MergedT);
  2878. }
  2879. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  2880. LookupResult &Previous) {
  2881. // C11 6.2.7p4:
  2882. // For an identifier with internal or external linkage declared
  2883. // in a scope in which a prior declaration of that identifier is
  2884. // visible, if the prior declaration specifies internal or
  2885. // external linkage, the type of the identifier at the later
  2886. // declaration becomes the composite type.
  2887. //
  2888. // If the variable isn't visible, we do not merge with its type.
  2889. if (Previous.isShadowed())
  2890. return false;
  2891. if (S.getLangOpts().CPlusPlus) {
  2892. // C++11 [dcl.array]p3:
  2893. // If there is a preceding declaration of the entity in the same
  2894. // scope in which the bound was specified, an omitted array bound
  2895. // is taken to be the same as in that earlier declaration.
  2896. return NewVD->isPreviousDeclInSameBlockScope() ||
  2897. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  2898. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  2899. } else {
  2900. // If the old declaration was function-local, don't merge with its
  2901. // type unless we're in the same function.
  2902. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  2903. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  2904. }
  2905. }
  2906. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  2907. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  2908. /// situation, merging decls or emitting diagnostics as appropriate.
  2909. ///
  2910. /// Tentative definition rules (C99 6.9.2p2) are checked by
  2911. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  2912. /// definitions here, since the initializer hasn't been attached.
  2913. ///
  2914. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  2915. // If the new decl is already invalid, don't do any other checking.
  2916. if (New->isInvalidDecl())
  2917. return;
  2918. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  2919. // Verify the old decl was also a variable or variable template.
  2920. VarDecl *Old = nullptr;
  2921. VarTemplateDecl *OldTemplate = nullptr;
  2922. if (Previous.isSingleResult()) {
  2923. if (NewTemplate) {
  2924. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  2925. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  2926. if (auto *Shadow =
  2927. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  2928. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  2929. return New->setInvalidDecl();
  2930. } else {
  2931. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  2932. if (auto *Shadow =
  2933. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  2934. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  2935. return New->setInvalidDecl();
  2936. }
  2937. }
  2938. if (!Old) {
  2939. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2940. << New->getDeclName();
  2941. Diag(Previous.getRepresentativeDecl()->getLocation(),
  2942. diag::note_previous_definition);
  2943. return New->setInvalidDecl();
  2944. }
  2945. if (!shouldLinkPossiblyHiddenDecl(Old, New))
  2946. return;
  2947. // Ensure the template parameters are compatible.
  2948. if (NewTemplate &&
  2949. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  2950. OldTemplate->getTemplateParameters(),
  2951. /*Complain=*/true, TPL_TemplateMatch))
  2952. return;
  2953. // C++ [class.mem]p1:
  2954. // A member shall not be declared twice in the member-specification [...]
  2955. //
  2956. // Here, we need only consider static data members.
  2957. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  2958. Diag(New->getLocation(), diag::err_duplicate_member)
  2959. << New->getIdentifier();
  2960. Diag(Old->getLocation(), diag::note_previous_declaration);
  2961. New->setInvalidDecl();
  2962. }
  2963. mergeDeclAttributes(New, Old);
  2964. // Warn if an already-declared variable is made a weak_import in a subsequent
  2965. // declaration
  2966. if (New->hasAttr<WeakImportAttr>() &&
  2967. Old->getStorageClass() == SC_None &&
  2968. !Old->hasAttr<WeakImportAttr>()) {
  2969. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  2970. Diag(Old->getLocation(), diag::note_previous_definition);
  2971. // Remove weak_import attribute on new declaration.
  2972. New->dropAttr<WeakImportAttr>();
  2973. }
  2974. // Merge the types.
  2975. VarDecl *MostRecent = Old->getMostRecentDecl();
  2976. if (MostRecent != Old) {
  2977. MergeVarDeclTypes(New, MostRecent,
  2978. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  2979. if (New->isInvalidDecl())
  2980. return;
  2981. }
  2982. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  2983. if (New->isInvalidDecl())
  2984. return;
  2985. diag::kind PrevDiag;
  2986. SourceLocation OldLocation;
  2987. std::tie(PrevDiag, OldLocation) =
  2988. getNoteDiagForInvalidRedeclaration(Old, New);
  2989. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  2990. if (New->getStorageClass() == SC_Static &&
  2991. !New->isStaticDataMember() &&
  2992. Old->hasExternalFormalLinkage()) {
  2993. if (getLangOpts().MicrosoftExt) {
  2994. Diag(New->getLocation(), diag::ext_static_non_static)
  2995. << New->getDeclName();
  2996. Diag(OldLocation, PrevDiag);
  2997. } else {
  2998. Diag(New->getLocation(), diag::err_static_non_static)
  2999. << New->getDeclName();
  3000. Diag(OldLocation, PrevDiag);
  3001. return New->setInvalidDecl();
  3002. }
  3003. }
  3004. // C99 6.2.2p4:
  3005. // For an identifier declared with the storage-class specifier
  3006. // extern in a scope in which a prior declaration of that
  3007. // identifier is visible,23) if the prior declaration specifies
  3008. // internal or external linkage, the linkage of the identifier at
  3009. // the later declaration is the same as the linkage specified at
  3010. // the prior declaration. If no prior declaration is visible, or
  3011. // if the prior declaration specifies no linkage, then the
  3012. // identifier has external linkage.
  3013. if (New->hasExternalStorage() && Old->hasLinkage())
  3014. /* Okay */;
  3015. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3016. !New->isStaticDataMember() &&
  3017. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3018. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3019. Diag(OldLocation, PrevDiag);
  3020. return New->setInvalidDecl();
  3021. }
  3022. // Check if extern is followed by non-extern and vice-versa.
  3023. if (New->hasExternalStorage() &&
  3024. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3025. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3026. Diag(OldLocation, PrevDiag);
  3027. return New->setInvalidDecl();
  3028. }
  3029. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3030. !New->hasExternalStorage()) {
  3031. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3032. Diag(OldLocation, PrevDiag);
  3033. return New->setInvalidDecl();
  3034. }
  3035. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3036. // FIXME: The test for external storage here seems wrong? We still
  3037. // need to check for mismatches.
  3038. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3039. // Don't complain about out-of-line definitions of static members.
  3040. !(Old->getLexicalDeclContext()->isRecord() &&
  3041. !New->getLexicalDeclContext()->isRecord())) {
  3042. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3043. Diag(OldLocation, PrevDiag);
  3044. return New->setInvalidDecl();
  3045. }
  3046. if (New->getTLSKind() != Old->getTLSKind()) {
  3047. if (!Old->getTLSKind()) {
  3048. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3049. Diag(OldLocation, PrevDiag);
  3050. } else if (!New->getTLSKind()) {
  3051. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3052. Diag(OldLocation, PrevDiag);
  3053. } else {
  3054. // Do not allow redeclaration to change the variable between requiring
  3055. // static and dynamic initialization.
  3056. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3057. // declaration to determine the kind. Do we need to be compatible here?
  3058. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3059. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3060. Diag(OldLocation, PrevDiag);
  3061. }
  3062. }
  3063. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3064. VarDecl *Def;
  3065. if (getLangOpts().CPlusPlus &&
  3066. New->isThisDeclarationADefinition() == VarDecl::Definition &&
  3067. (Def = Old->getDefinition())) {
  3068. NamedDecl *Hidden = nullptr;
  3069. if (!hasVisibleDefinition(Def, &Hidden) &&
  3070. (New->getFormalLinkage() == InternalLinkage ||
  3071. New->getDescribedVarTemplate() ||
  3072. New->getNumTemplateParameterLists() ||
  3073. New->getDeclContext()->isDependentContext())) {
  3074. // The previous definition is hidden, and multiple definitions are
  3075. // permitted (in separate TUs). Form another definition of it.
  3076. } else {
  3077. Diag(New->getLocation(), diag::err_redefinition) << New;
  3078. Diag(Def->getLocation(), diag::note_previous_definition);
  3079. New->setInvalidDecl();
  3080. return;
  3081. }
  3082. }
  3083. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3084. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3085. Diag(OldLocation, PrevDiag);
  3086. New->setInvalidDecl();
  3087. return;
  3088. }
  3089. // Merge "used" flag.
  3090. if (Old->getMostRecentDecl()->isUsed(false))
  3091. New->setIsUsed();
  3092. // Keep a chain of previous declarations.
  3093. New->setPreviousDecl(Old);
  3094. if (NewTemplate)
  3095. NewTemplate->setPreviousDecl(OldTemplate);
  3096. // Inherit access appropriately.
  3097. New->setAccess(Old->getAccess());
  3098. if (NewTemplate)
  3099. NewTemplate->setAccess(New->getAccess());
  3100. }
  3101. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3102. /// no declarator (e.g. "struct foo;") is parsed.
  3103. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  3104. DeclSpec &DS) {
  3105. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
  3106. }
  3107. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3108. // disambiguate entities defined in different scopes.
  3109. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3110. // compatibility.
  3111. // We will pick our mangling number depending on which version of MSVC is being
  3112. // targeted.
  3113. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3114. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3115. ? S->getMSCurManglingNumber()
  3116. : S->getMSLastManglingNumber();
  3117. }
  3118. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3119. if (!Context.getLangOpts().CPlusPlus)
  3120. return;
  3121. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3122. // If this tag is the direct child of a class, number it if
  3123. // it is anonymous.
  3124. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3125. return;
  3126. MangleNumberingContext &MCtx =
  3127. Context.getManglingNumberContext(Tag->getParent());
  3128. Context.setManglingNumber(
  3129. Tag, MCtx.getManglingNumber(
  3130. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3131. return;
  3132. }
  3133. // If this tag isn't a direct child of a class, number it if it is local.
  3134. Decl *ManglingContextDecl;
  3135. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3136. Tag->getDeclContext(), ManglingContextDecl)) {
  3137. Context.setManglingNumber(
  3138. Tag, MCtx->getManglingNumber(
  3139. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3140. }
  3141. }
  3142. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3143. TypedefNameDecl *NewTD) {
  3144. if (TagFromDeclSpec->isInvalidDecl())
  3145. return;
  3146. // Do nothing if the tag already has a name for linkage purposes.
  3147. if (TagFromDeclSpec->hasNameForLinkage())
  3148. return;
  3149. // A well-formed anonymous tag must always be a TUK_Definition.
  3150. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3151. // The type must match the tag exactly; no qualifiers allowed.
  3152. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3153. Context.getTagDeclType(TagFromDeclSpec))) {
  3154. if (getLangOpts().CPlusPlus)
  3155. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3156. return;
  3157. }
  3158. // If we've already computed linkage for the anonymous tag, then
  3159. // adding a typedef name for the anonymous decl can change that
  3160. // linkage, which might be a serious problem. Diagnose this as
  3161. // unsupported and ignore the typedef name. TODO: we should
  3162. // pursue this as a language defect and establish a formal rule
  3163. // for how to handle it.
  3164. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3165. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3166. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3167. tagLoc = getLocForEndOfToken(tagLoc);
  3168. llvm::SmallString<40> textToInsert;
  3169. textToInsert += ' ';
  3170. textToInsert += NewTD->getIdentifier()->getName();
  3171. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3172. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3173. return;
  3174. }
  3175. // Otherwise, set this is the anon-decl typedef for the tag.
  3176. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3177. }
  3178. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3179. switch (T) {
  3180. case DeclSpec::TST_class:
  3181. return 0;
  3182. case DeclSpec::TST_struct:
  3183. return 1;
  3184. case DeclSpec::TST_interface:
  3185. return 2;
  3186. case DeclSpec::TST_union:
  3187. return 3;
  3188. case DeclSpec::TST_enum:
  3189. return 4;
  3190. default:
  3191. llvm_unreachable("unexpected type specifier");
  3192. }
  3193. }
  3194. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3195. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3196. /// parameters to cope with template friend declarations.
  3197. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  3198. DeclSpec &DS,
  3199. MultiTemplateParamsArg TemplateParams,
  3200. bool IsExplicitInstantiation) {
  3201. Decl *TagD = nullptr;
  3202. TagDecl *Tag = nullptr;
  3203. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3204. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3205. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3206. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3207. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3208. TagD = DS.getRepAsDecl();
  3209. if (!TagD) // We probably had an error
  3210. return nullptr;
  3211. // Note that the above type specs guarantee that the
  3212. // type rep is a Decl, whereas in many of the others
  3213. // it's a Type.
  3214. if (isa<TagDecl>(TagD))
  3215. Tag = cast<TagDecl>(TagD);
  3216. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3217. Tag = CTD->getTemplatedDecl();
  3218. }
  3219. if (Tag) {
  3220. handleTagNumbering(Tag, S);
  3221. Tag->setFreeStanding();
  3222. if (Tag->isInvalidDecl())
  3223. return Tag;
  3224. }
  3225. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3226. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3227. // or incomplete types shall not be restrict-qualified."
  3228. if (TypeQuals & DeclSpec::TQ_restrict)
  3229. Diag(DS.getRestrictSpecLoc(),
  3230. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3231. << DS.getSourceRange();
  3232. }
  3233. if (DS.isConstexprSpecified()) {
  3234. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3235. // and definitions of functions and variables.
  3236. if (Tag)
  3237. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3238. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
  3239. else
  3240. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  3241. // Don't emit warnings after this error.
  3242. return TagD;
  3243. }
  3244. if (DS.isConceptSpecified()) {
  3245. // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
  3246. // either a function concept and its definition or a variable concept and
  3247. // its initializer.
  3248. Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
  3249. return TagD;
  3250. }
  3251. DiagnoseFunctionSpecifiers(DS);
  3252. if (DS.isFriendSpecified()) {
  3253. // If we're dealing with a decl but not a TagDecl, assume that
  3254. // whatever routines created it handled the friendship aspect.
  3255. if (TagD && !Tag)
  3256. return nullptr;
  3257. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3258. }
  3259. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3260. bool IsExplicitSpecialization =
  3261. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3262. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3263. !IsExplicitInstantiation && !IsExplicitSpecialization) {
  3264. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3265. // nested-name-specifier unless it is an explicit instantiation
  3266. // or an explicit specialization.
  3267. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3268. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3269. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3270. return nullptr;
  3271. }
  3272. // Track whether this decl-specifier declares anything.
  3273. bool DeclaresAnything = true;
  3274. // Handle anonymous struct definitions.
  3275. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3276. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3277. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3278. if (getLangOpts().CPlusPlus ||
  3279. Record->getDeclContext()->isRecord())
  3280. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3281. Context.getPrintingPolicy());
  3282. DeclaresAnything = false;
  3283. }
  3284. }
  3285. // C11 6.7.2.1p2:
  3286. // A struct-declaration that does not declare an anonymous structure or
  3287. // anonymous union shall contain a struct-declarator-list.
  3288. //
  3289. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3290. // did not permit a struct-declaration without a struct-declarator-list.
  3291. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3292. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3293. // Check for Microsoft C extension: anonymous struct/union member.
  3294. // Handle 2 kinds of anonymous struct/union:
  3295. // struct STRUCT;
  3296. // union UNION;
  3297. // and
  3298. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3299. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3300. if ((Tag && Tag->getDeclName()) ||
  3301. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3302. RecordDecl *Record = nullptr;
  3303. if (Tag)
  3304. Record = dyn_cast<RecordDecl>(Tag);
  3305. else if (const RecordType *RT =
  3306. DS.getRepAsType().get()->getAsStructureType())
  3307. Record = RT->getDecl();
  3308. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3309. Record = UT->getDecl();
  3310. if (Record && getLangOpts().MicrosoftExt) {
  3311. Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
  3312. << Record->isUnion() << DS.getSourceRange();
  3313. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3314. }
  3315. DeclaresAnything = false;
  3316. }
  3317. }
  3318. // Skip all the checks below if we have a type error.
  3319. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3320. (TagD && TagD->isInvalidDecl()))
  3321. return TagD;
  3322. if (getLangOpts().CPlusPlus &&
  3323. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3324. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  3325. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  3326. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  3327. DeclaresAnything = false;
  3328. if (!DS.isMissingDeclaratorOk()) {
  3329. // Customize diagnostic for a typedef missing a name.
  3330. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  3331. Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
  3332. << DS.getSourceRange();
  3333. else
  3334. DeclaresAnything = false;
  3335. }
  3336. if (DS.isModulePrivateSpecified() &&
  3337. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  3338. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  3339. << Tag->getTagKind()
  3340. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  3341. ActOnDocumentableDecl(TagD);
  3342. // C 6.7/2:
  3343. // A declaration [...] shall declare at least a declarator [...], a tag,
  3344. // or the members of an enumeration.
  3345. // C++ [dcl.dcl]p3:
  3346. // [If there are no declarators], and except for the declaration of an
  3347. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  3348. // names into the program, or shall redeclare a name introduced by a
  3349. // previous declaration.
  3350. if (!DeclaresAnything) {
  3351. // In C, we allow this as a (popular) extension / bug. Don't bother
  3352. // producing further diagnostics for redundant qualifiers after this.
  3353. Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
  3354. return TagD;
  3355. }
  3356. // C++ [dcl.stc]p1:
  3357. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  3358. // init-declarator-list of the declaration shall not be empty.
  3359. // C++ [dcl.fct.spec]p1:
  3360. // If a cv-qualifier appears in a decl-specifier-seq, the
  3361. // init-declarator-list of the declaration shall not be empty.
  3362. //
  3363. // Spurious qualifiers here appear to be valid in C.
  3364. unsigned DiagID = diag::warn_standalone_specifier;
  3365. if (getLangOpts().CPlusPlus)
  3366. DiagID = diag::ext_standalone_specifier;
  3367. // Note that a linkage-specification sets a storage class, but
  3368. // 'extern "C" struct foo;' is actually valid and not theoretically
  3369. // useless.
  3370. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3371. if (SCS == DeclSpec::SCS_mutable)
  3372. // Since mutable is not a viable storage class specifier in C, there is
  3373. // no reason to treat it as an extension. Instead, diagnose as an error.
  3374. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  3375. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  3376. Diag(DS.getStorageClassSpecLoc(), DiagID)
  3377. << DeclSpec::getSpecifierName(SCS);
  3378. }
  3379. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  3380. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  3381. << DeclSpec::getSpecifierName(TSCS);
  3382. if (DS.getTypeQualifiers()) {
  3383. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3384. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  3385. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3386. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  3387. // Restrict is covered above.
  3388. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3389. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  3390. }
  3391. // Warn about ignored type attributes, for example:
  3392. // __attribute__((aligned)) struct A;
  3393. // Attributes should be placed after tag to apply to type declaration.
  3394. if (!DS.getAttributes().empty()) {
  3395. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  3396. if (TypeSpecType == DeclSpec::TST_class ||
  3397. TypeSpecType == DeclSpec::TST_struct ||
  3398. TypeSpecType == DeclSpec::TST_interface ||
  3399. TypeSpecType == DeclSpec::TST_union ||
  3400. TypeSpecType == DeclSpec::TST_enum) {
  3401. for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
  3402. attrs = attrs->getNext())
  3403. Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
  3404. << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  3405. }
  3406. }
  3407. return TagD;
  3408. }
  3409. /// We are trying to inject an anonymous member into the given scope;
  3410. /// check if there's an existing declaration that can't be overloaded.
  3411. ///
  3412. /// \return true if this is a forbidden redeclaration
  3413. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  3414. Scope *S,
  3415. DeclContext *Owner,
  3416. DeclarationName Name,
  3417. SourceLocation NameLoc,
  3418. unsigned diagnostic) {
  3419. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  3420. Sema::ForRedeclaration);
  3421. if (!SemaRef.LookupName(R, S)) return false;
  3422. if (R.getAsSingle<TagDecl>())
  3423. return false;
  3424. // Pick a representative declaration.
  3425. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  3426. assert(PrevDecl && "Expected a non-null Decl");
  3427. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  3428. return false;
  3429. SemaRef.Diag(NameLoc, diagnostic) << Name;
  3430. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  3431. return true;
  3432. }
  3433. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  3434. /// anonymous struct or union AnonRecord into the owning context Owner
  3435. /// and scope S. This routine will be invoked just after we realize
  3436. /// that an unnamed union or struct is actually an anonymous union or
  3437. /// struct, e.g.,
  3438. ///
  3439. /// @code
  3440. /// union {
  3441. /// int i;
  3442. /// float f;
  3443. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  3444. /// // f into the surrounding scope.x
  3445. /// @endcode
  3446. ///
  3447. /// This routine is recursive, injecting the names of nested anonymous
  3448. /// structs/unions into the owning context and scope as well.
  3449. static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
  3450. DeclContext *Owner,
  3451. RecordDecl *AnonRecord,
  3452. AccessSpecifier AS,
  3453. SmallVectorImpl<NamedDecl *> &Chaining,
  3454. bool MSAnonStruct) {
  3455. unsigned diagKind
  3456. = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
  3457. : diag::err_anonymous_struct_member_redecl;
  3458. bool Invalid = false;
  3459. // Look every FieldDecl and IndirectFieldDecl with a name.
  3460. for (auto *D : AnonRecord->decls()) {
  3461. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  3462. cast<NamedDecl>(D)->getDeclName()) {
  3463. ValueDecl *VD = cast<ValueDecl>(D);
  3464. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  3465. VD->getLocation(), diagKind)) {
  3466. // C++ [class.union]p2:
  3467. // The names of the members of an anonymous union shall be
  3468. // distinct from the names of any other entity in the
  3469. // scope in which the anonymous union is declared.
  3470. Invalid = true;
  3471. } else {
  3472. // C++ [class.union]p2:
  3473. // For the purpose of name lookup, after the anonymous union
  3474. // definition, the members of the anonymous union are
  3475. // considered to have been defined in the scope in which the
  3476. // anonymous union is declared.
  3477. unsigned OldChainingSize = Chaining.size();
  3478. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  3479. Chaining.append(IF->chain_begin(), IF->chain_end());
  3480. else
  3481. Chaining.push_back(VD);
  3482. assert(Chaining.size() >= 2);
  3483. NamedDecl **NamedChain =
  3484. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  3485. for (unsigned i = 0; i < Chaining.size(); i++)
  3486. NamedChain[i] = Chaining[i];
  3487. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  3488. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  3489. VD->getType(), NamedChain, Chaining.size());
  3490. for (const auto *Attr : VD->attrs())
  3491. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  3492. IndirectField->setAccess(AS);
  3493. IndirectField->setImplicit();
  3494. SemaRef.PushOnScopeChains(IndirectField, S);
  3495. // That includes picking up the appropriate access specifier.
  3496. if (AS != AS_none) IndirectField->setAccess(AS);
  3497. Chaining.resize(OldChainingSize);
  3498. }
  3499. }
  3500. }
  3501. return Invalid;
  3502. }
  3503. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  3504. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  3505. /// illegal input values are mapped to SC_None.
  3506. static StorageClass
  3507. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  3508. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  3509. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  3510. "Parser allowed 'typedef' as storage class VarDecl.");
  3511. switch (StorageClassSpec) {
  3512. case DeclSpec::SCS_unspecified: return SC_None;
  3513. case DeclSpec::SCS_extern:
  3514. if (DS.isExternInLinkageSpec())
  3515. return SC_None;
  3516. return SC_Extern;
  3517. case DeclSpec::SCS_static: return SC_Static;
  3518. case DeclSpec::SCS_auto: return SC_Auto;
  3519. case DeclSpec::SCS_register: return SC_Register;
  3520. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  3521. // Illegal SCSs map to None: error reporting is up to the caller.
  3522. case DeclSpec::SCS_mutable: // Fall through.
  3523. case DeclSpec::SCS_typedef: return SC_None;
  3524. }
  3525. llvm_unreachable("unknown storage class specifier");
  3526. }
  3527. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  3528. assert(Record->hasInClassInitializer());
  3529. for (const auto *I : Record->decls()) {
  3530. const auto *FD = dyn_cast<FieldDecl>(I);
  3531. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  3532. FD = IFD->getAnonField();
  3533. if (FD && FD->hasInClassInitializer())
  3534. return FD->getLocation();
  3535. }
  3536. llvm_unreachable("couldn't find in-class initializer");
  3537. }
  3538. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3539. SourceLocation DefaultInitLoc) {
  3540. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3541. return;
  3542. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  3543. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  3544. }
  3545. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3546. CXXRecordDecl *AnonUnion) {
  3547. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3548. return;
  3549. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  3550. }
  3551. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  3552. /// anonymous structure or union. Anonymous unions are a C++ feature
  3553. /// (C++ [class.union]) and a C11 feature; anonymous structures
  3554. /// are a C11 feature and GNU C++ extension.
  3555. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  3556. AccessSpecifier AS,
  3557. RecordDecl *Record,
  3558. const PrintingPolicy &Policy) {
  3559. DeclContext *Owner = Record->getDeclContext();
  3560. // Diagnose whether this anonymous struct/union is an extension.
  3561. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  3562. Diag(Record->getLocation(), diag::ext_anonymous_union);
  3563. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  3564. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  3565. else if (!Record->isUnion() && !getLangOpts().C11)
  3566. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  3567. // C and C++ require different kinds of checks for anonymous
  3568. // structs/unions.
  3569. bool Invalid = false;
  3570. if (getLangOpts().CPlusPlus) {
  3571. const char *PrevSpec = nullptr;
  3572. unsigned DiagID;
  3573. if (Record->isUnion()) {
  3574. // C++ [class.union]p6:
  3575. // Anonymous unions declared in a named namespace or in the
  3576. // global namespace shall be declared static.
  3577. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  3578. (isa<TranslationUnitDecl>(Owner) ||
  3579. (isa<NamespaceDecl>(Owner) &&
  3580. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  3581. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  3582. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  3583. // Recover by adding 'static'.
  3584. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  3585. PrevSpec, DiagID, Policy);
  3586. }
  3587. // C++ [class.union]p6:
  3588. // A storage class is not allowed in a declaration of an
  3589. // anonymous union in a class scope.
  3590. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  3591. isa<RecordDecl>(Owner)) {
  3592. Diag(DS.getStorageClassSpecLoc(),
  3593. diag::err_anonymous_union_with_storage_spec)
  3594. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  3595. // Recover by removing the storage specifier.
  3596. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  3597. SourceLocation(),
  3598. PrevSpec, DiagID, Context.getPrintingPolicy());
  3599. }
  3600. }
  3601. // Ignore const/volatile/restrict qualifiers.
  3602. if (DS.getTypeQualifiers()) {
  3603. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3604. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  3605. << Record->isUnion() << "const"
  3606. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  3607. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3608. Diag(DS.getVolatileSpecLoc(),
  3609. diag::ext_anonymous_struct_union_qualified)
  3610. << Record->isUnion() << "volatile"
  3611. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  3612. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  3613. Diag(DS.getRestrictSpecLoc(),
  3614. diag::ext_anonymous_struct_union_qualified)
  3615. << Record->isUnion() << "restrict"
  3616. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  3617. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3618. Diag(DS.getAtomicSpecLoc(),
  3619. diag::ext_anonymous_struct_union_qualified)
  3620. << Record->isUnion() << "_Atomic"
  3621. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  3622. DS.ClearTypeQualifiers();
  3623. }
  3624. // C++ [class.union]p2:
  3625. // The member-specification of an anonymous union shall only
  3626. // define non-static data members. [Note: nested types and
  3627. // functions cannot be declared within an anonymous union. ]
  3628. for (auto *Mem : Record->decls()) {
  3629. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  3630. // C++ [class.union]p3:
  3631. // An anonymous union shall not have private or protected
  3632. // members (clause 11).
  3633. assert(FD->getAccess() != AS_none);
  3634. if (FD->getAccess() != AS_public) {
  3635. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  3636. << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
  3637. Invalid = true;
  3638. }
  3639. // C++ [class.union]p1
  3640. // An object of a class with a non-trivial constructor, a non-trivial
  3641. // copy constructor, a non-trivial destructor, or a non-trivial copy
  3642. // assignment operator cannot be a member of a union, nor can an
  3643. // array of such objects.
  3644. if (CheckNontrivialField(FD))
  3645. Invalid = true;
  3646. } else if (Mem->isImplicit()) {
  3647. // Any implicit members are fine.
  3648. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  3649. // This is a type that showed up in an
  3650. // elaborated-type-specifier inside the anonymous struct or
  3651. // union, but which actually declares a type outside of the
  3652. // anonymous struct or union. It's okay.
  3653. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  3654. if (!MemRecord->isAnonymousStructOrUnion() &&
  3655. MemRecord->getDeclName()) {
  3656. // Visual C++ allows type definition in anonymous struct or union.
  3657. if (getLangOpts().MicrosoftExt)
  3658. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  3659. << (int)Record->isUnion();
  3660. else {
  3661. // This is a nested type declaration.
  3662. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  3663. << (int)Record->isUnion();
  3664. Invalid = true;
  3665. }
  3666. } else {
  3667. // This is an anonymous type definition within another anonymous type.
  3668. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  3669. // not part of standard C++.
  3670. Diag(MemRecord->getLocation(),
  3671. diag::ext_anonymous_record_with_anonymous_type)
  3672. << (int)Record->isUnion();
  3673. }
  3674. } else if (isa<AccessSpecDecl>(Mem)) {
  3675. // Any access specifier is fine.
  3676. } else if (isa<StaticAssertDecl>(Mem)) {
  3677. // In C++1z, static_assert declarations are also fine.
  3678. } else {
  3679. // We have something that isn't a non-static data
  3680. // member. Complain about it.
  3681. unsigned DK = diag::err_anonymous_record_bad_member;
  3682. if (isa<TypeDecl>(Mem))
  3683. DK = diag::err_anonymous_record_with_type;
  3684. else if (isa<FunctionDecl>(Mem))
  3685. DK = diag::err_anonymous_record_with_function;
  3686. else if (isa<VarDecl>(Mem))
  3687. DK = diag::err_anonymous_record_with_static;
  3688. // Visual C++ allows type definition in anonymous struct or union.
  3689. if (getLangOpts().MicrosoftExt &&
  3690. DK == diag::err_anonymous_record_with_type)
  3691. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  3692. << (int)Record->isUnion();
  3693. else {
  3694. Diag(Mem->getLocation(), DK)
  3695. << (int)Record->isUnion();
  3696. Invalid = true;
  3697. }
  3698. }
  3699. }
  3700. // C++11 [class.union]p8 (DR1460):
  3701. // At most one variant member of a union may have a
  3702. // brace-or-equal-initializer.
  3703. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  3704. Owner->isRecord())
  3705. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  3706. cast<CXXRecordDecl>(Record));
  3707. }
  3708. if (!Record->isUnion() && !Owner->isRecord()) {
  3709. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  3710. << (int)getLangOpts().CPlusPlus;
  3711. Invalid = true;
  3712. }
  3713. // Mock up a declarator.
  3714. Declarator Dc(DS, Declarator::MemberContext);
  3715. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  3716. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  3717. // Create a declaration for this anonymous struct/union.
  3718. NamedDecl *Anon = nullptr;
  3719. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  3720. Anon = FieldDecl::Create(Context, OwningClass,
  3721. DS.getLocStart(),
  3722. Record->getLocation(),
  3723. /*IdentifierInfo=*/nullptr,
  3724. Context.getTypeDeclType(Record),
  3725. TInfo,
  3726. /*BitWidth=*/nullptr, /*Mutable=*/false,
  3727. /*InitStyle=*/ICIS_NoInit);
  3728. Anon->setAccess(AS);
  3729. if (getLangOpts().CPlusPlus)
  3730. FieldCollector->Add(cast<FieldDecl>(Anon));
  3731. } else {
  3732. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  3733. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  3734. if (SCSpec == DeclSpec::SCS_mutable) {
  3735. // mutable can only appear on non-static class members, so it's always
  3736. // an error here
  3737. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  3738. Invalid = true;
  3739. SC = SC_None;
  3740. }
  3741. Anon = VarDecl::Create(Context, Owner,
  3742. DS.getLocStart(),
  3743. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  3744. Context.getTypeDeclType(Record),
  3745. TInfo, SC);
  3746. // Default-initialize the implicit variable. This initialization will be
  3747. // trivial in almost all cases, except if a union member has an in-class
  3748. // initializer:
  3749. // union { int n = 0; };
  3750. ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
  3751. }
  3752. Anon->setImplicit();
  3753. // Mark this as an anonymous struct/union type.
  3754. Record->setAnonymousStructOrUnion(true);
  3755. // Add the anonymous struct/union object to the current
  3756. // context. We'll be referencing this object when we refer to one of
  3757. // its members.
  3758. Owner->addDecl(Anon);
  3759. // Inject the members of the anonymous struct/union into the owning
  3760. // context and into the identifier resolver chain for name lookup
  3761. // purposes.
  3762. SmallVector<NamedDecl*, 2> Chain;
  3763. Chain.push_back(Anon);
  3764. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
  3765. Chain, false))
  3766. Invalid = true;
  3767. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  3768. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  3769. Decl *ManglingContextDecl;
  3770. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3771. NewVD->getDeclContext(), ManglingContextDecl)) {
  3772. Context.setManglingNumber(
  3773. NewVD, MCtx->getManglingNumber(
  3774. NewVD, getMSManglingNumber(getLangOpts(), S)));
  3775. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  3776. }
  3777. }
  3778. }
  3779. if (Invalid)
  3780. Anon->setInvalidDecl();
  3781. return Anon;
  3782. }
  3783. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  3784. /// Microsoft C anonymous structure.
  3785. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  3786. /// Example:
  3787. ///
  3788. /// struct A { int a; };
  3789. /// struct B { struct A; int b; };
  3790. ///
  3791. /// void foo() {
  3792. /// B var;
  3793. /// var.a = 3;
  3794. /// }
  3795. ///
  3796. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  3797. RecordDecl *Record) {
  3798. assert(Record && "expected a record!");
  3799. // Mock up a declarator.
  3800. Declarator Dc(DS, Declarator::TypeNameContext);
  3801. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  3802. assert(TInfo && "couldn't build declarator info for anonymous struct");
  3803. auto *ParentDecl = cast<RecordDecl>(CurContext);
  3804. QualType RecTy = Context.getTypeDeclType(Record);
  3805. // Create a declaration for this anonymous struct.
  3806. NamedDecl *Anon = FieldDecl::Create(Context,
  3807. ParentDecl,
  3808. DS.getLocStart(),
  3809. DS.getLocStart(),
  3810. /*IdentifierInfo=*/nullptr,
  3811. RecTy,
  3812. TInfo,
  3813. /*BitWidth=*/nullptr, /*Mutable=*/false,
  3814. /*InitStyle=*/ICIS_NoInit);
  3815. Anon->setImplicit();
  3816. // Add the anonymous struct object to the current context.
  3817. CurContext->addDecl(Anon);
  3818. // Inject the members of the anonymous struct into the current
  3819. // context and into the identifier resolver chain for name lookup
  3820. // purposes.
  3821. SmallVector<NamedDecl*, 2> Chain;
  3822. Chain.push_back(Anon);
  3823. RecordDecl *RecordDef = Record->getDefinition();
  3824. if (RequireCompleteType(Anon->getLocation(), RecTy,
  3825. diag::err_field_incomplete) ||
  3826. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  3827. AS_none, Chain, true)) {
  3828. Anon->setInvalidDecl();
  3829. ParentDecl->setInvalidDecl();
  3830. }
  3831. return Anon;
  3832. }
  3833. /// GetNameForDeclarator - Determine the full declaration name for the
  3834. /// given Declarator.
  3835. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  3836. return GetNameFromUnqualifiedId(D.getName());
  3837. }
  3838. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  3839. DeclarationNameInfo
  3840. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  3841. DeclarationNameInfo NameInfo;
  3842. NameInfo.setLoc(Name.StartLocation);
  3843. switch (Name.getKind()) {
  3844. case UnqualifiedId::IK_ImplicitSelfParam:
  3845. case UnqualifiedId::IK_Identifier:
  3846. NameInfo.setName(Name.Identifier);
  3847. NameInfo.setLoc(Name.StartLocation);
  3848. return NameInfo;
  3849. case UnqualifiedId::IK_OperatorFunctionId:
  3850. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  3851. Name.OperatorFunctionId.Operator));
  3852. NameInfo.setLoc(Name.StartLocation);
  3853. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  3854. = Name.OperatorFunctionId.SymbolLocations[0];
  3855. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  3856. = Name.EndLocation.getRawEncoding();
  3857. return NameInfo;
  3858. case UnqualifiedId::IK_LiteralOperatorId:
  3859. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  3860. Name.Identifier));
  3861. NameInfo.setLoc(Name.StartLocation);
  3862. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  3863. return NameInfo;
  3864. case UnqualifiedId::IK_ConversionFunctionId: {
  3865. TypeSourceInfo *TInfo;
  3866. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  3867. if (Ty.isNull())
  3868. return DeclarationNameInfo();
  3869. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  3870. Context.getCanonicalType(Ty)));
  3871. NameInfo.setLoc(Name.StartLocation);
  3872. NameInfo.setNamedTypeInfo(TInfo);
  3873. return NameInfo;
  3874. }
  3875. case UnqualifiedId::IK_ConstructorName: {
  3876. TypeSourceInfo *TInfo;
  3877. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  3878. if (Ty.isNull())
  3879. return DeclarationNameInfo();
  3880. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  3881. Context.getCanonicalType(Ty)));
  3882. NameInfo.setLoc(Name.StartLocation);
  3883. NameInfo.setNamedTypeInfo(TInfo);
  3884. return NameInfo;
  3885. }
  3886. case UnqualifiedId::IK_ConstructorTemplateId: {
  3887. // In well-formed code, we can only have a constructor
  3888. // template-id that refers to the current context, so go there
  3889. // to find the actual type being constructed.
  3890. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  3891. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  3892. return DeclarationNameInfo();
  3893. // Determine the type of the class being constructed.
  3894. QualType CurClassType = Context.getTypeDeclType(CurClass);
  3895. // FIXME: Check two things: that the template-id names the same type as
  3896. // CurClassType, and that the template-id does not occur when the name
  3897. // was qualified.
  3898. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  3899. Context.getCanonicalType(CurClassType)));
  3900. NameInfo.setLoc(Name.StartLocation);
  3901. // FIXME: should we retrieve TypeSourceInfo?
  3902. NameInfo.setNamedTypeInfo(nullptr);
  3903. return NameInfo;
  3904. }
  3905. case UnqualifiedId::IK_DestructorName: {
  3906. TypeSourceInfo *TInfo;
  3907. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  3908. if (Ty.isNull())
  3909. return DeclarationNameInfo();
  3910. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  3911. Context.getCanonicalType(Ty)));
  3912. NameInfo.setLoc(Name.StartLocation);
  3913. NameInfo.setNamedTypeInfo(TInfo);
  3914. return NameInfo;
  3915. }
  3916. case UnqualifiedId::IK_TemplateId: {
  3917. TemplateName TName = Name.TemplateId->Template.get();
  3918. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  3919. return Context.getNameForTemplate(TName, TNameLoc);
  3920. }
  3921. } // switch (Name.getKind())
  3922. llvm_unreachable("Unknown name kind");
  3923. }
  3924. static QualType getCoreType(QualType Ty) {
  3925. do {
  3926. if (Ty->isPointerType() || Ty->isReferenceType())
  3927. Ty = Ty->getPointeeType();
  3928. else if (Ty->isArrayType())
  3929. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  3930. else
  3931. return Ty.withoutLocalFastQualifiers();
  3932. } while (true);
  3933. }
  3934. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  3935. /// and Definition have "nearly" matching parameters. This heuristic is
  3936. /// used to improve diagnostics in the case where an out-of-line function
  3937. /// definition doesn't match any declaration within the class or namespace.
  3938. /// Also sets Params to the list of indices to the parameters that differ
  3939. /// between the declaration and the definition. If hasSimilarParameters
  3940. /// returns true and Params is empty, then all of the parameters match.
  3941. static bool hasSimilarParameters(ASTContext &Context,
  3942. FunctionDecl *Declaration,
  3943. FunctionDecl *Definition,
  3944. SmallVectorImpl<unsigned> &Params) {
  3945. Params.clear();
  3946. if (Declaration->param_size() != Definition->param_size())
  3947. return false;
  3948. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  3949. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  3950. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  3951. // The parameter types are identical
  3952. if (Context.hasSameType(DefParamTy, DeclParamTy))
  3953. continue;
  3954. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  3955. QualType DefParamBaseTy = getCoreType(DefParamTy);
  3956. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  3957. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  3958. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  3959. (DeclTyName && DeclTyName == DefTyName))
  3960. Params.push_back(Idx);
  3961. else // The two parameters aren't even close
  3962. return false;
  3963. }
  3964. return true;
  3965. }
  3966. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  3967. /// declarator needs to be rebuilt in the current instantiation.
  3968. /// Any bits of declarator which appear before the name are valid for
  3969. /// consideration here. That's specifically the type in the decl spec
  3970. /// and the base type in any member-pointer chunks.
  3971. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  3972. DeclarationName Name) {
  3973. // The types we specifically need to rebuild are:
  3974. // - typenames, typeofs, and decltypes
  3975. // - types which will become injected class names
  3976. // Of course, we also need to rebuild any type referencing such a
  3977. // type. It's safest to just say "dependent", but we call out a
  3978. // few cases here.
  3979. DeclSpec &DS = D.getMutableDeclSpec();
  3980. switch (DS.getTypeSpecType()) {
  3981. case DeclSpec::TST_typename:
  3982. case DeclSpec::TST_typeofType:
  3983. case DeclSpec::TST_underlyingType:
  3984. case DeclSpec::TST_atomic: {
  3985. // Grab the type from the parser.
  3986. TypeSourceInfo *TSI = nullptr;
  3987. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  3988. if (T.isNull() || !T->isDependentType()) break;
  3989. // Make sure there's a type source info. This isn't really much
  3990. // of a waste; most dependent types should have type source info
  3991. // attached already.
  3992. if (!TSI)
  3993. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  3994. // Rebuild the type in the current instantiation.
  3995. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  3996. if (!TSI) return true;
  3997. // Store the new type back in the decl spec.
  3998. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  3999. DS.UpdateTypeRep(LocType);
  4000. break;
  4001. }
  4002. case DeclSpec::TST_decltype:
  4003. case DeclSpec::TST_typeofExpr: {
  4004. Expr *E = DS.getRepAsExpr();
  4005. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4006. if (Result.isInvalid()) return true;
  4007. DS.UpdateExprRep(Result.get());
  4008. break;
  4009. }
  4010. default:
  4011. // Nothing to do for these decl specs.
  4012. break;
  4013. }
  4014. // It doesn't matter what order we do this in.
  4015. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4016. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4017. // The only type information in the declarator which can come
  4018. // before the declaration name is the base type of a member
  4019. // pointer.
  4020. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4021. continue;
  4022. // Rebuild the scope specifier in-place.
  4023. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4024. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4025. return true;
  4026. }
  4027. return false;
  4028. }
  4029. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4030. D.setFunctionDefinitionKind(FDK_Declaration);
  4031. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4032. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4033. Dcl && Dcl->getDeclContext()->isFileContext())
  4034. Dcl->setTopLevelDeclInObjCContainer();
  4035. return Dcl;
  4036. }
  4037. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4038. /// If T is the name of a class, then each of the following shall have a
  4039. /// name different from T:
  4040. /// - every static data member of class T;
  4041. /// - every member function of class T
  4042. /// - every member of class T that is itself a type;
  4043. /// \returns true if the declaration name violates these rules.
  4044. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4045. DeclarationNameInfo NameInfo) {
  4046. DeclarationName Name = NameInfo.getName();
  4047. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  4048. if (Record->getIdentifier() && Record->getDeclName() == Name) {
  4049. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4050. return true;
  4051. }
  4052. return false;
  4053. }
  4054. /// \brief Diagnose a declaration whose declarator-id has the given
  4055. /// nested-name-specifier.
  4056. ///
  4057. /// \param SS The nested-name-specifier of the declarator-id.
  4058. ///
  4059. /// \param DC The declaration context to which the nested-name-specifier
  4060. /// resolves.
  4061. ///
  4062. /// \param Name The name of the entity being declared.
  4063. ///
  4064. /// \param Loc The location of the name of the entity being declared.
  4065. ///
  4066. /// \returns true if we cannot safely recover from this error, false otherwise.
  4067. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4068. DeclarationName Name,
  4069. SourceLocation Loc) {
  4070. DeclContext *Cur = CurContext;
  4071. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4072. Cur = Cur->getParent();
  4073. // If the user provided a superfluous scope specifier that refers back to the
  4074. // class in which the entity is already declared, diagnose and ignore it.
  4075. //
  4076. // class X {
  4077. // void X::f();
  4078. // };
  4079. //
  4080. // Note, it was once ill-formed to give redundant qualification in all
  4081. // contexts, but that rule was removed by DR482.
  4082. if (Cur->Equals(DC)) {
  4083. if (Cur->isRecord()) {
  4084. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4085. : diag::err_member_extra_qualification)
  4086. << Name << FixItHint::CreateRemoval(SS.getRange());
  4087. SS.clear();
  4088. } else {
  4089. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4090. }
  4091. return false;
  4092. }
  4093. // Check whether the qualifying scope encloses the scope of the original
  4094. // declaration.
  4095. if (!Cur->Encloses(DC)) {
  4096. if (Cur->isRecord())
  4097. Diag(Loc, diag::err_member_qualification)
  4098. << Name << SS.getRange();
  4099. else if (isa<TranslationUnitDecl>(DC))
  4100. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4101. << Name << SS.getRange();
  4102. else if (isa<FunctionDecl>(Cur))
  4103. Diag(Loc, diag::err_invalid_declarator_in_function)
  4104. << Name << SS.getRange();
  4105. else if (isa<BlockDecl>(Cur))
  4106. Diag(Loc, diag::err_invalid_declarator_in_block)
  4107. << Name << SS.getRange();
  4108. else
  4109. Diag(Loc, diag::err_invalid_declarator_scope)
  4110. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4111. return true;
  4112. }
  4113. if (Cur->isRecord()) {
  4114. // Cannot qualify members within a class.
  4115. Diag(Loc, diag::err_member_qualification)
  4116. << Name << SS.getRange();
  4117. SS.clear();
  4118. // C++ constructors and destructors with incorrect scopes can break
  4119. // our AST invariants by having the wrong underlying types. If
  4120. // that's the case, then drop this declaration entirely.
  4121. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4122. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4123. !Context.hasSameType(Name.getCXXNameType(),
  4124. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4125. return true;
  4126. return false;
  4127. }
  4128. // C++11 [dcl.meaning]p1:
  4129. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4130. // not begin with a decltype-specifer"
  4131. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4132. while (SpecLoc.getPrefix())
  4133. SpecLoc = SpecLoc.getPrefix();
  4134. if (dyn_cast_or_null<DecltypeType>(
  4135. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4136. Diag(Loc, diag::err_decltype_in_declarator)
  4137. << SpecLoc.getTypeLoc().getSourceRange();
  4138. return false;
  4139. }
  4140. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4141. MultiTemplateParamsArg TemplateParamLists) {
  4142. // TODO: consider using NameInfo for diagnostic.
  4143. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4144. DeclarationName Name = NameInfo.getName();
  4145. // All of these full declarators require an identifier. If it doesn't have
  4146. // one, the ParsedFreeStandingDeclSpec action should be used.
  4147. if (!Name) {
  4148. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4149. Diag(D.getDeclSpec().getLocStart(),
  4150. diag::err_declarator_need_ident)
  4151. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4152. return nullptr;
  4153. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4154. return nullptr;
  4155. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4156. // we find one that is.
  4157. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4158. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4159. S = S->getParent();
  4160. DeclContext *DC = CurContext;
  4161. if (D.getCXXScopeSpec().isInvalid())
  4162. D.setInvalidType();
  4163. else if (D.getCXXScopeSpec().isSet()) {
  4164. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4165. UPPC_DeclarationQualifier))
  4166. return nullptr;
  4167. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4168. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4169. if (!DC || isa<EnumDecl>(DC)) {
  4170. // If we could not compute the declaration context, it's because the
  4171. // declaration context is dependent but does not refer to a class,
  4172. // class template, or class template partial specialization. Complain
  4173. // and return early, to avoid the coming semantic disaster.
  4174. Diag(D.getIdentifierLoc(),
  4175. diag::err_template_qualified_declarator_no_match)
  4176. << D.getCXXScopeSpec().getScopeRep()
  4177. << D.getCXXScopeSpec().getRange();
  4178. return nullptr;
  4179. }
  4180. bool IsDependentContext = DC->isDependentContext();
  4181. if (!IsDependentContext &&
  4182. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4183. return nullptr;
  4184. // If a class is incomplete, do not parse entities inside it.
  4185. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4186. Diag(D.getIdentifierLoc(),
  4187. diag::err_member_def_undefined_record)
  4188. << Name << DC << D.getCXXScopeSpec().getRange();
  4189. return nullptr;
  4190. }
  4191. if (!D.getDeclSpec().isFriendSpecified()) {
  4192. if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
  4193. Name, D.getIdentifierLoc())) {
  4194. if (DC->isRecord())
  4195. return nullptr;
  4196. D.setInvalidType();
  4197. }
  4198. }
  4199. // Check whether we need to rebuild the type of the given
  4200. // declaration in the current instantiation.
  4201. if (EnteringContext && IsDependentContext &&
  4202. TemplateParamLists.size() != 0) {
  4203. ContextRAII SavedContext(*this, DC);
  4204. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4205. D.setInvalidType();
  4206. }
  4207. }
  4208. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4209. QualType R = TInfo->getType();
  4210. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4211. // If this is a typedef, we'll end up spewing multiple diagnostics.
  4212. // Just return early; it's safer. If this is a function, let the
  4213. // "constructor cannot have a return type" diagnostic handle it.
  4214. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4215. return nullptr;
  4216. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4217. UPPC_DeclarationType))
  4218. D.setInvalidType();
  4219. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4220. ForRedeclaration);
  4221. // If we're hiding internal-linkage symbols in modules from redeclaration
  4222. // lookup, let name lookup know.
  4223. if ((getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) &&
  4224. getLangOpts().ModulesHideInternalLinkage &&
  4225. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
  4226. Previous.setAllowHiddenInternal(false);
  4227. // See if this is a redefinition of a variable in the same scope.
  4228. if (!D.getCXXScopeSpec().isSet()) {
  4229. bool IsLinkageLookup = false;
  4230. bool CreateBuiltins = false;
  4231. // If the declaration we're planning to build will be a function
  4232. // or object with linkage, then look for another declaration with
  4233. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4234. //
  4235. // If the declaration we're planning to build will be declared with
  4236. // external linkage in the translation unit, create any builtin with
  4237. // the same name.
  4238. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4239. /* Do nothing*/;
  4240. else if (CurContext->isFunctionOrMethod() &&
  4241. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4242. R->isFunctionType())) {
  4243. IsLinkageLookup = true;
  4244. CreateBuiltins =
  4245. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4246. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4247. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4248. CreateBuiltins = true;
  4249. if (IsLinkageLookup)
  4250. Previous.clear(LookupRedeclarationWithLinkage);
  4251. LookupName(Previous, S, CreateBuiltins);
  4252. } else { // Something like "int foo::x;"
  4253. LookupQualifiedName(Previous, DC);
  4254. // C++ [dcl.meaning]p1:
  4255. // When the declarator-id is qualified, the declaration shall refer to a
  4256. // previously declared member of the class or namespace to which the
  4257. // qualifier refers (or, in the case of a namespace, of an element of the
  4258. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4259. // thereof; [...]
  4260. //
  4261. // Note that we already checked the context above, and that we do not have
  4262. // enough information to make sure that Previous contains the declaration
  4263. // we want to match. For example, given:
  4264. //
  4265. // class X {
  4266. // void f();
  4267. // void f(float);
  4268. // };
  4269. //
  4270. // void X::f(int) { } // ill-formed
  4271. //
  4272. // In this case, Previous will point to the overload set
  4273. // containing the two f's declared in X, but neither of them
  4274. // matches.
  4275. // C++ [dcl.meaning]p1:
  4276. // [...] the member shall not merely have been introduced by a
  4277. // using-declaration in the scope of the class or namespace nominated by
  4278. // the nested-name-specifier of the declarator-id.
  4279. RemoveUsingDecls(Previous);
  4280. }
  4281. if (Previous.isSingleResult() &&
  4282. Previous.getFoundDecl()->isTemplateParameter()) {
  4283. // Maybe we will complain about the shadowed template parameter.
  4284. if (!D.isInvalidType())
  4285. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4286. Previous.getFoundDecl());
  4287. // Just pretend that we didn't see the previous declaration.
  4288. Previous.clear();
  4289. }
  4290. // In C++, the previous declaration we find might be a tag type
  4291. // (class or enum). In this case, the new declaration will hide the
  4292. // tag type. Note that this does does not apply if we're declaring a
  4293. // typedef (C++ [dcl.typedef]p4).
  4294. if (Previous.isSingleTagDecl() &&
  4295. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
  4296. Previous.clear();
  4297. // Check that there are no default arguments other than in the parameters
  4298. // of a function declaration (C++ only).
  4299. if (getLangOpts().CPlusPlus)
  4300. CheckExtraCXXDefaultArguments(D);
  4301. if (D.getDeclSpec().isConceptSpecified()) {
  4302. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  4303. // applied only to the definition of a function template or variable
  4304. // template, declared in namespace scope
  4305. if (!TemplateParamLists.size()) {
  4306. Diag(D.getDeclSpec().getConceptSpecLoc(),
  4307. diag:: err_concept_wrong_decl_kind);
  4308. return nullptr;
  4309. }
  4310. if (!DC->getRedeclContext()->isFileContext()) {
  4311. Diag(D.getIdentifierLoc(),
  4312. diag::err_concept_decls_may_only_appear_in_namespace_scope);
  4313. return nullptr;
  4314. }
  4315. }
  4316. NamedDecl *New;
  4317. bool AddToScope = true;
  4318. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  4319. if (TemplateParamLists.size()) {
  4320. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  4321. return nullptr;
  4322. }
  4323. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  4324. } else if (R->isFunctionType()) {
  4325. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  4326. TemplateParamLists,
  4327. AddToScope);
  4328. } else {
  4329. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  4330. AddToScope);
  4331. }
  4332. if (!New)
  4333. return nullptr;
  4334. // If this has an identifier and is not an invalid redeclaration or
  4335. // function template specialization, add it to the scope stack.
  4336. if (New->getDeclName() && AddToScope &&
  4337. !(D.isRedeclaration() && New->isInvalidDecl())) {
  4338. // Only make a locally-scoped extern declaration visible if it is the first
  4339. // declaration of this entity. Qualified lookup for such an entity should
  4340. // only find this declaration if there is no visible declaration of it.
  4341. bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
  4342. PushOnScopeChains(New, S, AddToContext);
  4343. if (!AddToContext)
  4344. CurContext->addHiddenDecl(New);
  4345. }
  4346. return New;
  4347. }
  4348. /// Helper method to turn variable array types into constant array
  4349. /// types in certain situations which would otherwise be errors (for
  4350. /// GCC compatibility).
  4351. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  4352. ASTContext &Context,
  4353. bool &SizeIsNegative,
  4354. llvm::APSInt &Oversized) {
  4355. // This method tries to turn a variable array into a constant
  4356. // array even when the size isn't an ICE. This is necessary
  4357. // for compatibility with code that depends on gcc's buggy
  4358. // constant expression folding, like struct {char x[(int)(char*)2];}
  4359. SizeIsNegative = false;
  4360. Oversized = 0;
  4361. if (T->isDependentType())
  4362. return QualType();
  4363. QualifierCollector Qs;
  4364. const Type *Ty = Qs.strip(T);
  4365. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  4366. QualType Pointee = PTy->getPointeeType();
  4367. QualType FixedType =
  4368. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  4369. Oversized);
  4370. if (FixedType.isNull()) return FixedType;
  4371. FixedType = Context.getPointerType(FixedType);
  4372. return Qs.apply(Context, FixedType);
  4373. }
  4374. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  4375. QualType Inner = PTy->getInnerType();
  4376. QualType FixedType =
  4377. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  4378. Oversized);
  4379. if (FixedType.isNull()) return FixedType;
  4380. FixedType = Context.getParenType(FixedType);
  4381. return Qs.apply(Context, FixedType);
  4382. }
  4383. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  4384. if (!VLATy)
  4385. return QualType();
  4386. // FIXME: We should probably handle this case
  4387. if (VLATy->getElementType()->isVariablyModifiedType())
  4388. return QualType();
  4389. llvm::APSInt Res;
  4390. if (!VLATy->getSizeExpr() ||
  4391. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  4392. return QualType();
  4393. // Check whether the array size is negative.
  4394. if (Res.isSigned() && Res.isNegative()) {
  4395. SizeIsNegative = true;
  4396. return QualType();
  4397. }
  4398. // Check whether the array is too large to be addressed.
  4399. unsigned ActiveSizeBits
  4400. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  4401. Res);
  4402. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  4403. Oversized = Res;
  4404. return QualType();
  4405. }
  4406. return Context.getConstantArrayType(VLATy->getElementType(),
  4407. Res, ArrayType::Normal, 0);
  4408. }
  4409. static void
  4410. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  4411. SrcTL = SrcTL.getUnqualifiedLoc();
  4412. DstTL = DstTL.getUnqualifiedLoc();
  4413. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  4414. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  4415. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  4416. DstPTL.getPointeeLoc());
  4417. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  4418. return;
  4419. }
  4420. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  4421. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  4422. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  4423. DstPTL.getInnerLoc());
  4424. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  4425. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  4426. return;
  4427. }
  4428. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  4429. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  4430. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  4431. TypeLoc DstElemTL = DstATL.getElementLoc();
  4432. DstElemTL.initializeFullCopy(SrcElemTL);
  4433. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  4434. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  4435. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  4436. }
  4437. /// Helper method to turn variable array types into constant array
  4438. /// types in certain situations which would otherwise be errors (for
  4439. /// GCC compatibility).
  4440. static TypeSourceInfo*
  4441. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  4442. ASTContext &Context,
  4443. bool &SizeIsNegative,
  4444. llvm::APSInt &Oversized) {
  4445. QualType FixedTy
  4446. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  4447. SizeIsNegative, Oversized);
  4448. if (FixedTy.isNull())
  4449. return nullptr;
  4450. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  4451. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  4452. FixedTInfo->getTypeLoc());
  4453. return FixedTInfo;
  4454. }
  4455. /// \brief Register the given locally-scoped extern "C" declaration so
  4456. /// that it can be found later for redeclarations. We include any extern "C"
  4457. /// declaration that is not visible in the translation unit here, not just
  4458. /// function-scope declarations.
  4459. void
  4460. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  4461. if (!getLangOpts().CPlusPlus &&
  4462. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  4463. // Don't need to track declarations in the TU in C.
  4464. return;
  4465. // Note that we have a locally-scoped external with this name.
  4466. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  4467. }
  4468. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  4469. // FIXME: We can have multiple results via __attribute__((overloadable)).
  4470. auto Result = Context.getExternCContextDecl()->lookup(Name);
  4471. return Result.empty() ? nullptr : *Result.begin();
  4472. }
  4473. /// \brief Diagnose function specifiers on a declaration of an identifier that
  4474. /// does not identify a function.
  4475. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  4476. // FIXME: We should probably indicate the identifier in question to avoid
  4477. // confusion for constructs like "inline int a(), b;"
  4478. if (DS.isInlineSpecified())
  4479. Diag(DS.getInlineSpecLoc(),
  4480. diag::err_inline_non_function);
  4481. if (DS.isVirtualSpecified())
  4482. Diag(DS.getVirtualSpecLoc(),
  4483. diag::err_virtual_non_function);
  4484. if (DS.isExplicitSpecified())
  4485. Diag(DS.getExplicitSpecLoc(),
  4486. diag::err_explicit_non_function);
  4487. if (DS.isNoreturnSpecified())
  4488. Diag(DS.getNoreturnSpecLoc(),
  4489. diag::err_noreturn_non_function);
  4490. }
  4491. NamedDecl*
  4492. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  4493. TypeSourceInfo *TInfo, LookupResult &Previous) {
  4494. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  4495. if (D.getCXXScopeSpec().isSet()) {
  4496. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  4497. << D.getCXXScopeSpec().getRange();
  4498. D.setInvalidType();
  4499. // Pretend we didn't see the scope specifier.
  4500. DC = CurContext;
  4501. Previous.clear();
  4502. }
  4503. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  4504. if (D.getDeclSpec().isConstexprSpecified())
  4505. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  4506. << 1;
  4507. if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
  4508. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  4509. << D.getName().getSourceRange();
  4510. return nullptr;
  4511. }
  4512. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  4513. if (!NewTD) return nullptr;
  4514. // Handle attributes prior to checking for duplicates in MergeVarDecl
  4515. ProcessDeclAttributes(S, NewTD, D);
  4516. CheckTypedefForVariablyModifiedType(S, NewTD);
  4517. bool Redeclaration = D.isRedeclaration();
  4518. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  4519. D.setRedeclaration(Redeclaration);
  4520. return ND;
  4521. }
  4522. void
  4523. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  4524. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  4525. // then it shall have block scope.
  4526. // Note that variably modified types must be fixed before merging the decl so
  4527. // that redeclarations will match.
  4528. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  4529. QualType T = TInfo->getType();
  4530. if (T->isVariablyModifiedType()) {
  4531. getCurFunction()->setHasBranchProtectedScope();
  4532. if (S->getFnParent() == nullptr) {
  4533. bool SizeIsNegative;
  4534. llvm::APSInt Oversized;
  4535. TypeSourceInfo *FixedTInfo =
  4536. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  4537. SizeIsNegative,
  4538. Oversized);
  4539. if (FixedTInfo) {
  4540. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  4541. NewTD->setTypeSourceInfo(FixedTInfo);
  4542. } else {
  4543. if (SizeIsNegative)
  4544. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  4545. else if (T->isVariableArrayType())
  4546. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  4547. else if (Oversized.getBoolValue())
  4548. Diag(NewTD->getLocation(), diag::err_array_too_large)
  4549. << Oversized.toString(10);
  4550. else
  4551. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  4552. NewTD->setInvalidDecl();
  4553. }
  4554. }
  4555. }
  4556. }
  4557. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  4558. /// declares a typedef-name, either using the 'typedef' type specifier or via
  4559. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  4560. NamedDecl*
  4561. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  4562. LookupResult &Previous, bool &Redeclaration) {
  4563. // Merge the decl with the existing one if appropriate. If the decl is
  4564. // in an outer scope, it isn't the same thing.
  4565. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  4566. /*AllowInlineNamespace*/false);
  4567. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  4568. if (!Previous.empty()) {
  4569. Redeclaration = true;
  4570. MergeTypedefNameDecl(NewTD, Previous);
  4571. }
  4572. // If this is the C FILE type, notify the AST context.
  4573. if (IdentifierInfo *II = NewTD->getIdentifier())
  4574. if (!NewTD->isInvalidDecl() &&
  4575. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  4576. if (II->isStr("FILE"))
  4577. Context.setFILEDecl(NewTD);
  4578. else if (II->isStr("jmp_buf"))
  4579. Context.setjmp_bufDecl(NewTD);
  4580. else if (II->isStr("sigjmp_buf"))
  4581. Context.setsigjmp_bufDecl(NewTD);
  4582. else if (II->isStr("ucontext_t"))
  4583. Context.setucontext_tDecl(NewTD);
  4584. }
  4585. return NewTD;
  4586. }
  4587. /// \brief Determines whether the given declaration is an out-of-scope
  4588. /// previous declaration.
  4589. ///
  4590. /// This routine should be invoked when name lookup has found a
  4591. /// previous declaration (PrevDecl) that is not in the scope where a
  4592. /// new declaration by the same name is being introduced. If the new
  4593. /// declaration occurs in a local scope, previous declarations with
  4594. /// linkage may still be considered previous declarations (C99
  4595. /// 6.2.2p4-5, C++ [basic.link]p6).
  4596. ///
  4597. /// \param PrevDecl the previous declaration found by name
  4598. /// lookup
  4599. ///
  4600. /// \param DC the context in which the new declaration is being
  4601. /// declared.
  4602. ///
  4603. /// \returns true if PrevDecl is an out-of-scope previous declaration
  4604. /// for a new delcaration with the same name.
  4605. static bool
  4606. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  4607. ASTContext &Context) {
  4608. if (!PrevDecl)
  4609. return false;
  4610. if (!PrevDecl->hasLinkage())
  4611. return false;
  4612. if (Context.getLangOpts().CPlusPlus) {
  4613. // C++ [basic.link]p6:
  4614. // If there is a visible declaration of an entity with linkage
  4615. // having the same name and type, ignoring entities declared
  4616. // outside the innermost enclosing namespace scope, the block
  4617. // scope declaration declares that same entity and receives the
  4618. // linkage of the previous declaration.
  4619. DeclContext *OuterContext = DC->getRedeclContext();
  4620. if (!OuterContext->isFunctionOrMethod())
  4621. // This rule only applies to block-scope declarations.
  4622. return false;
  4623. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  4624. if (PrevOuterContext->isRecord())
  4625. // We found a member function: ignore it.
  4626. return false;
  4627. // Find the innermost enclosing namespace for the new and
  4628. // previous declarations.
  4629. OuterContext = OuterContext->getEnclosingNamespaceContext();
  4630. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  4631. // The previous declaration is in a different namespace, so it
  4632. // isn't the same function.
  4633. if (!OuterContext->Equals(PrevOuterContext))
  4634. return false;
  4635. }
  4636. return true;
  4637. }
  4638. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  4639. CXXScopeSpec &SS = D.getCXXScopeSpec();
  4640. if (!SS.isSet()) return;
  4641. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  4642. }
  4643. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  4644. QualType type = decl->getType();
  4645. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  4646. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  4647. // Various kinds of declaration aren't allowed to be __autoreleasing.
  4648. unsigned kind = -1U;
  4649. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  4650. if (var->hasAttr<BlocksAttr>())
  4651. kind = 0; // __block
  4652. else if (!var->hasLocalStorage())
  4653. kind = 1; // global
  4654. } else if (isa<ObjCIvarDecl>(decl)) {
  4655. kind = 3; // ivar
  4656. } else if (isa<FieldDecl>(decl)) {
  4657. kind = 2; // field
  4658. }
  4659. if (kind != -1U) {
  4660. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  4661. << kind;
  4662. }
  4663. } else if (lifetime == Qualifiers::OCL_None) {
  4664. // Try to infer lifetime.
  4665. if (!type->isObjCLifetimeType())
  4666. return false;
  4667. lifetime = type->getObjCARCImplicitLifetime();
  4668. type = Context.getLifetimeQualifiedType(type, lifetime);
  4669. decl->setType(type);
  4670. }
  4671. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  4672. // Thread-local variables cannot have lifetime.
  4673. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  4674. var->getTLSKind()) {
  4675. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  4676. << var->getType();
  4677. return true;
  4678. }
  4679. }
  4680. return false;
  4681. }
  4682. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  4683. // Ensure that an auto decl is deduced otherwise the checks below might cache
  4684. // the wrong linkage.
  4685. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  4686. // 'weak' only applies to declarations with external linkage.
  4687. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  4688. if (!ND.isExternallyVisible()) {
  4689. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  4690. ND.dropAttr<WeakAttr>();
  4691. }
  4692. }
  4693. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  4694. if (ND.isExternallyVisible()) {
  4695. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  4696. ND.dropAttr<WeakRefAttr>();
  4697. ND.dropAttr<AliasAttr>();
  4698. }
  4699. }
  4700. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  4701. if (VD->hasInit()) {
  4702. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  4703. assert(VD->isThisDeclarationADefinition() &&
  4704. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  4705. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
  4706. VD->dropAttr<AliasAttr>();
  4707. }
  4708. }
  4709. }
  4710. // 'selectany' only applies to externally visible variable declarations.
  4711. // It does not apply to functions.
  4712. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  4713. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  4714. S.Diag(Attr->getLocation(),
  4715. diag::err_attribute_selectany_non_extern_data);
  4716. ND.dropAttr<SelectAnyAttr>();
  4717. }
  4718. }
  4719. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  4720. // dll attributes require external linkage. Static locals may have external
  4721. // linkage but still cannot be explicitly imported or exported.
  4722. auto *VD = dyn_cast<VarDecl>(&ND);
  4723. if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
  4724. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  4725. << &ND << Attr;
  4726. ND.setInvalidDecl();
  4727. }
  4728. }
  4729. }
  4730. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  4731. NamedDecl *NewDecl,
  4732. bool IsSpecialization) {
  4733. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
  4734. OldDecl = OldTD->getTemplatedDecl();
  4735. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
  4736. NewDecl = NewTD->getTemplatedDecl();
  4737. if (!OldDecl || !NewDecl)
  4738. return;
  4739. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  4740. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  4741. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  4742. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  4743. // dllimport and dllexport are inheritable attributes so we have to exclude
  4744. // inherited attribute instances.
  4745. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  4746. (NewExportAttr && !NewExportAttr->isInherited());
  4747. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  4748. // the only exception being explicit specializations.
  4749. // Implicitly generated declarations are also excluded for now because there
  4750. // is no other way to switch these to use dllimport or dllexport.
  4751. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  4752. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  4753. // Allow with a warning for free functions and global variables.
  4754. bool JustWarn = false;
  4755. if (!OldDecl->isCXXClassMember()) {
  4756. auto *VD = dyn_cast<VarDecl>(OldDecl);
  4757. if (VD && !VD->getDescribedVarTemplate())
  4758. JustWarn = true;
  4759. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  4760. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  4761. JustWarn = true;
  4762. }
  4763. // We cannot change a declaration that's been used because IR has already
  4764. // been emitted. Dllimported functions will still work though (modulo
  4765. // address equality) as they can use the thunk.
  4766. if (OldDecl->isUsed())
  4767. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  4768. JustWarn = false;
  4769. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  4770. : diag::err_attribute_dll_redeclaration;
  4771. S.Diag(NewDecl->getLocation(), DiagID)
  4772. << NewDecl
  4773. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  4774. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  4775. if (!JustWarn) {
  4776. NewDecl->setInvalidDecl();
  4777. return;
  4778. }
  4779. }
  4780. // A redeclaration is not allowed to drop a dllimport attribute, the only
  4781. // exceptions being inline function definitions, local extern declarations,
  4782. // and qualified friend declarations.
  4783. // NB: MSVC converts such a declaration to dllexport.
  4784. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  4785. if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
  4786. // Ignore static data because out-of-line definitions are diagnosed
  4787. // separately.
  4788. IsStaticDataMember = VD->isStaticDataMember();
  4789. else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  4790. IsInline = FD->isInlined();
  4791. IsQualifiedFriend = FD->getQualifier() &&
  4792. FD->getFriendObjectKind() == Decl::FOK_Declared;
  4793. }
  4794. if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
  4795. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  4796. S.Diag(NewDecl->getLocation(),
  4797. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  4798. << NewDecl << OldImportAttr;
  4799. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  4800. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  4801. OldDecl->dropAttr<DLLImportAttr>();
  4802. NewDecl->dropAttr<DLLImportAttr>();
  4803. } else if (IsInline && OldImportAttr &&
  4804. !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  4805. // In MinGW, seeing a function declared inline drops the dllimport attribute.
  4806. OldDecl->dropAttr<DLLImportAttr>();
  4807. NewDecl->dropAttr<DLLImportAttr>();
  4808. S.Diag(NewDecl->getLocation(),
  4809. diag::warn_dllimport_dropped_from_inline_function)
  4810. << NewDecl << OldImportAttr;
  4811. }
  4812. }
  4813. /// Given that we are within the definition of the given function,
  4814. /// will that definition behave like C99's 'inline', where the
  4815. /// definition is discarded except for optimization purposes?
  4816. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  4817. // Try to avoid calling GetGVALinkageForFunction.
  4818. // All cases of this require the 'inline' keyword.
  4819. if (!FD->isInlined()) return false;
  4820. // This is only possible in C++ with the gnu_inline attribute.
  4821. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  4822. return false;
  4823. // Okay, go ahead and call the relatively-more-expensive function.
  4824. #ifndef NDEBUG
  4825. // AST quite reasonably asserts that it's working on a function
  4826. // definition. We don't really have a way to tell it that we're
  4827. // currently defining the function, so just lie to it in +Asserts
  4828. // builds. This is an awful hack.
  4829. FD->setLazyBody(1);
  4830. #endif
  4831. bool isC99Inline =
  4832. S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  4833. #ifndef NDEBUG
  4834. FD->setLazyBody(0);
  4835. #endif
  4836. return isC99Inline;
  4837. }
  4838. /// Determine whether a variable is extern "C" prior to attaching
  4839. /// an initializer. We can't just call isExternC() here, because that
  4840. /// will also compute and cache whether the declaration is externally
  4841. /// visible, which might change when we attach the initializer.
  4842. ///
  4843. /// This can only be used if the declaration is known to not be a
  4844. /// redeclaration of an internal linkage declaration.
  4845. ///
  4846. /// For instance:
  4847. ///
  4848. /// auto x = []{};
  4849. ///
  4850. /// Attaching the initializer here makes this declaration not externally
  4851. /// visible, because its type has internal linkage.
  4852. ///
  4853. /// FIXME: This is a hack.
  4854. template<typename T>
  4855. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  4856. if (S.getLangOpts().CPlusPlus) {
  4857. // In C++, the overloadable attribute negates the effects of extern "C".
  4858. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  4859. return false;
  4860. }
  4861. return D->isExternC();
  4862. }
  4863. static bool shouldConsiderLinkage(const VarDecl *VD) {
  4864. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  4865. if (DC->isFunctionOrMethod())
  4866. return VD->hasExternalStorage();
  4867. if (DC->isFileContext())
  4868. return true;
  4869. if (DC->isRecord())
  4870. return false;
  4871. llvm_unreachable("Unexpected context");
  4872. }
  4873. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  4874. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  4875. if (DC->isFileContext() || DC->isFunctionOrMethod())
  4876. return true;
  4877. if (DC->isRecord())
  4878. return false;
  4879. llvm_unreachable("Unexpected context");
  4880. }
  4881. static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
  4882. AttributeList::Kind Kind) {
  4883. for (const AttributeList *L = AttrList; L; L = L->getNext())
  4884. if (L->getKind() == Kind)
  4885. return true;
  4886. return false;
  4887. }
  4888. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  4889. AttributeList::Kind Kind) {
  4890. // Check decl attributes on the DeclSpec.
  4891. if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
  4892. return true;
  4893. // Walk the declarator structure, checking decl attributes that were in a type
  4894. // position to the decl itself.
  4895. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  4896. if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
  4897. return true;
  4898. }
  4899. // Finally, check attributes on the decl itself.
  4900. return hasParsedAttr(S, PD.getAttributes(), Kind);
  4901. }
  4902. /// Adjust the \c DeclContext for a function or variable that might be a
  4903. /// function-local external declaration.
  4904. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  4905. if (!DC->isFunctionOrMethod())
  4906. return false;
  4907. // If this is a local extern function or variable declared within a function
  4908. // template, don't add it into the enclosing namespace scope until it is
  4909. // instantiated; it might have a dependent type right now.
  4910. if (DC->isDependentContext())
  4911. return true;
  4912. // C++11 [basic.link]p7:
  4913. // When a block scope declaration of an entity with linkage is not found to
  4914. // refer to some other declaration, then that entity is a member of the
  4915. // innermost enclosing namespace.
  4916. //
  4917. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  4918. // semantically-enclosing namespace, not a lexically-enclosing one.
  4919. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  4920. DC = DC->getParent();
  4921. return true;
  4922. }
  4923. /// \brief Returns true if given declaration has external C language linkage.
  4924. static bool isDeclExternC(const Decl *D) {
  4925. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  4926. return FD->isExternC();
  4927. if (const auto *VD = dyn_cast<VarDecl>(D))
  4928. return VD->isExternC();
  4929. llvm_unreachable("Unknown type of decl!");
  4930. }
  4931. NamedDecl *
  4932. Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  4933. TypeSourceInfo *TInfo, LookupResult &Previous,
  4934. MultiTemplateParamsArg TemplateParamLists,
  4935. bool &AddToScope) {
  4936. QualType R = TInfo->getType();
  4937. DeclarationName Name = GetNameForDeclarator(D).getName();
  4938. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  4939. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  4940. // dllimport globals without explicit storage class are treated as extern. We
  4941. // have to change the storage class this early to get the right DeclContext.
  4942. if (SC == SC_None && !DC->isRecord() &&
  4943. hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
  4944. !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
  4945. SC = SC_Extern;
  4946. DeclContext *OriginalDC = DC;
  4947. bool IsLocalExternDecl = SC == SC_Extern &&
  4948. adjustContextForLocalExternDecl(DC);
  4949. if (getLangOpts().OpenCL) {
  4950. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  4951. QualType NR = R;
  4952. while (NR->isPointerType()) {
  4953. if (NR->isFunctionPointerType()) {
  4954. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
  4955. D.setInvalidType();
  4956. break;
  4957. }
  4958. NR = NR->getPointeeType();
  4959. }
  4960. if (!getOpenCLOptions().cl_khr_fp16) {
  4961. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  4962. // half array type (unless the cl_khr_fp16 extension is enabled).
  4963. if (Context.getBaseElementType(R)->isHalfType()) {
  4964. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  4965. D.setInvalidType();
  4966. }
  4967. }
  4968. }
  4969. if (SCSpec == DeclSpec::SCS_mutable) {
  4970. // mutable can only appear on non-static class members, so it's always
  4971. // an error here
  4972. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  4973. D.setInvalidType();
  4974. SC = SC_None;
  4975. }
  4976. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  4977. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  4978. D.getDeclSpec().getStorageClassSpecLoc())) {
  4979. // In C++11, the 'register' storage class specifier is deprecated.
  4980. // Suppress the warning in system macros, it's used in macros in some
  4981. // popular C system headers, such as in glibc's htonl() macro.
  4982. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4983. diag::warn_deprecated_register)
  4984. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  4985. }
  4986. IdentifierInfo *II = Name.getAsIdentifierInfo();
  4987. if (!II) {
  4988. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
  4989. << Name;
  4990. return nullptr;
  4991. }
  4992. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  4993. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  4994. // C99 6.9p2: The storage-class specifiers auto and register shall not
  4995. // appear in the declaration specifiers in an external declaration.
  4996. // Global Register+Asm is a GNU extension we support.
  4997. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  4998. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  4999. D.setInvalidType();
  5000. }
  5001. }
  5002. if (getLangOpts().OpenCL) {
  5003. // Set up the special work-group-local storage class for variables in the
  5004. // OpenCL __local address space.
  5005. if (R.getAddressSpace() == LangAS::opencl_local) {
  5006. SC = SC_OpenCLWorkGroupLocal;
  5007. }
  5008. // OpenCL v1.2 s6.9.b p4:
  5009. // The sampler type cannot be used with the __local and __global address
  5010. // space qualifiers.
  5011. if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
  5012. R.getAddressSpace() == LangAS::opencl_global)) {
  5013. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5014. }
  5015. // OpenCL 1.2 spec, p6.9 r:
  5016. // The event type cannot be used to declare a program scope variable.
  5017. // The event type cannot be used with the __local, __constant and __global
  5018. // address space qualifiers.
  5019. if (R->isEventT()) {
  5020. if (S->getParent() == nullptr) {
  5021. Diag(D.getLocStart(), diag::err_event_t_global_var);
  5022. D.setInvalidType();
  5023. }
  5024. if (R.getAddressSpace()) {
  5025. Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
  5026. D.setInvalidType();
  5027. }
  5028. }
  5029. }
  5030. bool IsExplicitSpecialization = false;
  5031. bool IsVariableTemplateSpecialization = false;
  5032. bool IsPartialSpecialization = false;
  5033. bool IsVariableTemplate = false;
  5034. VarDecl *NewVD = nullptr;
  5035. VarTemplateDecl *NewTemplate = nullptr;
  5036. TemplateParameterList *TemplateParams = nullptr;
  5037. if (!getLangOpts().CPlusPlus) {
  5038. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5039. D.getIdentifierLoc(), II,
  5040. R, TInfo, SC);
  5041. if (D.isInvalidType())
  5042. NewVD->setInvalidDecl();
  5043. } else {
  5044. bool Invalid = false;
  5045. if (DC->isRecord() && !CurContext->isRecord()) {
  5046. // This is an out-of-line definition of a static data member.
  5047. switch (SC) {
  5048. case SC_None:
  5049. break;
  5050. case SC_Static:
  5051. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5052. diag::err_static_out_of_line)
  5053. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5054. break;
  5055. case SC_Auto:
  5056. case SC_Register:
  5057. case SC_Extern:
  5058. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5059. // to names of variables declared in a block or to function parameters.
  5060. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5061. // of class members
  5062. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5063. diag::err_storage_class_for_static_member)
  5064. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5065. break;
  5066. case SC_PrivateExtern:
  5067. llvm_unreachable("C storage class in c++!");
  5068. case SC_OpenCLWorkGroupLocal:
  5069. llvm_unreachable("OpenCL storage class in c++!");
  5070. }
  5071. }
  5072. if (SC == SC_Static && CurContext->isRecord()) {
  5073. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5074. if (RD->isLocalClass())
  5075. Diag(D.getIdentifierLoc(),
  5076. diag::err_static_data_member_not_allowed_in_local_class)
  5077. << Name << RD->getDeclName();
  5078. // C++98 [class.union]p1: If a union contains a static data member,
  5079. // the program is ill-formed. C++11 drops this restriction.
  5080. if (RD->isUnion())
  5081. Diag(D.getIdentifierLoc(),
  5082. getLangOpts().CPlusPlus11
  5083. ? diag::warn_cxx98_compat_static_data_member_in_union
  5084. : diag::ext_static_data_member_in_union) << Name;
  5085. // We conservatively disallow static data members in anonymous structs.
  5086. else if (!RD->getDeclName())
  5087. Diag(D.getIdentifierLoc(),
  5088. diag::err_static_data_member_not_allowed_in_anon_struct)
  5089. << Name << RD->isUnion();
  5090. }
  5091. }
  5092. // Match up the template parameter lists with the scope specifier, then
  5093. // determine whether we have a template or a template specialization.
  5094. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5095. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  5096. D.getCXXScopeSpec(),
  5097. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  5098. ? D.getName().TemplateId
  5099. : nullptr,
  5100. TemplateParamLists,
  5101. /*never a friend*/ false, IsExplicitSpecialization, Invalid);
  5102. if (TemplateParams) {
  5103. if (!TemplateParams->size() &&
  5104. D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  5105. // There is an extraneous 'template<>' for this variable. Complain
  5106. // about it, but allow the declaration of the variable.
  5107. Diag(TemplateParams->getTemplateLoc(),
  5108. diag::err_template_variable_noparams)
  5109. << II
  5110. << SourceRange(TemplateParams->getTemplateLoc(),
  5111. TemplateParams->getRAngleLoc());
  5112. TemplateParams = nullptr;
  5113. } else {
  5114. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  5115. // This is an explicit specialization or a partial specialization.
  5116. // FIXME: Check that we can declare a specialization here.
  5117. IsVariableTemplateSpecialization = true;
  5118. IsPartialSpecialization = TemplateParams->size() > 0;
  5119. } else { // if (TemplateParams->size() > 0)
  5120. // This is a template declaration.
  5121. IsVariableTemplate = true;
  5122. // Check that we can declare a template here.
  5123. if (CheckTemplateDeclScope(S, TemplateParams))
  5124. return nullptr;
  5125. // Only C++1y supports variable templates (N3651).
  5126. Diag(D.getIdentifierLoc(),
  5127. getLangOpts().CPlusPlus14
  5128. ? diag::warn_cxx11_compat_variable_template
  5129. : diag::ext_variable_template);
  5130. }
  5131. }
  5132. } else {
  5133. assert(
  5134. (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
  5135. "should have a 'template<>' for this decl");
  5136. }
  5137. if (IsVariableTemplateSpecialization) {
  5138. SourceLocation TemplateKWLoc =
  5139. TemplateParamLists.size() > 0
  5140. ? TemplateParamLists[0]->getTemplateLoc()
  5141. : SourceLocation();
  5142. DeclResult Res = ActOnVarTemplateSpecialization(
  5143. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5144. IsPartialSpecialization);
  5145. if (Res.isInvalid())
  5146. return nullptr;
  5147. NewVD = cast<VarDecl>(Res.get());
  5148. AddToScope = false;
  5149. } else
  5150. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5151. D.getIdentifierLoc(), II, R, TInfo, SC);
  5152. // If this is supposed to be a variable template, create it as such.
  5153. if (IsVariableTemplate) {
  5154. NewTemplate =
  5155. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5156. TemplateParams, NewVD);
  5157. NewVD->setDescribedVarTemplate(NewTemplate);
  5158. }
  5159. // If this decl has an auto type in need of deduction, make a note of the
  5160. // Decl so we can diagnose uses of it in its own initializer.
  5161. if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
  5162. ParsingInitForAutoVars.insert(NewVD);
  5163. if (D.isInvalidType() || Invalid) {
  5164. NewVD->setInvalidDecl();
  5165. if (NewTemplate)
  5166. NewTemplate->setInvalidDecl();
  5167. }
  5168. SetNestedNameSpecifier(NewVD, D);
  5169. // If we have any template parameter lists that don't directly belong to
  5170. // the variable (matching the scope specifier), store them.
  5171. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5172. if (TemplateParamLists.size() > VDTemplateParamLists)
  5173. NewVD->setTemplateParameterListsInfo(
  5174. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  5175. if (D.getDeclSpec().isConstexprSpecified())
  5176. NewVD->setConstexpr(true);
  5177. if (D.getDeclSpec().isConceptSpecified()) {
  5178. NewVD->setConcept(true);
  5179. // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
  5180. // be declared with the thread_local, inline, friend, or constexpr
  5181. // specifiers, [...]
  5182. if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
  5183. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5184. diag::err_concept_decl_invalid_specifiers)
  5185. << 0 << 0;
  5186. NewVD->setInvalidDecl(true);
  5187. }
  5188. if (D.getDeclSpec().isConstexprSpecified()) {
  5189. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  5190. diag::err_concept_decl_invalid_specifiers)
  5191. << 0 << 3;
  5192. NewVD->setInvalidDecl(true);
  5193. }
  5194. }
  5195. }
  5196. // Set the lexical context. If the declarator has a C++ scope specifier, the
  5197. // lexical context will be different from the semantic context.
  5198. NewVD->setLexicalDeclContext(CurContext);
  5199. if (NewTemplate)
  5200. NewTemplate->setLexicalDeclContext(CurContext);
  5201. if (IsLocalExternDecl)
  5202. NewVD->setLocalExternDecl();
  5203. bool EmitTLSUnsupportedError = false;
  5204. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  5205. // C++11 [dcl.stc]p4:
  5206. // When thread_local is applied to a variable of block scope the
  5207. // storage-class-specifier static is implied if it does not appear
  5208. // explicitly.
  5209. // Core issue: 'static' is not implied if the variable is declared
  5210. // 'extern'.
  5211. if (NewVD->hasLocalStorage() &&
  5212. (SCSpec != DeclSpec::SCS_unspecified ||
  5213. TSCS != DeclSpec::TSCS_thread_local ||
  5214. !DC->isFunctionOrMethod()))
  5215. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5216. diag::err_thread_non_global)
  5217. << DeclSpec::getSpecifierName(TSCS);
  5218. else if (!Context.getTargetInfo().isTLSSupported()) {
  5219. if (getLangOpts().CUDA) {
  5220. // Postpone error emission until we've collected attributes required to
  5221. // figure out whether it's a host or device variable and whether the
  5222. // error should be ignored.
  5223. EmitTLSUnsupportedError = true;
  5224. // We still need to mark the variable as TLS so it shows up in AST with
  5225. // proper storage class for other tools to use even if we're not going
  5226. // to emit any code for it.
  5227. NewVD->setTSCSpec(TSCS);
  5228. } else
  5229. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5230. diag::err_thread_unsupported);
  5231. } else
  5232. NewVD->setTSCSpec(TSCS);
  5233. }
  5234. // C99 6.7.4p3
  5235. // An inline definition of a function with external linkage shall
  5236. // not contain a definition of a modifiable object with static or
  5237. // thread storage duration...
  5238. // We only apply this when the function is required to be defined
  5239. // elsewhere, i.e. when the function is not 'extern inline'. Note
  5240. // that a local variable with thread storage duration still has to
  5241. // be marked 'static'. Also note that it's possible to get these
  5242. // semantics in C++ using __attribute__((gnu_inline)).
  5243. if (SC == SC_Static && S->getFnParent() != nullptr &&
  5244. !NewVD->getType().isConstQualified()) {
  5245. FunctionDecl *CurFD = getCurFunctionDecl();
  5246. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  5247. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5248. diag::warn_static_local_in_extern_inline);
  5249. MaybeSuggestAddingStaticToDecl(CurFD);
  5250. }
  5251. }
  5252. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5253. if (IsVariableTemplateSpecialization)
  5254. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5255. << (IsPartialSpecialization ? 1 : 0)
  5256. << FixItHint::CreateRemoval(
  5257. D.getDeclSpec().getModulePrivateSpecLoc());
  5258. else if (IsExplicitSpecialization)
  5259. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5260. << 2
  5261. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5262. else if (NewVD->hasLocalStorage())
  5263. Diag(NewVD->getLocation(), diag::err_module_private_local)
  5264. << 0 << NewVD->getDeclName()
  5265. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5266. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5267. else {
  5268. NewVD->setModulePrivate();
  5269. if (NewTemplate)
  5270. NewTemplate->setModulePrivate();
  5271. }
  5272. }
  5273. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5274. ProcessDeclAttributes(S, NewVD, D);
  5275. if (getLangOpts().CUDA) {
  5276. if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
  5277. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5278. diag::err_thread_unsupported);
  5279. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  5280. // storage [duration]."
  5281. if (SC == SC_None && S->getFnParent() != nullptr &&
  5282. (NewVD->hasAttr<CUDASharedAttr>() ||
  5283. NewVD->hasAttr<CUDAConstantAttr>())) {
  5284. NewVD->setStorageClass(SC_Static);
  5285. }
  5286. }
  5287. // Ensure that dllimport globals without explicit storage class are treated as
  5288. // extern. The storage class is set above using parsed attributes. Now we can
  5289. // check the VarDecl itself.
  5290. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  5291. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  5292. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  5293. // In auto-retain/release, infer strong retension for variables of
  5294. // retainable type.
  5295. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  5296. NewVD->setInvalidDecl();
  5297. // Handle GNU asm-label extension (encoded as an attribute).
  5298. if (Expr *E = (Expr*)D.getAsmLabel()) {
  5299. // The parser guarantees this is a string.
  5300. StringLiteral *SE = cast<StringLiteral>(E);
  5301. StringRef Label = SE->getString();
  5302. if (S->getFnParent() != nullptr) {
  5303. switch (SC) {
  5304. case SC_None:
  5305. case SC_Auto:
  5306. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  5307. break;
  5308. case SC_Register:
  5309. // Local Named register
  5310. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  5311. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  5312. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5313. break;
  5314. case SC_Static:
  5315. case SC_Extern:
  5316. case SC_PrivateExtern:
  5317. case SC_OpenCLWorkGroupLocal:
  5318. break;
  5319. }
  5320. } else if (SC == SC_Register) {
  5321. // Global Named register
  5322. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  5323. DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
  5324. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5325. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  5326. Diag(D.getLocStart(), diag::err_asm_bad_register_type);
  5327. NewVD->setInvalidDecl(true);
  5328. }
  5329. }
  5330. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  5331. Context, Label, 0));
  5332. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  5333. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  5334. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  5335. if (I != ExtnameUndeclaredIdentifiers.end()) {
  5336. if (isDeclExternC(NewVD)) {
  5337. NewVD->addAttr(I->second);
  5338. ExtnameUndeclaredIdentifiers.erase(I);
  5339. } else
  5340. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  5341. << /*Variable*/1 << NewVD;
  5342. }
  5343. }
  5344. // Diagnose shadowed variables before filtering for scope.
  5345. if (D.getCXXScopeSpec().isEmpty())
  5346. CheckShadow(S, NewVD, Previous);
  5347. // Don't consider existing declarations that are in a different
  5348. // scope and are out-of-semantic-context declarations (if the new
  5349. // declaration has linkage).
  5350. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  5351. D.getCXXScopeSpec().isNotEmpty() ||
  5352. IsExplicitSpecialization ||
  5353. IsVariableTemplateSpecialization);
  5354. // Check whether the previous declaration is in the same block scope. This
  5355. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  5356. if (getLangOpts().CPlusPlus &&
  5357. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  5358. NewVD->setPreviousDeclInSameBlockScope(
  5359. Previous.isSingleResult() && !Previous.isShadowed() &&
  5360. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  5361. if (!getLangOpts().CPlusPlus) {
  5362. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  5363. } else {
  5364. // If this is an explicit specialization of a static data member, check it.
  5365. if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
  5366. CheckMemberSpecialization(NewVD, Previous))
  5367. NewVD->setInvalidDecl();
  5368. // Merge the decl with the existing one if appropriate.
  5369. if (!Previous.empty()) {
  5370. if (Previous.isSingleResult() &&
  5371. isa<FieldDecl>(Previous.getFoundDecl()) &&
  5372. D.getCXXScopeSpec().isSet()) {
  5373. // The user tried to define a non-static data member
  5374. // out-of-line (C++ [dcl.meaning]p1).
  5375. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  5376. << D.getCXXScopeSpec().getRange();
  5377. Previous.clear();
  5378. NewVD->setInvalidDecl();
  5379. }
  5380. } else if (D.getCXXScopeSpec().isSet()) {
  5381. // No previous declaration in the qualifying scope.
  5382. Diag(D.getIdentifierLoc(), diag::err_no_member)
  5383. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  5384. << D.getCXXScopeSpec().getRange();
  5385. NewVD->setInvalidDecl();
  5386. }
  5387. if (!IsVariableTemplateSpecialization)
  5388. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  5389. if (NewTemplate) {
  5390. VarTemplateDecl *PrevVarTemplate =
  5391. NewVD->getPreviousDecl()
  5392. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  5393. : nullptr;
  5394. // Check the template parameter list of this declaration, possibly
  5395. // merging in the template parameter list from the previous variable
  5396. // template declaration.
  5397. if (CheckTemplateParameterList(
  5398. TemplateParams,
  5399. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  5400. : nullptr,
  5401. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  5402. DC->isDependentContext())
  5403. ? TPC_ClassTemplateMember
  5404. : TPC_VarTemplate))
  5405. NewVD->setInvalidDecl();
  5406. // If we are providing an explicit specialization of a static variable
  5407. // template, make a note of that.
  5408. if (PrevVarTemplate &&
  5409. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  5410. PrevVarTemplate->setMemberSpecialization();
  5411. }
  5412. }
  5413. ProcessPragmaWeak(S, NewVD);
  5414. // If this is the first declaration of an extern C variable, update
  5415. // the map of such variables.
  5416. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  5417. isIncompleteDeclExternC(*this, NewVD))
  5418. RegisterLocallyScopedExternCDecl(NewVD, S);
  5419. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  5420. Decl *ManglingContextDecl;
  5421. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  5422. NewVD->getDeclContext(), ManglingContextDecl)) {
  5423. Context.setManglingNumber(
  5424. NewVD, MCtx->getManglingNumber(
  5425. NewVD, getMSManglingNumber(getLangOpts(), S)));
  5426. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  5427. }
  5428. }
  5429. // Special handling of variable named 'main'.
  5430. if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
  5431. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  5432. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  5433. // C++ [basic.start.main]p3
  5434. // A program that declares a variable main at global scope is ill-formed.
  5435. if (getLangOpts().CPlusPlus)
  5436. Diag(D.getLocStart(), diag::err_main_global_variable);
  5437. // In C, and external-linkage variable named main results in undefined
  5438. // behavior.
  5439. else if (NewVD->hasExternalFormalLinkage())
  5440. Diag(D.getLocStart(), diag::warn_main_redefined);
  5441. }
  5442. if (D.isRedeclaration() && !Previous.empty()) {
  5443. checkDLLAttributeRedeclaration(
  5444. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
  5445. IsExplicitSpecialization);
  5446. }
  5447. if (NewTemplate) {
  5448. if (NewVD->isInvalidDecl())
  5449. NewTemplate->setInvalidDecl();
  5450. ActOnDocumentableDecl(NewTemplate);
  5451. return NewTemplate;
  5452. }
  5453. return NewVD;
  5454. }
  5455. /// \brief Diagnose variable or built-in function shadowing. Implements
  5456. /// -Wshadow.
  5457. ///
  5458. /// This method is called whenever a VarDecl is added to a "useful"
  5459. /// scope.
  5460. ///
  5461. /// \param S the scope in which the shadowing name is being declared
  5462. /// \param R the lookup of the name
  5463. ///
  5464. void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
  5465. // Return if warning is ignored.
  5466. if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
  5467. return;
  5468. // Don't diagnose declarations at file scope.
  5469. if (D->hasGlobalStorage())
  5470. return;
  5471. DeclContext *NewDC = D->getDeclContext();
  5472. // Only diagnose if we're shadowing an unambiguous field or variable.
  5473. if (R.getResultKind() != LookupResult::Found)
  5474. return;
  5475. NamedDecl* ShadowedDecl = R.getFoundDecl();
  5476. if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
  5477. return;
  5478. // Fields are not shadowed by variables in C++ static methods.
  5479. if (isa<FieldDecl>(ShadowedDecl))
  5480. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  5481. if (MD->isStatic())
  5482. return;
  5483. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  5484. if (shadowedVar->isExternC()) {
  5485. // For shadowing external vars, make sure that we point to the global
  5486. // declaration, not a locally scoped extern declaration.
  5487. for (auto I : shadowedVar->redecls())
  5488. if (I->isFileVarDecl()) {
  5489. ShadowedDecl = I;
  5490. break;
  5491. }
  5492. }
  5493. DeclContext *OldDC = ShadowedDecl->getDeclContext();
  5494. // Only warn about certain kinds of shadowing for class members.
  5495. if (NewDC && NewDC->isRecord()) {
  5496. // In particular, don't warn about shadowing non-class members.
  5497. if (!OldDC->isRecord())
  5498. return;
  5499. // TODO: should we warn about static data members shadowing
  5500. // static data members from base classes?
  5501. // TODO: don't diagnose for inaccessible shadowed members.
  5502. // This is hard to do perfectly because we might friend the
  5503. // shadowing context, but that's just a false negative.
  5504. }
  5505. // Determine what kind of declaration we're shadowing.
  5506. unsigned Kind;
  5507. if (isa<RecordDecl>(OldDC)) {
  5508. if (isa<FieldDecl>(ShadowedDecl))
  5509. Kind = 3; // field
  5510. else
  5511. Kind = 2; // static data member
  5512. } else if (OldDC->isFileContext())
  5513. Kind = 1; // global
  5514. else
  5515. Kind = 0; // local
  5516. DeclarationName Name = R.getLookupName();
  5517. // Emit warning and note.
  5518. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  5519. return;
  5520. Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
  5521. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  5522. }
  5523. /// \brief Check -Wshadow without the advantage of a previous lookup.
  5524. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  5525. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  5526. return;
  5527. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  5528. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  5529. LookupName(R, S);
  5530. CheckShadow(S, D, R);
  5531. }
  5532. /// Check for conflict between this global or extern "C" declaration and
  5533. /// previous global or extern "C" declarations. This is only used in C++.
  5534. template<typename T>
  5535. static bool checkGlobalOrExternCConflict(
  5536. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  5537. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  5538. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  5539. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  5540. // The common case: this global doesn't conflict with any extern "C"
  5541. // declaration.
  5542. return false;
  5543. }
  5544. if (Prev) {
  5545. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  5546. // Both the old and new declarations have C language linkage. This is a
  5547. // redeclaration.
  5548. Previous.clear();
  5549. Previous.addDecl(Prev);
  5550. return true;
  5551. }
  5552. // This is a global, non-extern "C" declaration, and there is a previous
  5553. // non-global extern "C" declaration. Diagnose if this is a variable
  5554. // declaration.
  5555. if (!isa<VarDecl>(ND))
  5556. return false;
  5557. } else {
  5558. // The declaration is extern "C". Check for any declaration in the
  5559. // translation unit which might conflict.
  5560. if (IsGlobal) {
  5561. // We have already performed the lookup into the translation unit.
  5562. IsGlobal = false;
  5563. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  5564. I != E; ++I) {
  5565. if (isa<VarDecl>(*I)) {
  5566. Prev = *I;
  5567. break;
  5568. }
  5569. }
  5570. } else {
  5571. DeclContext::lookup_result R =
  5572. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  5573. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  5574. I != E; ++I) {
  5575. if (isa<VarDecl>(*I)) {
  5576. Prev = *I;
  5577. break;
  5578. }
  5579. // FIXME: If we have any other entity with this name in global scope,
  5580. // the declaration is ill-formed, but that is a defect: it breaks the
  5581. // 'stat' hack, for instance. Only variables can have mangled name
  5582. // clashes with extern "C" declarations, so only they deserve a
  5583. // diagnostic.
  5584. }
  5585. }
  5586. if (!Prev)
  5587. return false;
  5588. }
  5589. // Use the first declaration's location to ensure we point at something which
  5590. // is lexically inside an extern "C" linkage-spec.
  5591. assert(Prev && "should have found a previous declaration to diagnose");
  5592. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  5593. Prev = FD->getFirstDecl();
  5594. else
  5595. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  5596. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  5597. << IsGlobal << ND;
  5598. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  5599. << IsGlobal;
  5600. return false;
  5601. }
  5602. /// Apply special rules for handling extern "C" declarations. Returns \c true
  5603. /// if we have found that this is a redeclaration of some prior entity.
  5604. ///
  5605. /// Per C++ [dcl.link]p6:
  5606. /// Two declarations [for a function or variable] with C language linkage
  5607. /// with the same name that appear in different scopes refer to the same
  5608. /// [entity]. An entity with C language linkage shall not be declared with
  5609. /// the same name as an entity in global scope.
  5610. template<typename T>
  5611. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  5612. LookupResult &Previous) {
  5613. if (!S.getLangOpts().CPlusPlus) {
  5614. // In C, when declaring a global variable, look for a corresponding 'extern'
  5615. // variable declared in function scope. We don't need this in C++, because
  5616. // we find local extern decls in the surrounding file-scope DeclContext.
  5617. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5618. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  5619. Previous.clear();
  5620. Previous.addDecl(Prev);
  5621. return true;
  5622. }
  5623. }
  5624. return false;
  5625. }
  5626. // A declaration in the translation unit can conflict with an extern "C"
  5627. // declaration.
  5628. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  5629. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  5630. // An extern "C" declaration can conflict with a declaration in the
  5631. // translation unit or can be a redeclaration of an extern "C" declaration
  5632. // in another scope.
  5633. if (isIncompleteDeclExternC(S,ND))
  5634. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  5635. // Neither global nor extern "C": nothing to do.
  5636. return false;
  5637. }
  5638. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  5639. // If the decl is already known invalid, don't check it.
  5640. if (NewVD->isInvalidDecl())
  5641. return;
  5642. TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
  5643. QualType T = TInfo->getType();
  5644. // Defer checking an 'auto' type until its initializer is attached.
  5645. if (T->isUndeducedType())
  5646. return;
  5647. if (NewVD->hasAttrs())
  5648. CheckAlignasUnderalignment(NewVD);
  5649. if (T->isObjCObjectType()) {
  5650. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  5651. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  5652. T = Context.getObjCObjectPointerType(T);
  5653. NewVD->setType(T);
  5654. }
  5655. // Emit an error if an address space was applied to decl with local storage.
  5656. // This includes arrays of objects with address space qualifiers, but not
  5657. // automatic variables that point to other address spaces.
  5658. // ISO/IEC TR 18037 S5.1.2
  5659. if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
  5660. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
  5661. NewVD->setInvalidDecl();
  5662. return;
  5663. }
  5664. // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
  5665. // __constant address space.
  5666. if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
  5667. && T.getAddressSpace() != LangAS::opencl_constant
  5668. && !T->isSamplerT()){
  5669. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
  5670. NewVD->setInvalidDecl();
  5671. return;
  5672. }
  5673. // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
  5674. // scope.
  5675. if ((getLangOpts().OpenCLVersion >= 120)
  5676. && NewVD->isStaticLocal()) {
  5677. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  5678. NewVD->setInvalidDecl();
  5679. return;
  5680. }
  5681. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  5682. && !NewVD->hasAttr<BlocksAttr>()) {
  5683. if (getLangOpts().getGC() != LangOptions::NonGC)
  5684. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  5685. else {
  5686. assert(!getLangOpts().ObjCAutoRefCount);
  5687. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  5688. }
  5689. }
  5690. bool isVM = T->isVariablyModifiedType();
  5691. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  5692. NewVD->hasAttr<BlocksAttr>())
  5693. getCurFunction()->setHasBranchProtectedScope();
  5694. if ((isVM && NewVD->hasLinkage()) ||
  5695. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  5696. bool SizeIsNegative;
  5697. llvm::APSInt Oversized;
  5698. TypeSourceInfo *FixedTInfo =
  5699. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5700. SizeIsNegative, Oversized);
  5701. if (!FixedTInfo && T->isVariableArrayType()) {
  5702. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  5703. // FIXME: This won't give the correct result for
  5704. // int a[10][n];
  5705. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  5706. if (NewVD->isFileVarDecl())
  5707. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  5708. << SizeRange;
  5709. else if (NewVD->isStaticLocal())
  5710. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  5711. << SizeRange;
  5712. else
  5713. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  5714. << SizeRange;
  5715. NewVD->setInvalidDecl();
  5716. return;
  5717. }
  5718. if (!FixedTInfo) {
  5719. if (NewVD->isFileVarDecl())
  5720. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  5721. else
  5722. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  5723. NewVD->setInvalidDecl();
  5724. return;
  5725. }
  5726. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  5727. NewVD->setType(FixedTInfo->getType());
  5728. NewVD->setTypeSourceInfo(FixedTInfo);
  5729. }
  5730. if (T->isVoidType()) {
  5731. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  5732. // of objects and functions.
  5733. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  5734. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  5735. << T;
  5736. NewVD->setInvalidDecl();
  5737. return;
  5738. }
  5739. }
  5740. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  5741. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  5742. NewVD->setInvalidDecl();
  5743. return;
  5744. }
  5745. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  5746. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  5747. NewVD->setInvalidDecl();
  5748. return;
  5749. }
  5750. if (NewVD->isConstexpr() && !T->isDependentType() &&
  5751. RequireLiteralType(NewVD->getLocation(), T,
  5752. diag::err_constexpr_var_non_literal)) {
  5753. NewVD->setInvalidDecl();
  5754. return;
  5755. }
  5756. }
  5757. /// \brief Perform semantic checking on a newly-created variable
  5758. /// declaration.
  5759. ///
  5760. /// This routine performs all of the type-checking required for a
  5761. /// variable declaration once it has been built. It is used both to
  5762. /// check variables after they have been parsed and their declarators
  5763. /// have been translated into a declaration, and to check variables
  5764. /// that have been instantiated from a template.
  5765. ///
  5766. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  5767. ///
  5768. /// Returns true if the variable declaration is a redeclaration.
  5769. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  5770. CheckVariableDeclarationType(NewVD);
  5771. // If the decl is already known invalid, don't check it.
  5772. if (NewVD->isInvalidDecl())
  5773. return false;
  5774. // If we did not find anything by this name, look for a non-visible
  5775. // extern "C" declaration with the same name.
  5776. if (Previous.empty() &&
  5777. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  5778. Previous.setShadowed();
  5779. if (!Previous.empty()) {
  5780. MergeVarDecl(NewVD, Previous);
  5781. return true;
  5782. }
  5783. return false;
  5784. }
  5785. namespace {
  5786. struct FindOverriddenMethod {
  5787. Sema *S;
  5788. CXXMethodDecl *Method;
  5789. /// Member lookup function that determines whether a given C++
  5790. /// method overrides a method in a base class, to be used with
  5791. /// CXXRecordDecl::lookupInBases().
  5792. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  5793. RecordDecl *BaseRecord =
  5794. Specifier->getType()->getAs<RecordType>()->getDecl();
  5795. DeclarationName Name = Method->getDeclName();
  5796. // FIXME: Do we care about other names here too?
  5797. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  5798. // We really want to find the base class destructor here.
  5799. QualType T = S->Context.getTypeDeclType(BaseRecord);
  5800. CanQualType CT = S->Context.getCanonicalType(T);
  5801. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  5802. }
  5803. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  5804. Path.Decls = Path.Decls.slice(1)) {
  5805. NamedDecl *D = Path.Decls.front();
  5806. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  5807. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  5808. return true;
  5809. }
  5810. }
  5811. return false;
  5812. }
  5813. };
  5814. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  5815. } // end anonymous namespace
  5816. /// \brief Report an error regarding overriding, along with any relevant
  5817. /// overriden methods.
  5818. ///
  5819. /// \param DiagID the primary error to report.
  5820. /// \param MD the overriding method.
  5821. /// \param OEK which overrides to include as notes.
  5822. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  5823. OverrideErrorKind OEK = OEK_All) {
  5824. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  5825. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  5826. E = MD->end_overridden_methods();
  5827. I != E; ++I) {
  5828. // This check (& the OEK parameter) could be replaced by a predicate, but
  5829. // without lambdas that would be overkill. This is still nicer than writing
  5830. // out the diag loop 3 times.
  5831. if ((OEK == OEK_All) ||
  5832. (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
  5833. (OEK == OEK_Deleted && (*I)->isDeleted()))
  5834. S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
  5835. }
  5836. }
  5837. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  5838. /// and if so, check that it's a valid override and remember it.
  5839. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  5840. // Look for methods in base classes that this method might override.
  5841. CXXBasePaths Paths;
  5842. FindOverriddenMethod FOM;
  5843. FOM.Method = MD;
  5844. FOM.S = this;
  5845. bool hasDeletedOverridenMethods = false;
  5846. bool hasNonDeletedOverridenMethods = false;
  5847. bool AddedAny = false;
  5848. if (DC->lookupInBases(FOM, Paths)) {
  5849. for (auto *I : Paths.found_decls()) {
  5850. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  5851. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  5852. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  5853. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  5854. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  5855. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  5856. hasDeletedOverridenMethods |= OldMD->isDeleted();
  5857. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  5858. AddedAny = true;
  5859. }
  5860. }
  5861. }
  5862. }
  5863. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  5864. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  5865. }
  5866. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  5867. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  5868. }
  5869. return AddedAny;
  5870. }
  5871. namespace {
  5872. // Struct for holding all of the extra arguments needed by
  5873. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  5874. struct ActOnFDArgs {
  5875. Scope *S;
  5876. Declarator &D;
  5877. MultiTemplateParamsArg TemplateParamLists;
  5878. bool AddToScope;
  5879. };
  5880. }
  5881. namespace {
  5882. // Callback to only accept typo corrections that have a non-zero edit distance.
  5883. // Also only accept corrections that have the same parent decl.
  5884. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  5885. public:
  5886. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  5887. CXXRecordDecl *Parent)
  5888. : Context(Context), OriginalFD(TypoFD),
  5889. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  5890. bool ValidateCandidate(const TypoCorrection &candidate) override {
  5891. if (candidate.getEditDistance() == 0)
  5892. return false;
  5893. SmallVector<unsigned, 1> MismatchedParams;
  5894. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  5895. CDeclEnd = candidate.end();
  5896. CDecl != CDeclEnd; ++CDecl) {
  5897. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  5898. if (FD && !FD->hasBody() &&
  5899. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  5900. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  5901. CXXRecordDecl *Parent = MD->getParent();
  5902. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  5903. return true;
  5904. } else if (!ExpectedParent) {
  5905. return true;
  5906. }
  5907. }
  5908. }
  5909. return false;
  5910. }
  5911. private:
  5912. ASTContext &Context;
  5913. FunctionDecl *OriginalFD;
  5914. CXXRecordDecl *ExpectedParent;
  5915. };
  5916. }
  5917. /// \brief Generate diagnostics for an invalid function redeclaration.
  5918. ///
  5919. /// This routine handles generating the diagnostic messages for an invalid
  5920. /// function redeclaration, including finding possible similar declarations
  5921. /// or performing typo correction if there are no previous declarations with
  5922. /// the same name.
  5923. ///
  5924. /// Returns a NamedDecl iff typo correction was performed and substituting in
  5925. /// the new declaration name does not cause new errors.
  5926. static NamedDecl *DiagnoseInvalidRedeclaration(
  5927. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  5928. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  5929. DeclarationName Name = NewFD->getDeclName();
  5930. DeclContext *NewDC = NewFD->getDeclContext();
  5931. SmallVector<unsigned, 1> MismatchedParams;
  5932. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  5933. TypoCorrection Correction;
  5934. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  5935. unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
  5936. : diag::err_member_decl_does_not_match;
  5937. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  5938. IsLocalFriend ? Sema::LookupLocalFriendName
  5939. : Sema::LookupOrdinaryName,
  5940. Sema::ForRedeclaration);
  5941. NewFD->setInvalidDecl();
  5942. if (IsLocalFriend)
  5943. SemaRef.LookupName(Prev, S);
  5944. else
  5945. SemaRef.LookupQualifiedName(Prev, NewDC);
  5946. assert(!Prev.isAmbiguous() &&
  5947. "Cannot have an ambiguity in previous-declaration lookup");
  5948. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  5949. if (!Prev.empty()) {
  5950. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  5951. Func != FuncEnd; ++Func) {
  5952. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  5953. if (FD &&
  5954. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  5955. // Add 1 to the index so that 0 can mean the mismatch didn't
  5956. // involve a parameter
  5957. unsigned ParamNum =
  5958. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  5959. NearMatches.push_back(std::make_pair(FD, ParamNum));
  5960. }
  5961. }
  5962. // If the qualified name lookup yielded nothing, try typo correction
  5963. } else if ((Correction = SemaRef.CorrectTypo(
  5964. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  5965. &ExtraArgs.D.getCXXScopeSpec(),
  5966. llvm::make_unique<DifferentNameValidatorCCC>(
  5967. SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
  5968. Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
  5969. // Set up everything for the call to ActOnFunctionDeclarator
  5970. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  5971. ExtraArgs.D.getIdentifierLoc());
  5972. Previous.clear();
  5973. Previous.setLookupName(Correction.getCorrection());
  5974. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  5975. CDeclEnd = Correction.end();
  5976. CDecl != CDeclEnd; ++CDecl) {
  5977. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  5978. if (FD && !FD->hasBody() &&
  5979. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  5980. Previous.addDecl(FD);
  5981. }
  5982. }
  5983. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  5984. NamedDecl *Result;
  5985. // Retry building the function declaration with the new previous
  5986. // declarations, and with errors suppressed.
  5987. {
  5988. // Trap errors.
  5989. Sema::SFINAETrap Trap(SemaRef);
  5990. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  5991. // pieces need to verify the typo-corrected C++ declaration and hopefully
  5992. // eliminate the need for the parameter pack ExtraArgs.
  5993. Result = SemaRef.ActOnFunctionDeclarator(
  5994. ExtraArgs.S, ExtraArgs.D,
  5995. Correction.getCorrectionDecl()->getDeclContext(),
  5996. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  5997. ExtraArgs.AddToScope);
  5998. if (Trap.hasErrorOccurred())
  5999. Result = nullptr;
  6000. }
  6001. if (Result) {
  6002. // Determine which correction we picked.
  6003. Decl *Canonical = Result->getCanonicalDecl();
  6004. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6005. I != E; ++I)
  6006. if ((*I)->getCanonicalDecl() == Canonical)
  6007. Correction.setCorrectionDecl(*I);
  6008. SemaRef.diagnoseTypo(
  6009. Correction,
  6010. SemaRef.PDiag(IsLocalFriend
  6011. ? diag::err_no_matching_local_friend_suggest
  6012. : diag::err_member_decl_does_not_match_suggest)
  6013. << Name << NewDC << IsDefinition);
  6014. return Result;
  6015. }
  6016. // Pretend the typo correction never occurred
  6017. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  6018. ExtraArgs.D.getIdentifierLoc());
  6019. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  6020. Previous.clear();
  6021. Previous.setLookupName(Name);
  6022. }
  6023. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  6024. << Name << NewDC << IsDefinition << NewFD->getLocation();
  6025. bool NewFDisConst = false;
  6026. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  6027. NewFDisConst = NewMD->isConst();
  6028. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  6029. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  6030. NearMatch != NearMatchEnd; ++NearMatch) {
  6031. FunctionDecl *FD = NearMatch->first;
  6032. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6033. bool FDisConst = MD && MD->isConst();
  6034. bool IsMember = MD || !IsLocalFriend;
  6035. // FIXME: These notes are poorly worded for the local friend case.
  6036. if (unsigned Idx = NearMatch->second) {
  6037. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  6038. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  6039. if (Loc.isInvalid()) Loc = FD->getLocation();
  6040. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  6041. : diag::note_local_decl_close_param_match)
  6042. << Idx << FDParam->getType()
  6043. << NewFD->getParamDecl(Idx - 1)->getType();
  6044. } else if (FDisConst != NewFDisConst) {
  6045. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  6046. << NewFDisConst << FD->getSourceRange().getEnd();
  6047. } else
  6048. SemaRef.Diag(FD->getLocation(),
  6049. IsMember ? diag::note_member_def_close_match
  6050. : diag::note_local_decl_close_match);
  6051. }
  6052. return nullptr;
  6053. }
  6054. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  6055. switch (D.getDeclSpec().getStorageClassSpec()) {
  6056. default: llvm_unreachable("Unknown storage class!");
  6057. case DeclSpec::SCS_auto:
  6058. case DeclSpec::SCS_register:
  6059. case DeclSpec::SCS_mutable:
  6060. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6061. diag::err_typecheck_sclass_func);
  6062. D.setInvalidType();
  6063. break;
  6064. case DeclSpec::SCS_unspecified: break;
  6065. case DeclSpec::SCS_extern:
  6066. if (D.getDeclSpec().isExternInLinkageSpec())
  6067. return SC_None;
  6068. return SC_Extern;
  6069. case DeclSpec::SCS_static: {
  6070. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  6071. // C99 6.7.1p5:
  6072. // The declaration of an identifier for a function that has
  6073. // block scope shall have no explicit storage-class specifier
  6074. // other than extern
  6075. // See also (C++ [dcl.stc]p4).
  6076. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6077. diag::err_static_block_func);
  6078. break;
  6079. } else
  6080. return SC_Static;
  6081. }
  6082. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  6083. }
  6084. // No explicit storage class has already been returned
  6085. return SC_None;
  6086. }
  6087. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  6088. DeclContext *DC, QualType &R,
  6089. TypeSourceInfo *TInfo,
  6090. StorageClass SC,
  6091. bool &IsVirtualOkay) {
  6092. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  6093. DeclarationName Name = NameInfo.getName();
  6094. FunctionDecl *NewFD = nullptr;
  6095. bool isInline = D.getDeclSpec().isInlineSpecified();
  6096. if (!SemaRef.getLangOpts().CPlusPlus) {
  6097. // Determine whether the function was written with a
  6098. // prototype. This true when:
  6099. // - there is a prototype in the declarator, or
  6100. // - the type R of the function is some kind of typedef or other reference
  6101. // to a type name (which eventually refers to a function type).
  6102. bool HasPrototype =
  6103. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  6104. (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
  6105. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  6106. D.getLocStart(), NameInfo, R,
  6107. TInfo, SC, isInline,
  6108. HasPrototype, false);
  6109. if (D.isInvalidType())
  6110. NewFD->setInvalidDecl();
  6111. return NewFD;
  6112. }
  6113. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  6114. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  6115. // Check that the return type is not an abstract class type.
  6116. // For record types, this is done by the AbstractClassUsageDiagnoser once
  6117. // the class has been completely parsed.
  6118. if (!DC->isRecord() &&
  6119. SemaRef.RequireNonAbstractType(
  6120. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  6121. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  6122. D.setInvalidType();
  6123. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  6124. // This is a C++ constructor declaration.
  6125. assert(DC->isRecord() &&
  6126. "Constructors can only be declared in a member context");
  6127. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  6128. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  6129. D.getLocStart(), NameInfo,
  6130. R, TInfo, isExplicit, isInline,
  6131. /*isImplicitlyDeclared=*/false,
  6132. isConstexpr);
  6133. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6134. // This is a C++ destructor declaration.
  6135. if (DC->isRecord()) {
  6136. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  6137. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  6138. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  6139. SemaRef.Context, Record,
  6140. D.getLocStart(),
  6141. NameInfo, R, TInfo, isInline,
  6142. /*isImplicitlyDeclared=*/false);
  6143. // If the class is complete, then we now create the implicit exception
  6144. // specification. If the class is incomplete or dependent, we can't do
  6145. // it yet.
  6146. if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
  6147. Record->getDefinition() && !Record->isBeingDefined() &&
  6148. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  6149. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  6150. }
  6151. IsVirtualOkay = true;
  6152. return NewDD;
  6153. } else {
  6154. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  6155. D.setInvalidType();
  6156. // Create a FunctionDecl to satisfy the function definition parsing
  6157. // code path.
  6158. return FunctionDecl::Create(SemaRef.Context, DC,
  6159. D.getLocStart(),
  6160. D.getIdentifierLoc(), Name, R, TInfo,
  6161. SC, isInline,
  6162. /*hasPrototype=*/true, isConstexpr);
  6163. }
  6164. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  6165. if (!DC->isRecord()) {
  6166. SemaRef.Diag(D.getIdentifierLoc(),
  6167. diag::err_conv_function_not_member);
  6168. return nullptr;
  6169. }
  6170. SemaRef.CheckConversionDeclarator(D, R, SC);
  6171. IsVirtualOkay = true;
  6172. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  6173. D.getLocStart(), NameInfo,
  6174. R, TInfo, isInline, isExplicit,
  6175. isConstexpr, SourceLocation());
  6176. } else if (DC->isRecord()) {
  6177. // If the name of the function is the same as the name of the record,
  6178. // then this must be an invalid constructor that has a return type.
  6179. // (The parser checks for a return type and makes the declarator a
  6180. // constructor if it has no return type).
  6181. if (Name.getAsIdentifierInfo() &&
  6182. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  6183. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  6184. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  6185. << SourceRange(D.getIdentifierLoc());
  6186. return nullptr;
  6187. }
  6188. // This is a C++ method declaration.
  6189. CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
  6190. cast<CXXRecordDecl>(DC),
  6191. D.getLocStart(), NameInfo, R,
  6192. TInfo, SC, isInline,
  6193. isConstexpr, SourceLocation());
  6194. IsVirtualOkay = !Ret->isStatic();
  6195. return Ret;
  6196. } else {
  6197. bool isFriend =
  6198. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  6199. if (!isFriend && SemaRef.CurContext->isRecord())
  6200. return nullptr;
  6201. // Determine whether the function was written with a
  6202. // prototype. This true when:
  6203. // - we're in C++ (where every function has a prototype),
  6204. return FunctionDecl::Create(SemaRef.Context, DC,
  6205. D.getLocStart(),
  6206. NameInfo, R, TInfo, SC, isInline,
  6207. true/*HasPrototype*/, isConstexpr);
  6208. }
  6209. }
  6210. enum OpenCLParamType {
  6211. ValidKernelParam,
  6212. PtrPtrKernelParam,
  6213. PtrKernelParam,
  6214. PrivatePtrKernelParam,
  6215. InvalidKernelParam,
  6216. RecordKernelParam
  6217. };
  6218. static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
  6219. if (PT->isPointerType()) {
  6220. QualType PointeeType = PT->getPointeeType();
  6221. if (PointeeType->isPointerType())
  6222. return PtrPtrKernelParam;
  6223. return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
  6224. : PtrKernelParam;
  6225. }
  6226. // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
  6227. // be used as builtin types.
  6228. if (PT->isImageType())
  6229. return PtrKernelParam;
  6230. if (PT->isBooleanType())
  6231. return InvalidKernelParam;
  6232. if (PT->isEventT())
  6233. return InvalidKernelParam;
  6234. if (PT->isHalfType())
  6235. return InvalidKernelParam;
  6236. if (PT->isRecordType())
  6237. return RecordKernelParam;
  6238. return ValidKernelParam;
  6239. }
  6240. static void checkIsValidOpenCLKernelParameter(
  6241. Sema &S,
  6242. Declarator &D,
  6243. ParmVarDecl *Param,
  6244. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  6245. QualType PT = Param->getType();
  6246. // Cache the valid types we encounter to avoid rechecking structs that are
  6247. // used again
  6248. if (ValidTypes.count(PT.getTypePtr()))
  6249. return;
  6250. switch (getOpenCLKernelParameterType(PT)) {
  6251. case PtrPtrKernelParam:
  6252. // OpenCL v1.2 s6.9.a:
  6253. // A kernel function argument cannot be declared as a
  6254. // pointer to a pointer type.
  6255. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  6256. D.setInvalidType();
  6257. return;
  6258. case PrivatePtrKernelParam:
  6259. // OpenCL v1.2 s6.9.a:
  6260. // A kernel function argument cannot be declared as a
  6261. // pointer to the private address space.
  6262. S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
  6263. D.setInvalidType();
  6264. return;
  6265. // OpenCL v1.2 s6.9.k:
  6266. // Arguments to kernel functions in a program cannot be declared with the
  6267. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  6268. // uintptr_t or a struct and/or union that contain fields declared to be
  6269. // one of these built-in scalar types.
  6270. case InvalidKernelParam:
  6271. // OpenCL v1.2 s6.8 n:
  6272. // A kernel function argument cannot be declared
  6273. // of event_t type.
  6274. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  6275. D.setInvalidType();
  6276. return;
  6277. case PtrKernelParam:
  6278. case ValidKernelParam:
  6279. ValidTypes.insert(PT.getTypePtr());
  6280. return;
  6281. case RecordKernelParam:
  6282. break;
  6283. }
  6284. // Track nested structs we will inspect
  6285. SmallVector<const Decl *, 4> VisitStack;
  6286. // Track where we are in the nested structs. Items will migrate from
  6287. // VisitStack to HistoryStack as we do the DFS for bad field.
  6288. SmallVector<const FieldDecl *, 4> HistoryStack;
  6289. HistoryStack.push_back(nullptr);
  6290. const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
  6291. VisitStack.push_back(PD);
  6292. assert(VisitStack.back() && "First decl null?");
  6293. do {
  6294. const Decl *Next = VisitStack.pop_back_val();
  6295. if (!Next) {
  6296. assert(!HistoryStack.empty());
  6297. // Found a marker, we have gone up a level
  6298. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  6299. ValidTypes.insert(Hist->getType().getTypePtr());
  6300. continue;
  6301. }
  6302. // Adds everything except the original parameter declaration (which is not a
  6303. // field itself) to the history stack.
  6304. const RecordDecl *RD;
  6305. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  6306. HistoryStack.push_back(Field);
  6307. RD = Field->getType()->castAs<RecordType>()->getDecl();
  6308. } else {
  6309. RD = cast<RecordDecl>(Next);
  6310. }
  6311. // Add a null marker so we know when we've gone back up a level
  6312. VisitStack.push_back(nullptr);
  6313. for (const auto *FD : RD->fields()) {
  6314. QualType QT = FD->getType();
  6315. if (ValidTypes.count(QT.getTypePtr()))
  6316. continue;
  6317. OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
  6318. if (ParamType == ValidKernelParam)
  6319. continue;
  6320. if (ParamType == RecordKernelParam) {
  6321. VisitStack.push_back(FD);
  6322. continue;
  6323. }
  6324. // OpenCL v1.2 s6.9.p:
  6325. // Arguments to kernel functions that are declared to be a struct or union
  6326. // do not allow OpenCL objects to be passed as elements of the struct or
  6327. // union.
  6328. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  6329. ParamType == PrivatePtrKernelParam) {
  6330. S.Diag(Param->getLocation(),
  6331. diag::err_record_with_pointers_kernel_param)
  6332. << PT->isUnionType()
  6333. << PT;
  6334. } else {
  6335. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  6336. }
  6337. S.Diag(PD->getLocation(), diag::note_within_field_of_type)
  6338. << PD->getDeclName();
  6339. // We have an error, now let's go back up through history and show where
  6340. // the offending field came from
  6341. for (ArrayRef<const FieldDecl *>::const_iterator
  6342. I = HistoryStack.begin() + 1,
  6343. E = HistoryStack.end();
  6344. I != E; ++I) {
  6345. const FieldDecl *OuterField = *I;
  6346. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  6347. << OuterField->getType();
  6348. }
  6349. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  6350. << QT->isPointerType()
  6351. << QT;
  6352. D.setInvalidType();
  6353. return;
  6354. }
  6355. } while (!VisitStack.empty());
  6356. }
  6357. NamedDecl*
  6358. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  6359. TypeSourceInfo *TInfo, LookupResult &Previous,
  6360. MultiTemplateParamsArg TemplateParamLists,
  6361. bool &AddToScope) {
  6362. QualType R = TInfo->getType();
  6363. assert(R.getTypePtr()->isFunctionType());
  6364. // TODO: consider using NameInfo for diagnostic.
  6365. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  6366. DeclarationName Name = NameInfo.getName();
  6367. StorageClass SC = getFunctionStorageClass(*this, D);
  6368. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  6369. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6370. diag::err_invalid_thread)
  6371. << DeclSpec::getSpecifierName(TSCS);
  6372. if (D.isFirstDeclarationOfMember())
  6373. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  6374. D.getIdentifierLoc());
  6375. bool isFriend = false;
  6376. FunctionTemplateDecl *FunctionTemplate = nullptr;
  6377. bool isExplicitSpecialization = false;
  6378. bool isFunctionTemplateSpecialization = false;
  6379. bool isDependentClassScopeExplicitSpecialization = false;
  6380. bool HasExplicitTemplateArgs = false;
  6381. TemplateArgumentListInfo TemplateArgs;
  6382. bool isVirtualOkay = false;
  6383. DeclContext *OriginalDC = DC;
  6384. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  6385. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  6386. isVirtualOkay);
  6387. if (!NewFD) return nullptr;
  6388. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  6389. NewFD->setTopLevelDeclInObjCContainer();
  6390. // Set the lexical context. If this is a function-scope declaration, or has a
  6391. // C++ scope specifier, or is the object of a friend declaration, the lexical
  6392. // context will be different from the semantic context.
  6393. NewFD->setLexicalDeclContext(CurContext);
  6394. if (IsLocalExternDecl)
  6395. NewFD->setLocalExternDecl();
  6396. if (getLangOpts().CPlusPlus) {
  6397. bool isInline = D.getDeclSpec().isInlineSpecified();
  6398. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  6399. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  6400. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  6401. bool isConcept = D.getDeclSpec().isConceptSpecified();
  6402. isFriend = D.getDeclSpec().isFriendSpecified();
  6403. if (isFriend && !isInline && D.isFunctionDefinition()) {
  6404. // C++ [class.friend]p5
  6405. // A function can be defined in a friend declaration of a
  6406. // class . . . . Such a function is implicitly inline.
  6407. NewFD->setImplicitlyInline();
  6408. }
  6409. // If this is a method defined in an __interface, and is not a constructor
  6410. // or an overloaded operator, then set the pure flag (isVirtual will already
  6411. // return true).
  6412. if (const CXXRecordDecl *Parent =
  6413. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  6414. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  6415. NewFD->setPure(true);
  6416. // C++ [class.union]p2
  6417. // A union can have member functions, but not virtual functions.
  6418. if (isVirtual && Parent->isUnion())
  6419. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  6420. }
  6421. SetNestedNameSpecifier(NewFD, D);
  6422. isExplicitSpecialization = false;
  6423. isFunctionTemplateSpecialization = false;
  6424. if (D.isInvalidType())
  6425. NewFD->setInvalidDecl();
  6426. // Match up the template parameter lists with the scope specifier, then
  6427. // determine whether we have a template or a template specialization.
  6428. bool Invalid = false;
  6429. if (TemplateParameterList *TemplateParams =
  6430. MatchTemplateParametersToScopeSpecifier(
  6431. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  6432. D.getCXXScopeSpec(),
  6433. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  6434. ? D.getName().TemplateId
  6435. : nullptr,
  6436. TemplateParamLists, isFriend, isExplicitSpecialization,
  6437. Invalid)) {
  6438. if (TemplateParams->size() > 0) {
  6439. // This is a function template
  6440. // Check that we can declare a template here.
  6441. if (CheckTemplateDeclScope(S, TemplateParams))
  6442. NewFD->setInvalidDecl();
  6443. // A destructor cannot be a template.
  6444. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6445. Diag(NewFD->getLocation(), diag::err_destructor_template);
  6446. NewFD->setInvalidDecl();
  6447. }
  6448. // If we're adding a template to a dependent context, we may need to
  6449. // rebuilding some of the types used within the template parameter list,
  6450. // now that we know what the current instantiation is.
  6451. if (DC->isDependentContext()) {
  6452. ContextRAII SavedContext(*this, DC);
  6453. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  6454. Invalid = true;
  6455. }
  6456. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  6457. NewFD->getLocation(),
  6458. Name, TemplateParams,
  6459. NewFD);
  6460. FunctionTemplate->setLexicalDeclContext(CurContext);
  6461. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  6462. // For source fidelity, store the other template param lists.
  6463. if (TemplateParamLists.size() > 1) {
  6464. NewFD->setTemplateParameterListsInfo(Context,
  6465. TemplateParamLists.drop_back(1));
  6466. }
  6467. } else {
  6468. // This is a function template specialization.
  6469. isFunctionTemplateSpecialization = true;
  6470. // For source fidelity, store all the template param lists.
  6471. if (TemplateParamLists.size() > 0)
  6472. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  6473. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  6474. if (isFriend) {
  6475. // We want to remove the "template<>", found here.
  6476. SourceRange RemoveRange = TemplateParams->getSourceRange();
  6477. // If we remove the template<> and the name is not a
  6478. // template-id, we're actually silently creating a problem:
  6479. // the friend declaration will refer to an untemplated decl,
  6480. // and clearly the user wants a template specialization. So
  6481. // we need to insert '<>' after the name.
  6482. SourceLocation InsertLoc;
  6483. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  6484. InsertLoc = D.getName().getSourceRange().getEnd();
  6485. InsertLoc = getLocForEndOfToken(InsertLoc);
  6486. }
  6487. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  6488. << Name << RemoveRange
  6489. << FixItHint::CreateRemoval(RemoveRange)
  6490. << FixItHint::CreateInsertion(InsertLoc, "<>");
  6491. }
  6492. }
  6493. }
  6494. else {
  6495. // All template param lists were matched against the scope specifier:
  6496. // this is NOT (an explicit specialization of) a template.
  6497. if (TemplateParamLists.size() > 0)
  6498. // For source fidelity, store all the template param lists.
  6499. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  6500. }
  6501. if (Invalid) {
  6502. NewFD->setInvalidDecl();
  6503. if (FunctionTemplate)
  6504. FunctionTemplate->setInvalidDecl();
  6505. }
  6506. // C++ [dcl.fct.spec]p5:
  6507. // The virtual specifier shall only be used in declarations of
  6508. // nonstatic class member functions that appear within a
  6509. // member-specification of a class declaration; see 10.3.
  6510. //
  6511. if (isVirtual && !NewFD->isInvalidDecl()) {
  6512. if (!isVirtualOkay) {
  6513. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  6514. diag::err_virtual_non_function);
  6515. } else if (!CurContext->isRecord()) {
  6516. // 'virtual' was specified outside of the class.
  6517. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  6518. diag::err_virtual_out_of_class)
  6519. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  6520. } else if (NewFD->getDescribedFunctionTemplate()) {
  6521. // C++ [temp.mem]p3:
  6522. // A member function template shall not be virtual.
  6523. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  6524. diag::err_virtual_member_function_template)
  6525. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  6526. } else {
  6527. // Okay: Add virtual to the method.
  6528. NewFD->setVirtualAsWritten(true);
  6529. }
  6530. if (getLangOpts().CPlusPlus14 &&
  6531. NewFD->getReturnType()->isUndeducedType())
  6532. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  6533. }
  6534. if (getLangOpts().CPlusPlus14 &&
  6535. (NewFD->isDependentContext() ||
  6536. (isFriend && CurContext->isDependentContext())) &&
  6537. NewFD->getReturnType()->isUndeducedType()) {
  6538. // If the function template is referenced directly (for instance, as a
  6539. // member of the current instantiation), pretend it has a dependent type.
  6540. // This is not really justified by the standard, but is the only sane
  6541. // thing to do.
  6542. // FIXME: For a friend function, we have not marked the function as being
  6543. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  6544. const FunctionProtoType *FPT =
  6545. NewFD->getType()->castAs<FunctionProtoType>();
  6546. QualType Result =
  6547. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  6548. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  6549. FPT->getExtProtoInfo()));
  6550. }
  6551. // C++ [dcl.fct.spec]p3:
  6552. // The inline specifier shall not appear on a block scope function
  6553. // declaration.
  6554. if (isInline && !NewFD->isInvalidDecl()) {
  6555. if (CurContext->isFunctionOrMethod()) {
  6556. // 'inline' is not allowed on block scope function declaration.
  6557. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6558. diag::err_inline_declaration_block_scope) << Name
  6559. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  6560. }
  6561. }
  6562. // C++ [dcl.fct.spec]p6:
  6563. // The explicit specifier shall be used only in the declaration of a
  6564. // constructor or conversion function within its class definition;
  6565. // see 12.3.1 and 12.3.2.
  6566. if (isExplicit && !NewFD->isInvalidDecl()) {
  6567. if (!CurContext->isRecord()) {
  6568. // 'explicit' was specified outside of the class.
  6569. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  6570. diag::err_explicit_out_of_class)
  6571. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  6572. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  6573. !isa<CXXConversionDecl>(NewFD)) {
  6574. // 'explicit' was specified on a function that wasn't a constructor
  6575. // or conversion function.
  6576. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  6577. diag::err_explicit_non_ctor_or_conv_function)
  6578. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  6579. }
  6580. }
  6581. if (isConstexpr) {
  6582. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  6583. // are implicitly inline.
  6584. NewFD->setImplicitlyInline();
  6585. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  6586. // be either constructors or to return a literal type. Therefore,
  6587. // destructors cannot be declared constexpr.
  6588. if (isa<CXXDestructorDecl>(NewFD))
  6589. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  6590. }
  6591. if (isConcept) {
  6592. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  6593. // applied only to the definition of a function template [...]
  6594. if (!D.isFunctionDefinition()) {
  6595. Diag(D.getDeclSpec().getConceptSpecLoc(),
  6596. diag::err_function_concept_not_defined);
  6597. NewFD->setInvalidDecl();
  6598. }
  6599. // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
  6600. // have no exception-specification and is treated as if it were specified
  6601. // with noexcept(true) (15.4). [...]
  6602. if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
  6603. if (FPT->hasExceptionSpec()) {
  6604. SourceRange Range;
  6605. if (D.isFunctionDeclarator())
  6606. Range = D.getFunctionTypeInfo().getExceptionSpecRange();
  6607. Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
  6608. << FixItHint::CreateRemoval(Range);
  6609. NewFD->setInvalidDecl();
  6610. } else {
  6611. Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
  6612. }
  6613. }
  6614. // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
  6615. // implicity defined to be a constexpr declaration (implicitly inline)
  6616. NewFD->setImplicitlyInline();
  6617. // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
  6618. // be declared with the thread_local, inline, friend, or constexpr
  6619. // specifiers, [...]
  6620. if (isInline) {
  6621. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6622. diag::err_concept_decl_invalid_specifiers)
  6623. << 1 << 1;
  6624. NewFD->setInvalidDecl(true);
  6625. }
  6626. if (isFriend) {
  6627. Diag(D.getDeclSpec().getFriendSpecLoc(),
  6628. diag::err_concept_decl_invalid_specifiers)
  6629. << 1 << 2;
  6630. NewFD->setInvalidDecl(true);
  6631. }
  6632. if (isConstexpr) {
  6633. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  6634. diag::err_concept_decl_invalid_specifiers)
  6635. << 1 << 3;
  6636. NewFD->setInvalidDecl(true);
  6637. }
  6638. }
  6639. // If __module_private__ was specified, mark the function accordingly.
  6640. if (D.getDeclSpec().isModulePrivateSpecified()) {
  6641. if (isFunctionTemplateSpecialization) {
  6642. SourceLocation ModulePrivateLoc
  6643. = D.getDeclSpec().getModulePrivateSpecLoc();
  6644. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  6645. << 0
  6646. << FixItHint::CreateRemoval(ModulePrivateLoc);
  6647. } else {
  6648. NewFD->setModulePrivate();
  6649. if (FunctionTemplate)
  6650. FunctionTemplate->setModulePrivate();
  6651. }
  6652. }
  6653. if (isFriend) {
  6654. if (FunctionTemplate) {
  6655. FunctionTemplate->setObjectOfFriendDecl();
  6656. FunctionTemplate->setAccess(AS_public);
  6657. }
  6658. NewFD->setObjectOfFriendDecl();
  6659. NewFD->setAccess(AS_public);
  6660. }
  6661. // If a function is defined as defaulted or deleted, mark it as such now.
  6662. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  6663. // definition kind to FDK_Definition.
  6664. switch (D.getFunctionDefinitionKind()) {
  6665. case FDK_Declaration:
  6666. case FDK_Definition:
  6667. break;
  6668. case FDK_Defaulted:
  6669. NewFD->setDefaulted();
  6670. break;
  6671. case FDK_Deleted:
  6672. NewFD->setDeletedAsWritten();
  6673. break;
  6674. }
  6675. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  6676. D.isFunctionDefinition()) {
  6677. // C++ [class.mfct]p2:
  6678. // A member function may be defined (8.4) in its class definition, in
  6679. // which case it is an inline member function (7.1.2)
  6680. NewFD->setImplicitlyInline();
  6681. }
  6682. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  6683. !CurContext->isRecord()) {
  6684. // C++ [class.static]p1:
  6685. // A data or function member of a class may be declared static
  6686. // in a class definition, in which case it is a static member of
  6687. // the class.
  6688. // Complain about the 'static' specifier if it's on an out-of-line
  6689. // member function definition.
  6690. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6691. diag::err_static_out_of_line)
  6692. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  6693. }
  6694. // C++11 [except.spec]p15:
  6695. // A deallocation function with no exception-specification is treated
  6696. // as if it were specified with noexcept(true).
  6697. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  6698. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  6699. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  6700. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  6701. NewFD->setType(Context.getFunctionType(
  6702. FPT->getReturnType(), FPT->getParamTypes(),
  6703. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  6704. }
  6705. // Filter out previous declarations that don't match the scope.
  6706. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  6707. D.getCXXScopeSpec().isNotEmpty() ||
  6708. isExplicitSpecialization ||
  6709. isFunctionTemplateSpecialization);
  6710. // Handle GNU asm-label extension (encoded as an attribute).
  6711. if (Expr *E = (Expr*) D.getAsmLabel()) {
  6712. // The parser guarantees this is a string.
  6713. StringLiteral *SE = cast<StringLiteral>(E);
  6714. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  6715. SE->getString(), 0));
  6716. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  6717. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6718. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  6719. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6720. if (isDeclExternC(NewFD)) {
  6721. NewFD->addAttr(I->second);
  6722. ExtnameUndeclaredIdentifiers.erase(I);
  6723. } else
  6724. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  6725. << /*Variable*/0 << NewFD;
  6726. }
  6727. }
  6728. // Copy the parameter declarations from the declarator D to the function
  6729. // declaration NewFD, if they are available. First scavenge them into Params.
  6730. SmallVector<ParmVarDecl*, 16> Params;
  6731. if (D.isFunctionDeclarator()) {
  6732. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  6733. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  6734. // function that takes no arguments, not a function that takes a
  6735. // single void argument.
  6736. // We let through "const void" here because Sema::GetTypeForDeclarator
  6737. // already checks for that case.
  6738. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  6739. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  6740. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  6741. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  6742. Param->setDeclContext(NewFD);
  6743. Params.push_back(Param);
  6744. if (Param->isInvalidDecl())
  6745. NewFD->setInvalidDecl();
  6746. }
  6747. }
  6748. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  6749. // When we're declaring a function with a typedef, typeof, etc as in the
  6750. // following example, we'll need to synthesize (unnamed)
  6751. // parameters for use in the declaration.
  6752. //
  6753. // @code
  6754. // typedef void fn(int);
  6755. // fn f;
  6756. // @endcode
  6757. // Synthesize a parameter for each argument type.
  6758. for (const auto &AI : FT->param_types()) {
  6759. ParmVarDecl *Param =
  6760. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  6761. Param->setScopeInfo(0, Params.size());
  6762. Params.push_back(Param);
  6763. }
  6764. } else {
  6765. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  6766. "Should not need args for typedef of non-prototype fn");
  6767. }
  6768. // Finally, we know we have the right number of parameters, install them.
  6769. NewFD->setParams(Params);
  6770. // Find all anonymous symbols defined during the declaration of this function
  6771. // and add to NewFD. This lets us track decls such 'enum Y' in:
  6772. //
  6773. // void f(enum Y {AA} x) {}
  6774. //
  6775. // which would otherwise incorrectly end up in the translation unit scope.
  6776. NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
  6777. DeclsInPrototypeScope.clear();
  6778. if (D.getDeclSpec().isNoreturnSpecified())
  6779. NewFD->addAttr(
  6780. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  6781. Context, 0));
  6782. // Functions returning a variably modified type violate C99 6.7.5.2p2
  6783. // because all functions have linkage.
  6784. if (!NewFD->isInvalidDecl() &&
  6785. NewFD->getReturnType()->isVariablyModifiedType()) {
  6786. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  6787. NewFD->setInvalidDecl();
  6788. }
  6789. // Apply an implicit SectionAttr if #pragma code_seg is active.
  6790. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  6791. !NewFD->hasAttr<SectionAttr>()) {
  6792. NewFD->addAttr(
  6793. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  6794. CodeSegStack.CurrentValue->getString(),
  6795. CodeSegStack.CurrentPragmaLocation));
  6796. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  6797. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  6798. ASTContext::PSF_Read,
  6799. NewFD))
  6800. NewFD->dropAttr<SectionAttr>();
  6801. }
  6802. // Handle attributes.
  6803. ProcessDeclAttributes(S, NewFD, D);
  6804. if (getLangOpts().OpenCL) {
  6805. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  6806. // type declaration will generate a compilation error.
  6807. unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
  6808. if (AddressSpace == LangAS::opencl_local ||
  6809. AddressSpace == LangAS::opencl_global ||
  6810. AddressSpace == LangAS::opencl_constant) {
  6811. Diag(NewFD->getLocation(),
  6812. diag::err_opencl_return_value_with_address_space);
  6813. NewFD->setInvalidDecl();
  6814. }
  6815. }
  6816. if (!getLangOpts().CPlusPlus) {
  6817. // Perform semantic checking on the function declaration.
  6818. bool isExplicitSpecialization=false;
  6819. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  6820. CheckMain(NewFD, D.getDeclSpec());
  6821. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  6822. CheckMSVCRTEntryPoint(NewFD);
  6823. if (!NewFD->isInvalidDecl())
  6824. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  6825. isExplicitSpecialization));
  6826. else if (!Previous.empty())
  6827. // Recover gracefully from an invalid redeclaration.
  6828. D.setRedeclaration(true);
  6829. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  6830. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  6831. "previous declaration set still overloaded");
  6832. // Diagnose no-prototype function declarations with calling conventions that
  6833. // don't support variadic calls. Only do this in C and do it after merging
  6834. // possibly prototyped redeclarations.
  6835. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  6836. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  6837. CallingConv CC = FT->getExtInfo().getCC();
  6838. if (!supportsVariadicCall(CC)) {
  6839. // Windows system headers sometimes accidentally use stdcall without
  6840. // (void) parameters, so we relax this to a warning.
  6841. int DiagID =
  6842. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  6843. Diag(NewFD->getLocation(), DiagID)
  6844. << FunctionType::getNameForCallConv(CC);
  6845. }
  6846. }
  6847. } else {
  6848. // C++11 [replacement.functions]p3:
  6849. // The program's definitions shall not be specified as inline.
  6850. //
  6851. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  6852. //
  6853. // Suppress the diagnostic if the function is __attribute__((used)), since
  6854. // that forces an external definition to be emitted.
  6855. if (D.getDeclSpec().isInlineSpecified() &&
  6856. NewFD->isReplaceableGlobalAllocationFunction() &&
  6857. !NewFD->hasAttr<UsedAttr>())
  6858. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6859. diag::ext_operator_new_delete_declared_inline)
  6860. << NewFD->getDeclName();
  6861. // If the declarator is a template-id, translate the parser's template
  6862. // argument list into our AST format.
  6863. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  6864. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  6865. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  6866. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  6867. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  6868. TemplateId->NumArgs);
  6869. translateTemplateArguments(TemplateArgsPtr,
  6870. TemplateArgs);
  6871. HasExplicitTemplateArgs = true;
  6872. if (NewFD->isInvalidDecl()) {
  6873. HasExplicitTemplateArgs = false;
  6874. } else if (FunctionTemplate) {
  6875. // Function template with explicit template arguments.
  6876. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  6877. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  6878. HasExplicitTemplateArgs = false;
  6879. } else {
  6880. assert((isFunctionTemplateSpecialization ||
  6881. D.getDeclSpec().isFriendSpecified()) &&
  6882. "should have a 'template<>' for this decl");
  6883. // "friend void foo<>(int);" is an implicit specialization decl.
  6884. isFunctionTemplateSpecialization = true;
  6885. }
  6886. } else if (isFriend && isFunctionTemplateSpecialization) {
  6887. // This combination is only possible in a recovery case; the user
  6888. // wrote something like:
  6889. // template <> friend void foo(int);
  6890. // which we're recovering from as if the user had written:
  6891. // friend void foo<>(int);
  6892. // Go ahead and fake up a template id.
  6893. HasExplicitTemplateArgs = true;
  6894. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  6895. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  6896. }
  6897. // If it's a friend (and only if it's a friend), it's possible
  6898. // that either the specialized function type or the specialized
  6899. // template is dependent, and therefore matching will fail. In
  6900. // this case, don't check the specialization yet.
  6901. bool InstantiationDependent = false;
  6902. if (isFunctionTemplateSpecialization && isFriend &&
  6903. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  6904. TemplateSpecializationType::anyDependentTemplateArguments(
  6905. TemplateArgs.getArgumentArray(), TemplateArgs.size(),
  6906. InstantiationDependent))) {
  6907. assert(HasExplicitTemplateArgs &&
  6908. "friend function specialization without template args");
  6909. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  6910. Previous))
  6911. NewFD->setInvalidDecl();
  6912. } else if (isFunctionTemplateSpecialization) {
  6913. if (CurContext->isDependentContext() && CurContext->isRecord()
  6914. && !isFriend) {
  6915. isDependentClassScopeExplicitSpecialization = true;
  6916. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  6917. diag::ext_function_specialization_in_class :
  6918. diag::err_function_specialization_in_class)
  6919. << NewFD->getDeclName();
  6920. } else if (CheckFunctionTemplateSpecialization(NewFD,
  6921. (HasExplicitTemplateArgs ? &TemplateArgs
  6922. : nullptr),
  6923. Previous))
  6924. NewFD->setInvalidDecl();
  6925. // C++ [dcl.stc]p1:
  6926. // A storage-class-specifier shall not be specified in an explicit
  6927. // specialization (14.7.3)
  6928. FunctionTemplateSpecializationInfo *Info =
  6929. NewFD->getTemplateSpecializationInfo();
  6930. if (Info && SC != SC_None) {
  6931. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  6932. Diag(NewFD->getLocation(),
  6933. diag::err_explicit_specialization_inconsistent_storage_class)
  6934. << SC
  6935. << FixItHint::CreateRemoval(
  6936. D.getDeclSpec().getStorageClassSpecLoc());
  6937. else
  6938. Diag(NewFD->getLocation(),
  6939. diag::ext_explicit_specialization_storage_class)
  6940. << FixItHint::CreateRemoval(
  6941. D.getDeclSpec().getStorageClassSpecLoc());
  6942. }
  6943. } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
  6944. if (CheckMemberSpecialization(NewFD, Previous))
  6945. NewFD->setInvalidDecl();
  6946. }
  6947. // Perform semantic checking on the function declaration.
  6948. if (!isDependentClassScopeExplicitSpecialization) {
  6949. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  6950. CheckMain(NewFD, D.getDeclSpec());
  6951. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  6952. CheckMSVCRTEntryPoint(NewFD);
  6953. if (!NewFD->isInvalidDecl())
  6954. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  6955. isExplicitSpecialization));
  6956. else if (!Previous.empty())
  6957. // Recover gracefully from an invalid redeclaration.
  6958. D.setRedeclaration(true);
  6959. }
  6960. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  6961. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  6962. "previous declaration set still overloaded");
  6963. NamedDecl *PrincipalDecl = (FunctionTemplate
  6964. ? cast<NamedDecl>(FunctionTemplate)
  6965. : NewFD);
  6966. if (isFriend && D.isRedeclaration()) {
  6967. AccessSpecifier Access = AS_public;
  6968. if (!NewFD->isInvalidDecl())
  6969. Access = NewFD->getPreviousDecl()->getAccess();
  6970. NewFD->setAccess(Access);
  6971. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  6972. }
  6973. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  6974. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  6975. PrincipalDecl->setNonMemberOperator();
  6976. // If we have a function template, check the template parameter
  6977. // list. This will check and merge default template arguments.
  6978. if (FunctionTemplate) {
  6979. FunctionTemplateDecl *PrevTemplate =
  6980. FunctionTemplate->getPreviousDecl();
  6981. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  6982. PrevTemplate ? PrevTemplate->getTemplateParameters()
  6983. : nullptr,
  6984. D.getDeclSpec().isFriendSpecified()
  6985. ? (D.isFunctionDefinition()
  6986. ? TPC_FriendFunctionTemplateDefinition
  6987. : TPC_FriendFunctionTemplate)
  6988. : (D.getCXXScopeSpec().isSet() &&
  6989. DC && DC->isRecord() &&
  6990. DC->isDependentContext())
  6991. ? TPC_ClassTemplateMember
  6992. : TPC_FunctionTemplate);
  6993. }
  6994. if (NewFD->isInvalidDecl()) {
  6995. // Ignore all the rest of this.
  6996. } else if (!D.isRedeclaration()) {
  6997. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  6998. AddToScope };
  6999. // Fake up an access specifier if it's supposed to be a class member.
  7000. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  7001. NewFD->setAccess(AS_public);
  7002. // Qualified decls generally require a previous declaration.
  7003. if (D.getCXXScopeSpec().isSet()) {
  7004. // ...with the major exception of templated-scope or
  7005. // dependent-scope friend declarations.
  7006. // TODO: we currently also suppress this check in dependent
  7007. // contexts because (1) the parameter depth will be off when
  7008. // matching friend templates and (2) we might actually be
  7009. // selecting a friend based on a dependent factor. But there
  7010. // are situations where these conditions don't apply and we
  7011. // can actually do this check immediately.
  7012. if (isFriend &&
  7013. (TemplateParamLists.size() ||
  7014. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  7015. CurContext->isDependentContext())) {
  7016. // ignore these
  7017. } else {
  7018. // The user tried to provide an out-of-line definition for a
  7019. // function that is a member of a class or namespace, but there
  7020. // was no such member function declared (C++ [class.mfct]p2,
  7021. // C++ [namespace.memdef]p2). For example:
  7022. //
  7023. // class X {
  7024. // void f() const;
  7025. // };
  7026. //
  7027. // void X::f() { } // ill-formed
  7028. //
  7029. // Complain about this problem, and attempt to suggest close
  7030. // matches (e.g., those that differ only in cv-qualifiers and
  7031. // whether the parameter types are references).
  7032. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7033. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  7034. AddToScope = ExtraArgs.AddToScope;
  7035. return Result;
  7036. }
  7037. }
  7038. // Unqualified local friend declarations are required to resolve
  7039. // to something.
  7040. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  7041. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7042. *this, Previous, NewFD, ExtraArgs, true, S)) {
  7043. AddToScope = ExtraArgs.AddToScope;
  7044. return Result;
  7045. }
  7046. }
  7047. } else if (!D.isFunctionDefinition() &&
  7048. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  7049. !isFriend && !isFunctionTemplateSpecialization &&
  7050. !isExplicitSpecialization) {
  7051. // An out-of-line member function declaration must also be a
  7052. // definition (C++ [class.mfct]p2).
  7053. // Note that this is not the case for explicit specializations of
  7054. // function templates or member functions of class templates, per
  7055. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  7056. // extension for compatibility with old SWIG code which likes to
  7057. // generate them.
  7058. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  7059. << D.getCXXScopeSpec().getRange();
  7060. }
  7061. }
  7062. ProcessPragmaWeak(S, NewFD);
  7063. checkAttributesAfterMerging(*this, *NewFD);
  7064. AddKnownFunctionAttributes(NewFD);
  7065. if (NewFD->hasAttr<OverloadableAttr>() &&
  7066. !NewFD->getType()->getAs<FunctionProtoType>()) {
  7067. Diag(NewFD->getLocation(),
  7068. diag::err_attribute_overloadable_no_prototype)
  7069. << NewFD;
  7070. // Turn this into a variadic function with no parameters.
  7071. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  7072. FunctionProtoType::ExtProtoInfo EPI(
  7073. Context.getDefaultCallingConvention(true, false));
  7074. EPI.Variadic = true;
  7075. EPI.ExtInfo = FT->getExtInfo();
  7076. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  7077. NewFD->setType(R);
  7078. }
  7079. // If there's a #pragma GCC visibility in scope, and this isn't a class
  7080. // member, set the visibility of this function.
  7081. if (!DC->isRecord() && NewFD->isExternallyVisible())
  7082. AddPushedVisibilityAttribute(NewFD);
  7083. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  7084. // marking the function.
  7085. AddCFAuditedAttribute(NewFD);
  7086. // If this is a function definition, check if we have to apply optnone due to
  7087. // a pragma.
  7088. if(D.isFunctionDefinition())
  7089. AddRangeBasedOptnone(NewFD);
  7090. // If this is the first declaration of an extern C variable, update
  7091. // the map of such variables.
  7092. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  7093. isIncompleteDeclExternC(*this, NewFD))
  7094. RegisterLocallyScopedExternCDecl(NewFD, S);
  7095. // Set this FunctionDecl's range up to the right paren.
  7096. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  7097. if (D.isRedeclaration() && !Previous.empty()) {
  7098. checkDLLAttributeRedeclaration(
  7099. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
  7100. isExplicitSpecialization || isFunctionTemplateSpecialization);
  7101. }
  7102. if (getLangOpts().CPlusPlus) {
  7103. if (FunctionTemplate) {
  7104. if (NewFD->isInvalidDecl())
  7105. FunctionTemplate->setInvalidDecl();
  7106. return FunctionTemplate;
  7107. }
  7108. }
  7109. if (NewFD->hasAttr<OpenCLKernelAttr>()) {
  7110. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  7111. if ((getLangOpts().OpenCLVersion >= 120)
  7112. && (SC == SC_Static)) {
  7113. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  7114. D.setInvalidType();
  7115. }
  7116. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  7117. if (!NewFD->getReturnType()->isVoidType()) {
  7118. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  7119. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  7120. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  7121. : FixItHint());
  7122. D.setInvalidType();
  7123. }
  7124. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  7125. for (auto Param : NewFD->params())
  7126. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  7127. }
  7128. MarkUnusedFileScopedDecl(NewFD);
  7129. if (getLangOpts().CUDA)
  7130. if (IdentifierInfo *II = NewFD->getIdentifier())
  7131. if (!NewFD->isInvalidDecl() &&
  7132. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  7133. if (II->isStr("cudaConfigureCall")) {
  7134. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  7135. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  7136. Context.setcudaConfigureCallDecl(NewFD);
  7137. }
  7138. }
  7139. // Here we have an function template explicit specialization at class scope.
  7140. // The actually specialization will be postponed to template instatiation
  7141. // time via the ClassScopeFunctionSpecializationDecl node.
  7142. if (isDependentClassScopeExplicitSpecialization) {
  7143. ClassScopeFunctionSpecializationDecl *NewSpec =
  7144. ClassScopeFunctionSpecializationDecl::Create(
  7145. Context, CurContext, SourceLocation(),
  7146. cast<CXXMethodDecl>(NewFD),
  7147. HasExplicitTemplateArgs, TemplateArgs);
  7148. CurContext->addDecl(NewSpec);
  7149. AddToScope = false;
  7150. }
  7151. return NewFD;
  7152. }
  7153. /// \brief Perform semantic checking of a new function declaration.
  7154. ///
  7155. /// Performs semantic analysis of the new function declaration
  7156. /// NewFD. This routine performs all semantic checking that does not
  7157. /// require the actual declarator involved in the declaration, and is
  7158. /// used both for the declaration of functions as they are parsed
  7159. /// (called via ActOnDeclarator) and for the declaration of functions
  7160. /// that have been instantiated via C++ template instantiation (called
  7161. /// via InstantiateDecl).
  7162. ///
  7163. /// \param IsExplicitSpecialization whether this new function declaration is
  7164. /// an explicit specialization of the previous declaration.
  7165. ///
  7166. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  7167. ///
  7168. /// \returns true if the function declaration is a redeclaration.
  7169. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  7170. LookupResult &Previous,
  7171. bool IsExplicitSpecialization) {
  7172. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  7173. "Variably modified return types are not handled here");
  7174. // Determine whether the type of this function should be merged with
  7175. // a previous visible declaration. This never happens for functions in C++,
  7176. // and always happens in C if the previous declaration was visible.
  7177. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  7178. !Previous.isShadowed();
  7179. bool Redeclaration = false;
  7180. NamedDecl *OldDecl = nullptr;
  7181. // Merge or overload the declaration with an existing declaration of
  7182. // the same name, if appropriate.
  7183. if (!Previous.empty()) {
  7184. // Determine whether NewFD is an overload of PrevDecl or
  7185. // a declaration that requires merging. If it's an overload,
  7186. // there's no more work to do here; we'll just add the new
  7187. // function to the scope.
  7188. if (!AllowOverloadingOfFunction(Previous, Context)) {
  7189. NamedDecl *Candidate = Previous.getFoundDecl();
  7190. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  7191. Redeclaration = true;
  7192. OldDecl = Candidate;
  7193. }
  7194. } else {
  7195. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  7196. /*NewIsUsingDecl*/ false)) {
  7197. case Ovl_Match:
  7198. Redeclaration = true;
  7199. break;
  7200. case Ovl_NonFunction:
  7201. Redeclaration = true;
  7202. break;
  7203. case Ovl_Overload:
  7204. Redeclaration = false;
  7205. break;
  7206. }
  7207. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  7208. // If a function name is overloadable in C, then every function
  7209. // with that name must be marked "overloadable".
  7210. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  7211. << Redeclaration << NewFD;
  7212. NamedDecl *OverloadedDecl = nullptr;
  7213. if (Redeclaration)
  7214. OverloadedDecl = OldDecl;
  7215. else if (!Previous.empty())
  7216. OverloadedDecl = Previous.getRepresentativeDecl();
  7217. if (OverloadedDecl)
  7218. Diag(OverloadedDecl->getLocation(),
  7219. diag::note_attribute_overloadable_prev_overload);
  7220. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  7221. }
  7222. }
  7223. }
  7224. // Check for a previous extern "C" declaration with this name.
  7225. if (!Redeclaration &&
  7226. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  7227. if (!Previous.empty()) {
  7228. // This is an extern "C" declaration with the same name as a previous
  7229. // declaration, and thus redeclares that entity...
  7230. Redeclaration = true;
  7231. OldDecl = Previous.getFoundDecl();
  7232. MergeTypeWithPrevious = false;
  7233. // ... except in the presence of __attribute__((overloadable)).
  7234. if (OldDecl->hasAttr<OverloadableAttr>()) {
  7235. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  7236. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  7237. << Redeclaration << NewFD;
  7238. Diag(Previous.getFoundDecl()->getLocation(),
  7239. diag::note_attribute_overloadable_prev_overload);
  7240. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  7241. }
  7242. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  7243. Redeclaration = false;
  7244. OldDecl = nullptr;
  7245. }
  7246. }
  7247. }
  7248. }
  7249. // C++11 [dcl.constexpr]p8:
  7250. // A constexpr specifier for a non-static member function that is not
  7251. // a constructor declares that member function to be const.
  7252. //
  7253. // This needs to be delayed until we know whether this is an out-of-line
  7254. // definition of a static member function.
  7255. //
  7256. // This rule is not present in C++1y, so we produce a backwards
  7257. // compatibility warning whenever it happens in C++11.
  7258. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  7259. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  7260. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  7261. (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
  7262. CXXMethodDecl *OldMD = nullptr;
  7263. if (OldDecl)
  7264. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  7265. if (!OldMD || !OldMD->isStatic()) {
  7266. const FunctionProtoType *FPT =
  7267. MD->getType()->castAs<FunctionProtoType>();
  7268. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  7269. EPI.TypeQuals |= Qualifiers::Const;
  7270. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  7271. FPT->getParamTypes(), EPI));
  7272. // Warn that we did this, if we're not performing template instantiation.
  7273. // In that case, we'll have warned already when the template was defined.
  7274. if (ActiveTemplateInstantiations.empty()) {
  7275. SourceLocation AddConstLoc;
  7276. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  7277. .IgnoreParens().getAs<FunctionTypeLoc>())
  7278. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  7279. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  7280. << FixItHint::CreateInsertion(AddConstLoc, " const");
  7281. }
  7282. }
  7283. }
  7284. if (Redeclaration) {
  7285. // NewFD and OldDecl represent declarations that need to be
  7286. // merged.
  7287. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  7288. NewFD->setInvalidDecl();
  7289. return Redeclaration;
  7290. }
  7291. Previous.clear();
  7292. Previous.addDecl(OldDecl);
  7293. if (FunctionTemplateDecl *OldTemplateDecl
  7294. = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  7295. NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
  7296. FunctionTemplateDecl *NewTemplateDecl
  7297. = NewFD->getDescribedFunctionTemplate();
  7298. assert(NewTemplateDecl && "Template/non-template mismatch");
  7299. if (CXXMethodDecl *Method
  7300. = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
  7301. Method->setAccess(OldTemplateDecl->getAccess());
  7302. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  7303. }
  7304. // If this is an explicit specialization of a member that is a function
  7305. // template, mark it as a member specialization.
  7306. if (IsExplicitSpecialization &&
  7307. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  7308. NewTemplateDecl->setMemberSpecialization();
  7309. assert(OldTemplateDecl->isMemberSpecialization());
  7310. }
  7311. } else {
  7312. // This needs to happen first so that 'inline' propagates.
  7313. NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
  7314. if (isa<CXXMethodDecl>(NewFD))
  7315. NewFD->setAccess(OldDecl->getAccess());
  7316. }
  7317. }
  7318. // Semantic checking for this function declaration (in isolation).
  7319. if (getLangOpts().CPlusPlus) {
  7320. // C++-specific checks.
  7321. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  7322. CheckConstructor(Constructor);
  7323. } else if (CXXDestructorDecl *Destructor =
  7324. dyn_cast<CXXDestructorDecl>(NewFD)) {
  7325. CXXRecordDecl *Record = Destructor->getParent();
  7326. QualType ClassType = Context.getTypeDeclType(Record);
  7327. // FIXME: Shouldn't we be able to perform this check even when the class
  7328. // type is dependent? Both gcc and edg can handle that.
  7329. if (!ClassType->isDependentType()) {
  7330. DeclarationName Name
  7331. = Context.DeclarationNames.getCXXDestructorName(
  7332. Context.getCanonicalType(ClassType));
  7333. if (NewFD->getDeclName() != Name) {
  7334. Diag(NewFD->getLocation(), diag::err_destructor_name);
  7335. NewFD->setInvalidDecl();
  7336. return Redeclaration;
  7337. }
  7338. }
  7339. } else if (CXXConversionDecl *Conversion
  7340. = dyn_cast<CXXConversionDecl>(NewFD)) {
  7341. ActOnConversionDeclarator(Conversion);
  7342. }
  7343. // Find any virtual functions that this function overrides.
  7344. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  7345. if (!Method->isFunctionTemplateSpecialization() &&
  7346. !Method->getDescribedFunctionTemplate() &&
  7347. Method->isCanonicalDecl()) {
  7348. if (AddOverriddenMethods(Method->getParent(), Method)) {
  7349. // If the function was marked as "static", we have a problem.
  7350. if (NewFD->getStorageClass() == SC_Static) {
  7351. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  7352. }
  7353. }
  7354. }
  7355. if (Method->isStatic())
  7356. checkThisInStaticMemberFunctionType(Method);
  7357. }
  7358. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  7359. if (NewFD->isOverloadedOperator() &&
  7360. CheckOverloadedOperatorDeclaration(NewFD)) {
  7361. NewFD->setInvalidDecl();
  7362. return Redeclaration;
  7363. }
  7364. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  7365. if (NewFD->getLiteralIdentifier() &&
  7366. CheckLiteralOperatorDeclaration(NewFD)) {
  7367. NewFD->setInvalidDecl();
  7368. return Redeclaration;
  7369. }
  7370. // In C++, check default arguments now that we have merged decls. Unless
  7371. // the lexical context is the class, because in this case this is done
  7372. // during delayed parsing anyway.
  7373. if (!CurContext->isRecord())
  7374. CheckCXXDefaultArguments(NewFD);
  7375. // If this function declares a builtin function, check the type of this
  7376. // declaration against the expected type for the builtin.
  7377. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  7378. ASTContext::GetBuiltinTypeError Error;
  7379. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  7380. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  7381. if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
  7382. // The type of this function differs from the type of the builtin,
  7383. // so forget about the builtin entirely.
  7384. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  7385. }
  7386. }
  7387. // If this function is declared as being extern "C", then check to see if
  7388. // the function returns a UDT (class, struct, or union type) that is not C
  7389. // compatible, and if it does, warn the user.
  7390. // But, issue any diagnostic on the first declaration only.
  7391. if (Previous.empty() && NewFD->isExternC()) {
  7392. QualType R = NewFD->getReturnType();
  7393. if (R->isIncompleteType() && !R->isVoidType())
  7394. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  7395. << NewFD << R;
  7396. else if (!R.isPODType(Context) && !R->isVoidType() &&
  7397. !R->isObjCObjectPointerType())
  7398. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  7399. }
  7400. }
  7401. return Redeclaration;
  7402. }
  7403. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  7404. // C++11 [basic.start.main]p3:
  7405. // A program that [...] declares main to be inline, static or
  7406. // constexpr is ill-formed.
  7407. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  7408. // appear in a declaration of main.
  7409. // static main is not an error under C99, but we should warn about it.
  7410. // We accept _Noreturn main as an extension.
  7411. if (FD->getStorageClass() == SC_Static)
  7412. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  7413. ? diag::err_static_main : diag::warn_static_main)
  7414. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  7415. if (FD->isInlineSpecified())
  7416. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  7417. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  7418. if (DS.isNoreturnSpecified()) {
  7419. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  7420. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  7421. Diag(NoreturnLoc, diag::ext_noreturn_main);
  7422. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  7423. << FixItHint::CreateRemoval(NoreturnRange);
  7424. }
  7425. if (FD->isConstexpr()) {
  7426. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  7427. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  7428. FD->setConstexpr(false);
  7429. }
  7430. if (getLangOpts().OpenCL) {
  7431. Diag(FD->getLocation(), diag::err_opencl_no_main)
  7432. << FD->hasAttr<OpenCLKernelAttr>();
  7433. FD->setInvalidDecl();
  7434. return;
  7435. }
  7436. QualType T = FD->getType();
  7437. assert(T->isFunctionType() && "function decl is not of function type");
  7438. const FunctionType* FT = T->castAs<FunctionType>();
  7439. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  7440. // In C with GNU extensions we allow main() to have non-integer return
  7441. // type, but we should warn about the extension, and we disable the
  7442. // implicit-return-zero rule.
  7443. // GCC in C mode accepts qualified 'int'.
  7444. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  7445. FD->setHasImplicitReturnZero(true);
  7446. else {
  7447. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  7448. SourceRange RTRange = FD->getReturnTypeSourceRange();
  7449. if (RTRange.isValid())
  7450. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  7451. << FixItHint::CreateReplacement(RTRange, "int");
  7452. }
  7453. } else {
  7454. // In C and C++, main magically returns 0 if you fall off the end;
  7455. // set the flag which tells us that.
  7456. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  7457. // All the standards say that main() should return 'int'.
  7458. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  7459. FD->setHasImplicitReturnZero(true);
  7460. else {
  7461. // Otherwise, this is just a flat-out error.
  7462. SourceRange RTRange = FD->getReturnTypeSourceRange();
  7463. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  7464. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  7465. : FixItHint());
  7466. FD->setInvalidDecl(true);
  7467. }
  7468. }
  7469. // Treat protoless main() as nullary.
  7470. if (isa<FunctionNoProtoType>(FT)) return;
  7471. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  7472. unsigned nparams = FTP->getNumParams();
  7473. assert(FD->getNumParams() == nparams);
  7474. bool HasExtraParameters = (nparams > 3);
  7475. if (FTP->isVariadic()) {
  7476. Diag(FD->getLocation(), diag::ext_variadic_main);
  7477. // FIXME: if we had information about the location of the ellipsis, we
  7478. // could add a FixIt hint to remove it as a parameter.
  7479. }
  7480. // Darwin passes an undocumented fourth argument of type char**. If
  7481. // other platforms start sprouting these, the logic below will start
  7482. // getting shifty.
  7483. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  7484. HasExtraParameters = false;
  7485. if (HasExtraParameters) {
  7486. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  7487. FD->setInvalidDecl(true);
  7488. nparams = 3;
  7489. }
  7490. // FIXME: a lot of the following diagnostics would be improved
  7491. // if we had some location information about types.
  7492. QualType CharPP =
  7493. Context.getPointerType(Context.getPointerType(Context.CharTy));
  7494. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  7495. for (unsigned i = 0; i < nparams; ++i) {
  7496. QualType AT = FTP->getParamType(i);
  7497. bool mismatch = true;
  7498. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  7499. mismatch = false;
  7500. else if (Expected[i] == CharPP) {
  7501. // As an extension, the following forms are okay:
  7502. // char const **
  7503. // char const * const *
  7504. // char * const *
  7505. QualifierCollector qs;
  7506. const PointerType* PT;
  7507. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  7508. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  7509. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  7510. Context.CharTy)) {
  7511. qs.removeConst();
  7512. mismatch = !qs.empty();
  7513. }
  7514. }
  7515. if (mismatch) {
  7516. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  7517. // TODO: suggest replacing given type with expected type
  7518. FD->setInvalidDecl(true);
  7519. }
  7520. }
  7521. if (nparams == 1 && !FD->isInvalidDecl()) {
  7522. Diag(FD->getLocation(), diag::warn_main_one_arg);
  7523. }
  7524. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  7525. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  7526. FD->setInvalidDecl();
  7527. }
  7528. }
  7529. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  7530. QualType T = FD->getType();
  7531. assert(T->isFunctionType() && "function decl is not of function type");
  7532. const FunctionType *FT = T->castAs<FunctionType>();
  7533. // Set an implicit return of 'zero' if the function can return some integral,
  7534. // enumeration, pointer or nullptr type.
  7535. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  7536. FT->getReturnType()->isAnyPointerType() ||
  7537. FT->getReturnType()->isNullPtrType())
  7538. // DllMain is exempt because a return value of zero means it failed.
  7539. if (FD->getName() != "DllMain")
  7540. FD->setHasImplicitReturnZero(true);
  7541. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  7542. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  7543. FD->setInvalidDecl();
  7544. }
  7545. }
  7546. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  7547. // FIXME: Need strict checking. In C89, we need to check for
  7548. // any assignment, increment, decrement, function-calls, or
  7549. // commas outside of a sizeof. In C99, it's the same list,
  7550. // except that the aforementioned are allowed in unevaluated
  7551. // expressions. Everything else falls under the
  7552. // "may accept other forms of constant expressions" exception.
  7553. // (We never end up here for C++, so the constant expression
  7554. // rules there don't matter.)
  7555. const Expr *Culprit;
  7556. if (Init->isConstantInitializer(Context, false, &Culprit))
  7557. return false;
  7558. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  7559. << Culprit->getSourceRange();
  7560. return true;
  7561. }
  7562. namespace {
  7563. // Visits an initialization expression to see if OrigDecl is evaluated in
  7564. // its own initialization and throws a warning if it does.
  7565. class SelfReferenceChecker
  7566. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  7567. Sema &S;
  7568. Decl *OrigDecl;
  7569. bool isRecordType;
  7570. bool isPODType;
  7571. bool isReferenceType;
  7572. bool isInitList;
  7573. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  7574. public:
  7575. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  7576. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  7577. S(S), OrigDecl(OrigDecl) {
  7578. isPODType = false;
  7579. isRecordType = false;
  7580. isReferenceType = false;
  7581. isInitList = false;
  7582. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  7583. isPODType = VD->getType().isPODType(S.Context);
  7584. isRecordType = VD->getType()->isRecordType();
  7585. isReferenceType = VD->getType()->isReferenceType();
  7586. }
  7587. }
  7588. // For most expressions, just call the visitor. For initializer lists,
  7589. // track the index of the field being initialized since fields are
  7590. // initialized in order allowing use of previously initialized fields.
  7591. void CheckExpr(Expr *E) {
  7592. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  7593. if (!InitList) {
  7594. Visit(E);
  7595. return;
  7596. }
  7597. // Track and increment the index here.
  7598. isInitList = true;
  7599. InitFieldIndex.push_back(0);
  7600. for (auto Child : InitList->children()) {
  7601. CheckExpr(cast<Expr>(Child));
  7602. ++InitFieldIndex.back();
  7603. }
  7604. InitFieldIndex.pop_back();
  7605. }
  7606. // Returns true if MemberExpr is checked and no futher checking is needed.
  7607. // Returns false if additional checking is required.
  7608. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  7609. llvm::SmallVector<FieldDecl*, 4> Fields;
  7610. Expr *Base = E;
  7611. bool ReferenceField = false;
  7612. // Get the field memebers used.
  7613. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  7614. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  7615. if (!FD)
  7616. return false;
  7617. Fields.push_back(FD);
  7618. if (FD->getType()->isReferenceType())
  7619. ReferenceField = true;
  7620. Base = ME->getBase()->IgnoreParenImpCasts();
  7621. }
  7622. // Keep checking only if the base Decl is the same.
  7623. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  7624. if (!DRE || DRE->getDecl() != OrigDecl)
  7625. return false;
  7626. // A reference field can be bound to an unininitialized field.
  7627. if (CheckReference && !ReferenceField)
  7628. return true;
  7629. // Convert FieldDecls to their index number.
  7630. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  7631. for (const FieldDecl *I : llvm::reverse(Fields))
  7632. UsedFieldIndex.push_back(I->getFieldIndex());
  7633. // See if a warning is needed by checking the first difference in index
  7634. // numbers. If field being used has index less than the field being
  7635. // initialized, then the use is safe.
  7636. for (auto UsedIter = UsedFieldIndex.begin(),
  7637. UsedEnd = UsedFieldIndex.end(),
  7638. OrigIter = InitFieldIndex.begin(),
  7639. OrigEnd = InitFieldIndex.end();
  7640. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  7641. if (*UsedIter < *OrigIter)
  7642. return true;
  7643. if (*UsedIter > *OrigIter)
  7644. break;
  7645. }
  7646. // TODO: Add a different warning which will print the field names.
  7647. HandleDeclRefExpr(DRE);
  7648. return true;
  7649. }
  7650. // For most expressions, the cast is directly above the DeclRefExpr.
  7651. // For conditional operators, the cast can be outside the conditional
  7652. // operator if both expressions are DeclRefExpr's.
  7653. void HandleValue(Expr *E) {
  7654. E = E->IgnoreParens();
  7655. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  7656. HandleDeclRefExpr(DRE);
  7657. return;
  7658. }
  7659. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  7660. Visit(CO->getCond());
  7661. HandleValue(CO->getTrueExpr());
  7662. HandleValue(CO->getFalseExpr());
  7663. return;
  7664. }
  7665. if (BinaryConditionalOperator *BCO =
  7666. dyn_cast<BinaryConditionalOperator>(E)) {
  7667. Visit(BCO->getCond());
  7668. HandleValue(BCO->getFalseExpr());
  7669. return;
  7670. }
  7671. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  7672. HandleValue(OVE->getSourceExpr());
  7673. return;
  7674. }
  7675. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  7676. if (BO->getOpcode() == BO_Comma) {
  7677. Visit(BO->getLHS());
  7678. HandleValue(BO->getRHS());
  7679. return;
  7680. }
  7681. }
  7682. if (isa<MemberExpr>(E)) {
  7683. if (isInitList) {
  7684. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  7685. false /*CheckReference*/))
  7686. return;
  7687. }
  7688. Expr *Base = E->IgnoreParenImpCasts();
  7689. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  7690. // Check for static member variables and don't warn on them.
  7691. if (!isa<FieldDecl>(ME->getMemberDecl()))
  7692. return;
  7693. Base = ME->getBase()->IgnoreParenImpCasts();
  7694. }
  7695. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  7696. HandleDeclRefExpr(DRE);
  7697. return;
  7698. }
  7699. Visit(E);
  7700. }
  7701. // Reference types not handled in HandleValue are handled here since all
  7702. // uses of references are bad, not just r-value uses.
  7703. void VisitDeclRefExpr(DeclRefExpr *E) {
  7704. if (isReferenceType)
  7705. HandleDeclRefExpr(E);
  7706. }
  7707. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  7708. if (E->getCastKind() == CK_LValueToRValue) {
  7709. HandleValue(E->getSubExpr());
  7710. return;
  7711. }
  7712. Inherited::VisitImplicitCastExpr(E);
  7713. }
  7714. void VisitMemberExpr(MemberExpr *E) {
  7715. if (isInitList) {
  7716. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  7717. return;
  7718. }
  7719. // Don't warn on arrays since they can be treated as pointers.
  7720. if (E->getType()->canDecayToPointerType()) return;
  7721. // Warn when a non-static method call is followed by non-static member
  7722. // field accesses, which is followed by a DeclRefExpr.
  7723. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  7724. bool Warn = (MD && !MD->isStatic());
  7725. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  7726. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  7727. if (!isa<FieldDecl>(ME->getMemberDecl()))
  7728. Warn = false;
  7729. Base = ME->getBase()->IgnoreParenImpCasts();
  7730. }
  7731. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  7732. if (Warn)
  7733. HandleDeclRefExpr(DRE);
  7734. return;
  7735. }
  7736. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  7737. // Visit that expression.
  7738. Visit(Base);
  7739. }
  7740. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  7741. Expr *Callee = E->getCallee();
  7742. if (isa<UnresolvedLookupExpr>(Callee))
  7743. return Inherited::VisitCXXOperatorCallExpr(E);
  7744. Visit(Callee);
  7745. for (auto Arg: E->arguments())
  7746. HandleValue(Arg->IgnoreParenImpCasts());
  7747. }
  7748. void VisitUnaryOperator(UnaryOperator *E) {
  7749. // For POD record types, addresses of its own members are well-defined.
  7750. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  7751. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  7752. if (!isPODType)
  7753. HandleValue(E->getSubExpr());
  7754. return;
  7755. }
  7756. if (E->isIncrementDecrementOp()) {
  7757. HandleValue(E->getSubExpr());
  7758. return;
  7759. }
  7760. Inherited::VisitUnaryOperator(E);
  7761. }
  7762. void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
  7763. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  7764. if (E->getConstructor()->isCopyConstructor()) {
  7765. Expr *ArgExpr = E->getArg(0);
  7766. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  7767. if (ILE->getNumInits() == 1)
  7768. ArgExpr = ILE->getInit(0);
  7769. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  7770. if (ICE->getCastKind() == CK_NoOp)
  7771. ArgExpr = ICE->getSubExpr();
  7772. HandleValue(ArgExpr);
  7773. return;
  7774. }
  7775. Inherited::VisitCXXConstructExpr(E);
  7776. }
  7777. void VisitCallExpr(CallExpr *E) {
  7778. // Treat std::move as a use.
  7779. if (E->getNumArgs() == 1) {
  7780. if (FunctionDecl *FD = E->getDirectCallee()) {
  7781. if (FD->isInStdNamespace() && FD->getIdentifier() &&
  7782. FD->getIdentifier()->isStr("move")) {
  7783. HandleValue(E->getArg(0));
  7784. return;
  7785. }
  7786. }
  7787. }
  7788. Inherited::VisitCallExpr(E);
  7789. }
  7790. void VisitBinaryOperator(BinaryOperator *E) {
  7791. if (E->isCompoundAssignmentOp()) {
  7792. HandleValue(E->getLHS());
  7793. Visit(E->getRHS());
  7794. return;
  7795. }
  7796. Inherited::VisitBinaryOperator(E);
  7797. }
  7798. // A custom visitor for BinaryConditionalOperator is needed because the
  7799. // regular visitor would check the condition and true expression separately
  7800. // but both point to the same place giving duplicate diagnostics.
  7801. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  7802. Visit(E->getCond());
  7803. Visit(E->getFalseExpr());
  7804. }
  7805. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  7806. Decl* ReferenceDecl = DRE->getDecl();
  7807. if (OrigDecl != ReferenceDecl) return;
  7808. unsigned diag;
  7809. if (isReferenceType) {
  7810. diag = diag::warn_uninit_self_reference_in_reference_init;
  7811. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  7812. diag = diag::warn_static_self_reference_in_init;
  7813. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  7814. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  7815. DRE->getDecl()->getType()->isRecordType()) {
  7816. diag = diag::warn_uninit_self_reference_in_init;
  7817. } else {
  7818. // Local variables will be handled by the CFG analysis.
  7819. return;
  7820. }
  7821. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  7822. S.PDiag(diag)
  7823. << DRE->getNameInfo().getName()
  7824. << OrigDecl->getLocation()
  7825. << DRE->getSourceRange());
  7826. }
  7827. };
  7828. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  7829. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  7830. bool DirectInit) {
  7831. // Parameters arguments are occassionially constructed with itself,
  7832. // for instance, in recursive functions. Skip them.
  7833. if (isa<ParmVarDecl>(OrigDecl))
  7834. return;
  7835. E = E->IgnoreParens();
  7836. // Skip checking T a = a where T is not a record or reference type.
  7837. // Doing so is a way to silence uninitialized warnings.
  7838. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  7839. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  7840. if (ICE->getCastKind() == CK_LValueToRValue)
  7841. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  7842. if (DRE->getDecl() == OrigDecl)
  7843. return;
  7844. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  7845. }
  7846. }
  7847. /// AddInitializerToDecl - Adds the initializer Init to the
  7848. /// declaration dcl. If DirectInit is true, this is C++ direct
  7849. /// initialization rather than copy initialization.
  7850. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
  7851. bool DirectInit, bool TypeMayContainAuto) {
  7852. // If there is no declaration, there was an error parsing it. Just ignore
  7853. // the initializer.
  7854. if (!RealDecl || RealDecl->isInvalidDecl()) {
  7855. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  7856. return;
  7857. }
  7858. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  7859. // Pure-specifiers are handled in ActOnPureSpecifier.
  7860. Diag(Method->getLocation(), diag::err_member_function_initialization)
  7861. << Method->getDeclName() << Init->getSourceRange();
  7862. Method->setInvalidDecl();
  7863. return;
  7864. }
  7865. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  7866. if (!VDecl) {
  7867. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  7868. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  7869. RealDecl->setInvalidDecl();
  7870. return;
  7871. }
  7872. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  7873. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  7874. if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
  7875. // Attempt typo correction early so that the type of the init expression can
  7876. // be deduced based on the chosen correction:if the original init contains a
  7877. // TypoExpr.
  7878. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  7879. if (!Res.isUsable()) {
  7880. RealDecl->setInvalidDecl();
  7881. return;
  7882. }
  7883. if (Res.get() != Init) {
  7884. Init = Res.get();
  7885. if (CXXDirectInit)
  7886. CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  7887. }
  7888. Expr *DeduceInit = Init;
  7889. // Initializer could be a C++ direct-initializer. Deduction only works if it
  7890. // contains exactly one expression.
  7891. if (CXXDirectInit) {
  7892. if (CXXDirectInit->getNumExprs() == 0) {
  7893. // It isn't possible to write this directly, but it is possible to
  7894. // end up in this situation with "auto x(some_pack...);"
  7895. Diag(CXXDirectInit->getLocStart(),
  7896. VDecl->isInitCapture() ? diag::err_init_capture_no_expression
  7897. : diag::err_auto_var_init_no_expression)
  7898. << VDecl->getDeclName() << VDecl->getType()
  7899. << VDecl->getSourceRange();
  7900. RealDecl->setInvalidDecl();
  7901. return;
  7902. } else if (CXXDirectInit->getNumExprs() > 1) {
  7903. Diag(CXXDirectInit->getExpr(1)->getLocStart(),
  7904. VDecl->isInitCapture()
  7905. ? diag::err_init_capture_multiple_expressions
  7906. : diag::err_auto_var_init_multiple_expressions)
  7907. << VDecl->getDeclName() << VDecl->getType()
  7908. << VDecl->getSourceRange();
  7909. RealDecl->setInvalidDecl();
  7910. return;
  7911. } else {
  7912. DeduceInit = CXXDirectInit->getExpr(0);
  7913. if (isa<InitListExpr>(DeduceInit))
  7914. Diag(CXXDirectInit->getLocStart(),
  7915. diag::err_auto_var_init_paren_braces)
  7916. << VDecl->getDeclName() << VDecl->getType()
  7917. << VDecl->getSourceRange();
  7918. }
  7919. }
  7920. // Expressions default to 'id' when we're in a debugger.
  7921. bool DefaultedToAuto = false;
  7922. if (getLangOpts().DebuggerCastResultToId &&
  7923. Init->getType() == Context.UnknownAnyTy) {
  7924. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  7925. if (Result.isInvalid()) {
  7926. VDecl->setInvalidDecl();
  7927. return;
  7928. }
  7929. Init = Result.get();
  7930. DefaultedToAuto = true;
  7931. }
  7932. QualType DeducedType;
  7933. if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
  7934. DAR_Failed)
  7935. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  7936. if (DeducedType.isNull()) {
  7937. RealDecl->setInvalidDecl();
  7938. return;
  7939. }
  7940. VDecl->setType(DeducedType);
  7941. assert(VDecl->isLinkageValid());
  7942. // In ARC, infer lifetime.
  7943. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  7944. VDecl->setInvalidDecl();
  7945. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  7946. // 'id' instead of a specific object type prevents most of our usual checks.
  7947. // We only want to warn outside of template instantiations, though:
  7948. // inside a template, the 'id' could have come from a parameter.
  7949. if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
  7950. DeducedType->isObjCIdType()) {
  7951. SourceLocation Loc =
  7952. VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
  7953. Diag(Loc, diag::warn_auto_var_is_id)
  7954. << VDecl->getDeclName() << DeduceInit->getSourceRange();
  7955. }
  7956. // If this is a redeclaration, check that the type we just deduced matches
  7957. // the previously declared type.
  7958. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  7959. // We never need to merge the type, because we cannot form an incomplete
  7960. // array of auto, nor deduce such a type.
  7961. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
  7962. }
  7963. // Check the deduced type is valid for a variable declaration.
  7964. CheckVariableDeclarationType(VDecl);
  7965. if (VDecl->isInvalidDecl())
  7966. return;
  7967. // If all looks well, warn if this is a case that will change meaning when
  7968. // we implement N3922.
  7969. if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) {
  7970. Diag(Init->getLocStart(),
  7971. diag::warn_auto_var_direct_list_init)
  7972. << FixItHint::CreateInsertion(Init->getLocStart(), "=");
  7973. }
  7974. }
  7975. // dllimport cannot be used on variable definitions.
  7976. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  7977. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  7978. VDecl->setInvalidDecl();
  7979. return;
  7980. }
  7981. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  7982. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  7983. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  7984. VDecl->setInvalidDecl();
  7985. return;
  7986. }
  7987. if (!VDecl->getType()->isDependentType()) {
  7988. // A definition must end up with a complete type, which means it must be
  7989. // complete with the restriction that an array type might be completed by
  7990. // the initializer; note that later code assumes this restriction.
  7991. QualType BaseDeclType = VDecl->getType();
  7992. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  7993. BaseDeclType = Array->getElementType();
  7994. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  7995. diag::err_typecheck_decl_incomplete_type)) {
  7996. RealDecl->setInvalidDecl();
  7997. return;
  7998. }
  7999. // The variable can not have an abstract class type.
  8000. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  8001. diag::err_abstract_type_in_decl,
  8002. AbstractVariableType))
  8003. VDecl->setInvalidDecl();
  8004. }
  8005. VarDecl *Def;
  8006. if ((Def = VDecl->getDefinition()) && Def != VDecl) {
  8007. NamedDecl *Hidden = nullptr;
  8008. if (!hasVisibleDefinition(Def, &Hidden) &&
  8009. (VDecl->getFormalLinkage() == InternalLinkage ||
  8010. VDecl->getDescribedVarTemplate() ||
  8011. VDecl->getNumTemplateParameterLists() ||
  8012. VDecl->getDeclContext()->isDependentContext())) {
  8013. // The previous definition is hidden, and multiple definitions are
  8014. // permitted (in separate TUs). Form another definition of it.
  8015. } else {
  8016. Diag(VDecl->getLocation(), diag::err_redefinition)
  8017. << VDecl->getDeclName();
  8018. Diag(Def->getLocation(), diag::note_previous_definition);
  8019. VDecl->setInvalidDecl();
  8020. return;
  8021. }
  8022. }
  8023. if (getLangOpts().CPlusPlus) {
  8024. // C++ [class.static.data]p4
  8025. // If a static data member is of const integral or const
  8026. // enumeration type, its declaration in the class definition can
  8027. // specify a constant-initializer which shall be an integral
  8028. // constant expression (5.19). In that case, the member can appear
  8029. // in integral constant expressions. The member shall still be
  8030. // defined in a namespace scope if it is used in the program and the
  8031. // namespace scope definition shall not contain an initializer.
  8032. //
  8033. // We already performed a redefinition check above, but for static
  8034. // data members we also need to check whether there was an in-class
  8035. // declaration with an initializer.
  8036. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  8037. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  8038. << VDecl->getDeclName();
  8039. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  8040. diag::note_previous_initializer)
  8041. << 0;
  8042. return;
  8043. }
  8044. if (VDecl->hasLocalStorage())
  8045. getCurFunction()->setHasBranchProtectedScope();
  8046. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  8047. VDecl->setInvalidDecl();
  8048. return;
  8049. }
  8050. }
  8051. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  8052. // a kernel function cannot be initialized."
  8053. if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
  8054. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  8055. VDecl->setInvalidDecl();
  8056. return;
  8057. }
  8058. // Get the decls type and save a reference for later, since
  8059. // CheckInitializerTypes may change it.
  8060. QualType DclT = VDecl->getType(), SavT = DclT;
  8061. // Expressions default to 'id' when we're in a debugger
  8062. // and we are assigning it to a variable of Objective-C pointer type.
  8063. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  8064. Init->getType() == Context.UnknownAnyTy) {
  8065. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  8066. if (Result.isInvalid()) {
  8067. VDecl->setInvalidDecl();
  8068. return;
  8069. }
  8070. Init = Result.get();
  8071. }
  8072. // Perform the initialization.
  8073. if (!VDecl->isInvalidDecl()) {
  8074. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  8075. InitializationKind Kind
  8076. = DirectInit ?
  8077. CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
  8078. Init->getLocStart(),
  8079. Init->getLocEnd())
  8080. : InitializationKind::CreateDirectList(
  8081. VDecl->getLocation())
  8082. : InitializationKind::CreateCopy(VDecl->getLocation(),
  8083. Init->getLocStart());
  8084. MultiExprArg Args = Init;
  8085. if (CXXDirectInit)
  8086. Args = MultiExprArg(CXXDirectInit->getExprs(),
  8087. CXXDirectInit->getNumExprs());
  8088. // Try to correct any TypoExprs in the initialization arguments.
  8089. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  8090. ExprResult Res = CorrectDelayedTyposInExpr(
  8091. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  8092. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  8093. return Init.Failed() ? ExprError() : E;
  8094. });
  8095. if (Res.isInvalid()) {
  8096. VDecl->setInvalidDecl();
  8097. } else if (Res.get() != Args[Idx]) {
  8098. Args[Idx] = Res.get();
  8099. }
  8100. }
  8101. if (VDecl->isInvalidDecl())
  8102. return;
  8103. InitializationSequence InitSeq(*this, Entity, Kind, Args);
  8104. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  8105. if (Result.isInvalid()) {
  8106. VDecl->setInvalidDecl();
  8107. return;
  8108. }
  8109. Init = Result.getAs<Expr>();
  8110. }
  8111. // Check for self-references within variable initializers.
  8112. // Variables declared within a function/method body (except for references)
  8113. // are handled by a dataflow analysis.
  8114. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  8115. VDecl->getType()->isReferenceType()) {
  8116. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  8117. }
  8118. // If the type changed, it means we had an incomplete type that was
  8119. // completed by the initializer. For example:
  8120. // int ary[] = { 1, 3, 5 };
  8121. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  8122. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  8123. VDecl->setType(DclT);
  8124. if (!VDecl->isInvalidDecl()) {
  8125. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  8126. if (VDecl->hasAttr<BlocksAttr>())
  8127. checkRetainCycles(VDecl, Init);
  8128. // It is safe to assign a weak reference into a strong variable.
  8129. // Although this code can still have problems:
  8130. // id x = self.weakProp;
  8131. // id y = self.weakProp;
  8132. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  8133. // paths through the function. This should be revisited if
  8134. // -Wrepeated-use-of-weak is made flow-sensitive.
  8135. if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
  8136. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  8137. Init->getLocStart()))
  8138. getCurFunction()->markSafeWeakUse(Init);
  8139. }
  8140. // The initialization is usually a full-expression.
  8141. //
  8142. // FIXME: If this is a braced initialization of an aggregate, it is not
  8143. // an expression, and each individual field initializer is a separate
  8144. // full-expression. For instance, in:
  8145. //
  8146. // struct Temp { ~Temp(); };
  8147. // struct S { S(Temp); };
  8148. // struct T { S a, b; } t = { Temp(), Temp() }
  8149. //
  8150. // we should destroy the first Temp before constructing the second.
  8151. ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
  8152. false,
  8153. VDecl->isConstexpr());
  8154. if (Result.isInvalid()) {
  8155. VDecl->setInvalidDecl();
  8156. return;
  8157. }
  8158. Init = Result.get();
  8159. // Attach the initializer to the decl.
  8160. VDecl->setInit(Init);
  8161. if (VDecl->isLocalVarDecl()) {
  8162. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  8163. // static storage duration shall be constant expressions or string literals.
  8164. // C++ does not have this restriction.
  8165. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
  8166. const Expr *Culprit;
  8167. if (VDecl->getStorageClass() == SC_Static)
  8168. CheckForConstantInitializer(Init, DclT);
  8169. // C89 is stricter than C99 for non-static aggregate types.
  8170. // C89 6.5.7p3: All the expressions [...] in an initializer list
  8171. // for an object that has aggregate or union type shall be
  8172. // constant expressions.
  8173. else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  8174. isa<InitListExpr>(Init) &&
  8175. !Init->isConstantInitializer(Context, false, &Culprit))
  8176. Diag(Culprit->getExprLoc(),
  8177. diag::ext_aggregate_init_not_constant)
  8178. << Culprit->getSourceRange();
  8179. }
  8180. } else if (VDecl->isStaticDataMember() &&
  8181. VDecl->getLexicalDeclContext()->isRecord()) {
  8182. // This is an in-class initialization for a static data member, e.g.,
  8183. //
  8184. // struct S {
  8185. // static const int value = 17;
  8186. // };
  8187. // C++ [class.mem]p4:
  8188. // A member-declarator can contain a constant-initializer only
  8189. // if it declares a static member (9.4) of const integral or
  8190. // const enumeration type, see 9.4.2.
  8191. //
  8192. // C++11 [class.static.data]p3:
  8193. // If a non-volatile const static data member is of integral or
  8194. // enumeration type, its declaration in the class definition can
  8195. // specify a brace-or-equal-initializer in which every initalizer-clause
  8196. // that is an assignment-expression is a constant expression. A static
  8197. // data member of literal type can be declared in the class definition
  8198. // with the constexpr specifier; if so, its declaration shall specify a
  8199. // brace-or-equal-initializer in which every initializer-clause that is
  8200. // an assignment-expression is a constant expression.
  8201. // Do nothing on dependent types.
  8202. if (DclT->isDependentType()) {
  8203. // Allow any 'static constexpr' members, whether or not they are of literal
  8204. // type. We separately check that every constexpr variable is of literal
  8205. // type.
  8206. } else if (VDecl->isConstexpr()) {
  8207. // Require constness.
  8208. } else if (!DclT.isConstQualified()) {
  8209. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  8210. << Init->getSourceRange();
  8211. VDecl->setInvalidDecl();
  8212. // We allow integer constant expressions in all cases.
  8213. } else if (DclT->isIntegralOrEnumerationType()) {
  8214. // Check whether the expression is a constant expression.
  8215. SourceLocation Loc;
  8216. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  8217. // In C++11, a non-constexpr const static data member with an
  8218. // in-class initializer cannot be volatile.
  8219. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  8220. else if (Init->isValueDependent())
  8221. ; // Nothing to check.
  8222. else if (Init->isIntegerConstantExpr(Context, &Loc))
  8223. ; // Ok, it's an ICE!
  8224. else if (Init->isEvaluatable(Context)) {
  8225. // If we can constant fold the initializer through heroics, accept it,
  8226. // but report this as a use of an extension for -pedantic.
  8227. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  8228. << Init->getSourceRange();
  8229. } else {
  8230. // Otherwise, this is some crazy unknown case. Report the issue at the
  8231. // location provided by the isIntegerConstantExpr failed check.
  8232. Diag(Loc, diag::err_in_class_initializer_non_constant)
  8233. << Init->getSourceRange();
  8234. VDecl->setInvalidDecl();
  8235. }
  8236. // We allow foldable floating-point constants as an extension.
  8237. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  8238. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  8239. // it anyway and provide a fixit to add the 'constexpr'.
  8240. if (getLangOpts().CPlusPlus11) {
  8241. Diag(VDecl->getLocation(),
  8242. diag::ext_in_class_initializer_float_type_cxx11)
  8243. << DclT << Init->getSourceRange();
  8244. Diag(VDecl->getLocStart(),
  8245. diag::note_in_class_initializer_float_type_cxx11)
  8246. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  8247. } else {
  8248. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  8249. << DclT << Init->getSourceRange();
  8250. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  8251. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  8252. << Init->getSourceRange();
  8253. VDecl->setInvalidDecl();
  8254. }
  8255. }
  8256. // Suggest adding 'constexpr' in C++11 for literal types.
  8257. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  8258. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  8259. << DclT << Init->getSourceRange()
  8260. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  8261. VDecl->setConstexpr(true);
  8262. } else {
  8263. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  8264. << DclT << Init->getSourceRange();
  8265. VDecl->setInvalidDecl();
  8266. }
  8267. } else if (VDecl->isFileVarDecl()) {
  8268. if (VDecl->getStorageClass() == SC_Extern &&
  8269. (!getLangOpts().CPlusPlus ||
  8270. !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
  8271. VDecl->isExternC())) &&
  8272. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  8273. Diag(VDecl->getLocation(), diag::warn_extern_init);
  8274. // C99 6.7.8p4. All file scoped initializers need to be constant.
  8275. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  8276. CheckForConstantInitializer(Init, DclT);
  8277. }
  8278. // We will represent direct-initialization similarly to copy-initialization:
  8279. // int x(1); -as-> int x = 1;
  8280. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  8281. //
  8282. // Clients that want to distinguish between the two forms, can check for
  8283. // direct initializer using VarDecl::getInitStyle().
  8284. // A major benefit is that clients that don't particularly care about which
  8285. // exactly form was it (like the CodeGen) can handle both cases without
  8286. // special case code.
  8287. // C++ 8.5p11:
  8288. // The form of initialization (using parentheses or '=') is generally
  8289. // insignificant, but does matter when the entity being initialized has a
  8290. // class type.
  8291. if (CXXDirectInit) {
  8292. assert(DirectInit && "Call-style initializer must be direct init.");
  8293. VDecl->setInitStyle(VarDecl::CallInit);
  8294. } else if (DirectInit) {
  8295. // This must be list-initialization. No other way is direct-initialization.
  8296. VDecl->setInitStyle(VarDecl::ListInit);
  8297. }
  8298. CheckCompleteVariableDeclaration(VDecl);
  8299. }
  8300. /// ActOnInitializerError - Given that there was an error parsing an
  8301. /// initializer for the given declaration, try to return to some form
  8302. /// of sanity.
  8303. void Sema::ActOnInitializerError(Decl *D) {
  8304. // Our main concern here is re-establishing invariants like "a
  8305. // variable's type is either dependent or complete".
  8306. if (!D || D->isInvalidDecl()) return;
  8307. VarDecl *VD = dyn_cast<VarDecl>(D);
  8308. if (!VD) return;
  8309. // Auto types are meaningless if we can't make sense of the initializer.
  8310. if (ParsingInitForAutoVars.count(D)) {
  8311. D->setInvalidDecl();
  8312. return;
  8313. }
  8314. QualType Ty = VD->getType();
  8315. if (Ty->isDependentType()) return;
  8316. // Require a complete type.
  8317. if (RequireCompleteType(VD->getLocation(),
  8318. Context.getBaseElementType(Ty),
  8319. diag::err_typecheck_decl_incomplete_type)) {
  8320. VD->setInvalidDecl();
  8321. return;
  8322. }
  8323. // Require a non-abstract type.
  8324. if (RequireNonAbstractType(VD->getLocation(), Ty,
  8325. diag::err_abstract_type_in_decl,
  8326. AbstractVariableType)) {
  8327. VD->setInvalidDecl();
  8328. return;
  8329. }
  8330. // Don't bother complaining about constructors or destructors,
  8331. // though.
  8332. }
  8333. void Sema::ActOnUninitializedDecl(Decl *RealDecl,
  8334. bool TypeMayContainAuto) {
  8335. // If there is no declaration, there was an error parsing it. Just ignore it.
  8336. if (!RealDecl)
  8337. return;
  8338. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  8339. QualType Type = Var->getType();
  8340. // C++11 [dcl.spec.auto]p3
  8341. if (TypeMayContainAuto && Type->getContainedAutoType()) {
  8342. Diag(Var->getLocation(), diag::err_auto_var_requires_init)
  8343. << Var->getDeclName() << Type;
  8344. Var->setInvalidDecl();
  8345. return;
  8346. }
  8347. // C++11 [class.static.data]p3: A static data member can be declared with
  8348. // the constexpr specifier; if so, its declaration shall specify
  8349. // a brace-or-equal-initializer.
  8350. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  8351. // the definition of a variable [...] or the declaration of a static data
  8352. // member.
  8353. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
  8354. if (Var->isStaticDataMember())
  8355. Diag(Var->getLocation(),
  8356. diag::err_constexpr_static_mem_var_requires_init)
  8357. << Var->getDeclName();
  8358. else
  8359. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  8360. Var->setInvalidDecl();
  8361. return;
  8362. }
  8363. // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
  8364. // definition having the concept specifier is called a variable concept. A
  8365. // concept definition refers to [...] a variable concept and its initializer.
  8366. if (Var->isConcept()) {
  8367. Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
  8368. Var->setInvalidDecl();
  8369. return;
  8370. }
  8371. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  8372. // be initialized.
  8373. if (!Var->isInvalidDecl() &&
  8374. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  8375. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  8376. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  8377. Var->setInvalidDecl();
  8378. return;
  8379. }
  8380. switch (Var->isThisDeclarationADefinition()) {
  8381. case VarDecl::Definition:
  8382. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  8383. break;
  8384. // We have an out-of-line definition of a static data member
  8385. // that has an in-class initializer, so we type-check this like
  8386. // a declaration.
  8387. //
  8388. // Fall through
  8389. case VarDecl::DeclarationOnly:
  8390. // It's only a declaration.
  8391. // Block scope. C99 6.7p7: If an identifier for an object is
  8392. // declared with no linkage (C99 6.2.2p6), the type for the
  8393. // object shall be complete.
  8394. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  8395. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  8396. RequireCompleteType(Var->getLocation(), Type,
  8397. diag::err_typecheck_decl_incomplete_type))
  8398. Var->setInvalidDecl();
  8399. // Make sure that the type is not abstract.
  8400. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  8401. RequireNonAbstractType(Var->getLocation(), Type,
  8402. diag::err_abstract_type_in_decl,
  8403. AbstractVariableType))
  8404. Var->setInvalidDecl();
  8405. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  8406. Var->getStorageClass() == SC_PrivateExtern) {
  8407. Diag(Var->getLocation(), diag::warn_private_extern);
  8408. Diag(Var->getLocation(), diag::note_private_extern);
  8409. }
  8410. return;
  8411. case VarDecl::TentativeDefinition:
  8412. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  8413. // object that has file scope without an initializer, and without a
  8414. // storage-class specifier or with the storage-class specifier "static",
  8415. // constitutes a tentative definition. Note: A tentative definition with
  8416. // external linkage is valid (C99 6.2.2p5).
  8417. if (!Var->isInvalidDecl()) {
  8418. if (const IncompleteArrayType *ArrayT
  8419. = Context.getAsIncompleteArrayType(Type)) {
  8420. if (RequireCompleteType(Var->getLocation(),
  8421. ArrayT->getElementType(),
  8422. diag::err_illegal_decl_array_incomplete_type))
  8423. Var->setInvalidDecl();
  8424. } else if (Var->getStorageClass() == SC_Static) {
  8425. // C99 6.9.2p3: If the declaration of an identifier for an object is
  8426. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  8427. // declared type shall not be an incomplete type.
  8428. // NOTE: code such as the following
  8429. // static struct s;
  8430. // struct s { int a; };
  8431. // is accepted by gcc. Hence here we issue a warning instead of
  8432. // an error and we do not invalidate the static declaration.
  8433. // NOTE: to avoid multiple warnings, only check the first declaration.
  8434. if (Var->isFirstDecl())
  8435. RequireCompleteType(Var->getLocation(), Type,
  8436. diag::ext_typecheck_decl_incomplete_type);
  8437. }
  8438. }
  8439. // Record the tentative definition; we're done.
  8440. if (!Var->isInvalidDecl())
  8441. TentativeDefinitions.push_back(Var);
  8442. return;
  8443. }
  8444. // Provide a specific diagnostic for uninitialized variable
  8445. // definitions with incomplete array type.
  8446. if (Type->isIncompleteArrayType()) {
  8447. Diag(Var->getLocation(),
  8448. diag::err_typecheck_incomplete_array_needs_initializer);
  8449. Var->setInvalidDecl();
  8450. return;
  8451. }
  8452. // Provide a specific diagnostic for uninitialized variable
  8453. // definitions with reference type.
  8454. if (Type->isReferenceType()) {
  8455. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  8456. << Var->getDeclName()
  8457. << SourceRange(Var->getLocation(), Var->getLocation());
  8458. Var->setInvalidDecl();
  8459. return;
  8460. }
  8461. // Do not attempt to type-check the default initializer for a
  8462. // variable with dependent type.
  8463. if (Type->isDependentType())
  8464. return;
  8465. if (Var->isInvalidDecl())
  8466. return;
  8467. if (!Var->hasAttr<AliasAttr>()) {
  8468. if (RequireCompleteType(Var->getLocation(),
  8469. Context.getBaseElementType(Type),
  8470. diag::err_typecheck_decl_incomplete_type)) {
  8471. Var->setInvalidDecl();
  8472. return;
  8473. }
  8474. } else {
  8475. return;
  8476. }
  8477. // The variable can not have an abstract class type.
  8478. if (RequireNonAbstractType(Var->getLocation(), Type,
  8479. diag::err_abstract_type_in_decl,
  8480. AbstractVariableType)) {
  8481. Var->setInvalidDecl();
  8482. return;
  8483. }
  8484. // Check for jumps past the implicit initializer. C++0x
  8485. // clarifies that this applies to a "variable with automatic
  8486. // storage duration", not a "local variable".
  8487. // C++11 [stmt.dcl]p3
  8488. // A program that jumps from a point where a variable with automatic
  8489. // storage duration is not in scope to a point where it is in scope is
  8490. // ill-formed unless the variable has scalar type, class type with a
  8491. // trivial default constructor and a trivial destructor, a cv-qualified
  8492. // version of one of these types, or an array of one of the preceding
  8493. // types and is declared without an initializer.
  8494. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  8495. if (const RecordType *Record
  8496. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  8497. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  8498. // Mark the function for further checking even if the looser rules of
  8499. // C++11 do not require such checks, so that we can diagnose
  8500. // incompatibilities with C++98.
  8501. if (!CXXRecord->isPOD())
  8502. getCurFunction()->setHasBranchProtectedScope();
  8503. }
  8504. }
  8505. // C++03 [dcl.init]p9:
  8506. // If no initializer is specified for an object, and the
  8507. // object is of (possibly cv-qualified) non-POD class type (or
  8508. // array thereof), the object shall be default-initialized; if
  8509. // the object is of const-qualified type, the underlying class
  8510. // type shall have a user-declared default
  8511. // constructor. Otherwise, if no initializer is specified for
  8512. // a non- static object, the object and its subobjects, if
  8513. // any, have an indeterminate initial value); if the object
  8514. // or any of its subobjects are of const-qualified type, the
  8515. // program is ill-formed.
  8516. // C++0x [dcl.init]p11:
  8517. // If no initializer is specified for an object, the object is
  8518. // default-initialized; [...].
  8519. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  8520. InitializationKind Kind
  8521. = InitializationKind::CreateDefault(Var->getLocation());
  8522. InitializationSequence InitSeq(*this, Entity, Kind, None);
  8523. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  8524. if (Init.isInvalid())
  8525. Var->setInvalidDecl();
  8526. else if (Init.get()) {
  8527. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  8528. // This is important for template substitution.
  8529. Var->setInitStyle(VarDecl::CallInit);
  8530. }
  8531. CheckCompleteVariableDeclaration(Var);
  8532. }
  8533. }
  8534. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  8535. VarDecl *VD = dyn_cast<VarDecl>(D);
  8536. if (!VD) {
  8537. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  8538. D->setInvalidDecl();
  8539. return;
  8540. }
  8541. VD->setCXXForRangeDecl(true);
  8542. // for-range-declaration cannot be given a storage class specifier.
  8543. int Error = -1;
  8544. switch (VD->getStorageClass()) {
  8545. case SC_None:
  8546. break;
  8547. case SC_Extern:
  8548. Error = 0;
  8549. break;
  8550. case SC_Static:
  8551. Error = 1;
  8552. break;
  8553. case SC_PrivateExtern:
  8554. Error = 2;
  8555. break;
  8556. case SC_Auto:
  8557. Error = 3;
  8558. break;
  8559. case SC_Register:
  8560. Error = 4;
  8561. break;
  8562. case SC_OpenCLWorkGroupLocal:
  8563. llvm_unreachable("Unexpected storage class");
  8564. }
  8565. if (Error != -1) {
  8566. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  8567. << VD->getDeclName() << Error;
  8568. D->setInvalidDecl();
  8569. }
  8570. }
  8571. StmtResult
  8572. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  8573. IdentifierInfo *Ident,
  8574. ParsedAttributes &Attrs,
  8575. SourceLocation AttrEnd) {
  8576. // C++1y [stmt.iter]p1:
  8577. // A range-based for statement of the form
  8578. // for ( for-range-identifier : for-range-initializer ) statement
  8579. // is equivalent to
  8580. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  8581. DeclSpec DS(Attrs.getPool().getFactory());
  8582. const char *PrevSpec;
  8583. unsigned DiagID;
  8584. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  8585. getPrintingPolicy());
  8586. Declarator D(DS, Declarator::ForContext);
  8587. D.SetIdentifier(Ident, IdentLoc);
  8588. D.takeAttributes(Attrs, AttrEnd);
  8589. ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
  8590. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
  8591. EmptyAttrs, IdentLoc);
  8592. Decl *Var = ActOnDeclarator(S, D);
  8593. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  8594. FinalizeDeclaration(Var);
  8595. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  8596. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  8597. }
  8598. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  8599. if (var->isInvalidDecl()) return;
  8600. // In ARC, don't allow jumps past the implicit initialization of a
  8601. // local retaining variable.
  8602. if (getLangOpts().ObjCAutoRefCount &&
  8603. var->hasLocalStorage()) {
  8604. switch (var->getType().getObjCLifetime()) {
  8605. case Qualifiers::OCL_None:
  8606. case Qualifiers::OCL_ExplicitNone:
  8607. case Qualifiers::OCL_Autoreleasing:
  8608. break;
  8609. case Qualifiers::OCL_Weak:
  8610. case Qualifiers::OCL_Strong:
  8611. getCurFunction()->setHasBranchProtectedScope();
  8612. break;
  8613. }
  8614. }
  8615. // Warn about externally-visible variables being defined without a
  8616. // prior declaration. We only want to do this for global
  8617. // declarations, but we also specifically need to avoid doing it for
  8618. // class members because the linkage of an anonymous class can
  8619. // change if it's later given a typedef name.
  8620. if (var->isThisDeclarationADefinition() &&
  8621. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  8622. var->isExternallyVisible() && var->hasLinkage() &&
  8623. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  8624. var->getLocation())) {
  8625. // Find a previous declaration that's not a definition.
  8626. VarDecl *prev = var->getPreviousDecl();
  8627. while (prev && prev->isThisDeclarationADefinition())
  8628. prev = prev->getPreviousDecl();
  8629. if (!prev)
  8630. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  8631. }
  8632. if (var->getTLSKind() == VarDecl::TLS_Static) {
  8633. const Expr *Culprit;
  8634. if (var->getType().isDestructedType()) {
  8635. // GNU C++98 edits for __thread, [basic.start.term]p3:
  8636. // The type of an object with thread storage duration shall not
  8637. // have a non-trivial destructor.
  8638. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  8639. if (getLangOpts().CPlusPlus11)
  8640. Diag(var->getLocation(), diag::note_use_thread_local);
  8641. } else if (getLangOpts().CPlusPlus && var->hasInit() &&
  8642. !var->getInit()->isConstantInitializer(
  8643. Context, var->getType()->isReferenceType(), &Culprit)) {
  8644. // GNU C++98 edits for __thread, [basic.start.init]p4:
  8645. // An object of thread storage duration shall not require dynamic
  8646. // initialization.
  8647. // FIXME: Need strict checking here.
  8648. Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
  8649. << Culprit->getSourceRange();
  8650. if (getLangOpts().CPlusPlus11)
  8651. Diag(var->getLocation(), diag::note_use_thread_local);
  8652. }
  8653. }
  8654. // Apply section attributes and pragmas to global variables.
  8655. bool GlobalStorage = var->hasGlobalStorage();
  8656. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  8657. ActiveTemplateInstantiations.empty()) {
  8658. PragmaStack<StringLiteral *> *Stack = nullptr;
  8659. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  8660. if (var->getType().isConstQualified())
  8661. Stack = &ConstSegStack;
  8662. else if (!var->getInit()) {
  8663. Stack = &BSSSegStack;
  8664. SectionFlags |= ASTContext::PSF_Write;
  8665. } else {
  8666. Stack = &DataSegStack;
  8667. SectionFlags |= ASTContext::PSF_Write;
  8668. }
  8669. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  8670. var->addAttr(SectionAttr::CreateImplicit(
  8671. Context, SectionAttr::Declspec_allocate,
  8672. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  8673. }
  8674. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  8675. if (UnifySection(SA->getName(), SectionFlags, var))
  8676. var->dropAttr<SectionAttr>();
  8677. // Apply the init_seg attribute if this has an initializer. If the
  8678. // initializer turns out to not be dynamic, we'll end up ignoring this
  8679. // attribute.
  8680. if (CurInitSeg && var->getInit())
  8681. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  8682. CurInitSegLoc));
  8683. }
  8684. // All the following checks are C++ only.
  8685. if (!getLangOpts().CPlusPlus) return;
  8686. QualType type = var->getType();
  8687. if (type->isDependentType()) return;
  8688. // __block variables might require us to capture a copy-initializer.
  8689. if (var->hasAttr<BlocksAttr>()) {
  8690. // It's currently invalid to ever have a __block variable with an
  8691. // array type; should we diagnose that here?
  8692. // Regardless, we don't want to ignore array nesting when
  8693. // constructing this copy.
  8694. if (type->isStructureOrClassType()) {
  8695. EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
  8696. SourceLocation poi = var->getLocation();
  8697. Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
  8698. ExprResult result
  8699. = PerformMoveOrCopyInitialization(
  8700. InitializedEntity::InitializeBlock(poi, type, false),
  8701. var, var->getType(), varRef, /*AllowNRVO=*/true);
  8702. if (!result.isInvalid()) {
  8703. result = MaybeCreateExprWithCleanups(result);
  8704. Expr *init = result.getAs<Expr>();
  8705. Context.setBlockVarCopyInits(var, init);
  8706. }
  8707. }
  8708. }
  8709. Expr *Init = var->getInit();
  8710. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  8711. QualType baseType = Context.getBaseElementType(type);
  8712. if (!var->getDeclContext()->isDependentContext() &&
  8713. Init && !Init->isValueDependent()) {
  8714. if (IsGlobal && !var->isConstexpr() &&
  8715. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  8716. var->getLocation())) {
  8717. // Warn about globals which don't have a constant initializer. Don't
  8718. // warn about globals with a non-trivial destructor because we already
  8719. // warned about them.
  8720. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  8721. if (!(RD && !RD->hasTrivialDestructor()) &&
  8722. !Init->isConstantInitializer(Context, baseType->isReferenceType()))
  8723. Diag(var->getLocation(), diag::warn_global_constructor)
  8724. << Init->getSourceRange();
  8725. }
  8726. if (var->isConstexpr()) {
  8727. SmallVector<PartialDiagnosticAt, 8> Notes;
  8728. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  8729. SourceLocation DiagLoc = var->getLocation();
  8730. // If the note doesn't add any useful information other than a source
  8731. // location, fold it into the primary diagnostic.
  8732. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  8733. diag::note_invalid_subexpr_in_const_expr) {
  8734. DiagLoc = Notes[0].first;
  8735. Notes.clear();
  8736. }
  8737. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  8738. << var << Init->getSourceRange();
  8739. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  8740. Diag(Notes[I].first, Notes[I].second);
  8741. }
  8742. } else if (var->isUsableInConstantExpressions(Context)) {
  8743. // Check whether the initializer of a const variable of integral or
  8744. // enumeration type is an ICE now, since we can't tell whether it was
  8745. // initialized by a constant expression if we check later.
  8746. var->checkInitIsICE();
  8747. }
  8748. }
  8749. // Require the destructor.
  8750. if (const RecordType *recordType = baseType->getAs<RecordType>())
  8751. FinalizeVarWithDestructor(var, recordType);
  8752. }
  8753. /// \brief Determines if a variable's alignment is dependent.
  8754. static bool hasDependentAlignment(VarDecl *VD) {
  8755. if (VD->getType()->isDependentType())
  8756. return true;
  8757. for (auto *I : VD->specific_attrs<AlignedAttr>())
  8758. if (I->isAlignmentDependent())
  8759. return true;
  8760. return false;
  8761. }
  8762. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  8763. /// any semantic actions necessary after any initializer has been attached.
  8764. void
  8765. Sema::FinalizeDeclaration(Decl *ThisDecl) {
  8766. // Note that we are no longer parsing the initializer for this declaration.
  8767. ParsingInitForAutoVars.erase(ThisDecl);
  8768. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  8769. if (!VD)
  8770. return;
  8771. checkAttributesAfterMerging(*this, *VD);
  8772. // Perform TLS alignment check here after attributes attached to the variable
  8773. // which may affect the alignment have been processed. Only perform the check
  8774. // if the target has a maximum TLS alignment (zero means no constraints).
  8775. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  8776. // Protect the check so that it's not performed on dependent types and
  8777. // dependent alignments (we can't determine the alignment in that case).
  8778. if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
  8779. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  8780. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  8781. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  8782. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  8783. << (unsigned)MaxAlignChars.getQuantity();
  8784. }
  8785. }
  8786. }
  8787. // Static locals inherit dll attributes from their function.
  8788. if (VD->isStaticLocal()) {
  8789. if (FunctionDecl *FD =
  8790. dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  8791. if (Attr *A = getDLLAttr(FD)) {
  8792. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  8793. NewAttr->setInherited(true);
  8794. VD->addAttr(NewAttr);
  8795. }
  8796. }
  8797. }
  8798. // Grab the dllimport or dllexport attribute off of the VarDecl.
  8799. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  8800. // Imported static data members cannot be defined out-of-line.
  8801. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  8802. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  8803. VD->isThisDeclarationADefinition()) {
  8804. // We allow definitions of dllimport class template static data members
  8805. // with a warning.
  8806. CXXRecordDecl *Context =
  8807. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  8808. bool IsClassTemplateMember =
  8809. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  8810. Context->getDescribedClassTemplate();
  8811. Diag(VD->getLocation(),
  8812. IsClassTemplateMember
  8813. ? diag::warn_attribute_dllimport_static_field_definition
  8814. : diag::err_attribute_dllimport_static_field_definition);
  8815. Diag(IA->getLocation(), diag::note_attribute);
  8816. if (!IsClassTemplateMember)
  8817. VD->setInvalidDecl();
  8818. }
  8819. }
  8820. // dllimport/dllexport variables cannot be thread local, their TLS index
  8821. // isn't exported with the variable.
  8822. if (DLLAttr && VD->getTLSKind()) {
  8823. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  8824. if (F && getDLLAttr(F)) {
  8825. assert(VD->isStaticLocal());
  8826. // But if this is a static local in a dlimport/dllexport function, the
  8827. // function will never be inlined, which means the var would never be
  8828. // imported, so having it marked import/export is safe.
  8829. } else {
  8830. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  8831. << DLLAttr;
  8832. VD->setInvalidDecl();
  8833. }
  8834. }
  8835. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  8836. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  8837. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  8838. VD->dropAttr<UsedAttr>();
  8839. }
  8840. }
  8841. const DeclContext *DC = VD->getDeclContext();
  8842. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8843. // member, set the visibility of this variable.
  8844. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  8845. AddPushedVisibilityAttribute(VD);
  8846. // FIXME: Warn on unused templates.
  8847. if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
  8848. !isa<VarTemplatePartialSpecializationDecl>(VD))
  8849. MarkUnusedFileScopedDecl(VD);
  8850. // Now we have parsed the initializer and can update the table of magic
  8851. // tag values.
  8852. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  8853. !VD->getType()->isIntegralOrEnumerationType())
  8854. return;
  8855. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  8856. const Expr *MagicValueExpr = VD->getInit();
  8857. if (!MagicValueExpr) {
  8858. continue;
  8859. }
  8860. llvm::APSInt MagicValueInt;
  8861. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  8862. Diag(I->getRange().getBegin(),
  8863. diag::err_type_tag_for_datatype_not_ice)
  8864. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  8865. continue;
  8866. }
  8867. if (MagicValueInt.getActiveBits() > 64) {
  8868. Diag(I->getRange().getBegin(),
  8869. diag::err_type_tag_for_datatype_too_large)
  8870. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  8871. continue;
  8872. }
  8873. uint64_t MagicValue = MagicValueInt.getZExtValue();
  8874. RegisterTypeTagForDatatype(I->getArgumentKind(),
  8875. MagicValue,
  8876. I->getMatchingCType(),
  8877. I->getLayoutCompatible(),
  8878. I->getMustBeNull());
  8879. }
  8880. }
  8881. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  8882. ArrayRef<Decl *> Group) {
  8883. SmallVector<Decl*, 8> Decls;
  8884. if (DS.isTypeSpecOwned())
  8885. Decls.push_back(DS.getRepAsDecl());
  8886. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  8887. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  8888. if (Decl *D = Group[i]) {
  8889. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
  8890. if (!FirstDeclaratorInGroup)
  8891. FirstDeclaratorInGroup = DD;
  8892. Decls.push_back(D);
  8893. }
  8894. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  8895. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  8896. handleTagNumbering(Tag, S);
  8897. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  8898. getLangOpts().CPlusPlus)
  8899. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  8900. }
  8901. }
  8902. return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
  8903. }
  8904. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  8905. /// group, performing any necessary semantic checking.
  8906. Sema::DeclGroupPtrTy
  8907. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
  8908. bool TypeMayContainAuto) {
  8909. // C++0x [dcl.spec.auto]p7:
  8910. // If the type deduced for the template parameter U is not the same in each
  8911. // deduction, the program is ill-formed.
  8912. // FIXME: When initializer-list support is added, a distinction is needed
  8913. // between the deduced type U and the deduced type which 'auto' stands for.
  8914. // auto a = 0, b = { 1, 2, 3 };
  8915. // is legal because the deduced type U is 'int' in both cases.
  8916. if (TypeMayContainAuto && Group.size() > 1) {
  8917. QualType Deduced;
  8918. CanQualType DeducedCanon;
  8919. VarDecl *DeducedDecl = nullptr;
  8920. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  8921. if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
  8922. AutoType *AT = D->getType()->getContainedAutoType();
  8923. // Don't reissue diagnostics when instantiating a template.
  8924. if (AT && D->isInvalidDecl())
  8925. break;
  8926. QualType U = AT ? AT->getDeducedType() : QualType();
  8927. if (!U.isNull()) {
  8928. CanQualType UCanon = Context.getCanonicalType(U);
  8929. if (Deduced.isNull()) {
  8930. Deduced = U;
  8931. DeducedCanon = UCanon;
  8932. DeducedDecl = D;
  8933. } else if (DeducedCanon != UCanon) {
  8934. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  8935. diag::err_auto_different_deductions)
  8936. << (AT->isDecltypeAuto() ? 1 : 0)
  8937. << Deduced << DeducedDecl->getDeclName()
  8938. << U << D->getDeclName()
  8939. << DeducedDecl->getInit()->getSourceRange()
  8940. << D->getInit()->getSourceRange();
  8941. D->setInvalidDecl();
  8942. break;
  8943. }
  8944. }
  8945. }
  8946. }
  8947. }
  8948. ActOnDocumentableDecls(Group);
  8949. return DeclGroupPtrTy::make(
  8950. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  8951. }
  8952. void Sema::ActOnDocumentableDecl(Decl *D) {
  8953. ActOnDocumentableDecls(D);
  8954. }
  8955. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  8956. // Don't parse the comment if Doxygen diagnostics are ignored.
  8957. if (Group.empty() || !Group[0])
  8958. return;
  8959. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  8960. Group[0]->getLocation()) &&
  8961. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  8962. Group[0]->getLocation()))
  8963. return;
  8964. if (Group.size() >= 2) {
  8965. // This is a decl group. Normally it will contain only declarations
  8966. // produced from declarator list. But in case we have any definitions or
  8967. // additional declaration references:
  8968. // 'typedef struct S {} S;'
  8969. // 'typedef struct S *S;'
  8970. // 'struct S *pS;'
  8971. // FinalizeDeclaratorGroup adds these as separate declarations.
  8972. Decl *MaybeTagDecl = Group[0];
  8973. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  8974. Group = Group.slice(1);
  8975. }
  8976. }
  8977. // See if there are any new comments that are not attached to a decl.
  8978. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  8979. if (!Comments.empty() &&
  8980. !Comments.back()->isAttached()) {
  8981. // There is at least one comment that not attached to a decl.
  8982. // Maybe it should be attached to one of these decls?
  8983. //
  8984. // Note that this way we pick up not only comments that precede the
  8985. // declaration, but also comments that *follow* the declaration -- thanks to
  8986. // the lookahead in the lexer: we've consumed the semicolon and looked
  8987. // ahead through comments.
  8988. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  8989. Context.getCommentForDecl(Group[i], &PP);
  8990. }
  8991. }
  8992. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  8993. /// to introduce parameters into function prototype scope.
  8994. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  8995. const DeclSpec &DS = D.getDeclSpec();
  8996. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  8997. // C++03 [dcl.stc]p2 also permits 'auto'.
  8998. StorageClass SC = SC_None;
  8999. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  9000. SC = SC_Register;
  9001. } else if (getLangOpts().CPlusPlus &&
  9002. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  9003. SC = SC_Auto;
  9004. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  9005. Diag(DS.getStorageClassSpecLoc(),
  9006. diag::err_invalid_storage_class_in_func_decl);
  9007. D.getMutableDeclSpec().ClearStorageClassSpecs();
  9008. }
  9009. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  9010. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  9011. << DeclSpec::getSpecifierName(TSCS);
  9012. if (DS.isConstexprSpecified())
  9013. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  9014. << 0;
  9015. DiagnoseFunctionSpecifiers(DS);
  9016. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  9017. QualType parmDeclType = TInfo->getType();
  9018. if (getLangOpts().CPlusPlus) {
  9019. // Check that there are no default arguments inside the type of this
  9020. // parameter.
  9021. CheckExtraCXXDefaultArguments(D);
  9022. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  9023. if (D.getCXXScopeSpec().isSet()) {
  9024. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  9025. << D.getCXXScopeSpec().getRange();
  9026. D.getCXXScopeSpec().clear();
  9027. }
  9028. }
  9029. // Ensure we have a valid name
  9030. IdentifierInfo *II = nullptr;
  9031. if (D.hasName()) {
  9032. II = D.getIdentifier();
  9033. if (!II) {
  9034. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  9035. << GetNameForDeclarator(D).getName();
  9036. D.setInvalidType(true);
  9037. }
  9038. }
  9039. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  9040. if (II) {
  9041. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  9042. ForRedeclaration);
  9043. LookupName(R, S);
  9044. if (R.isSingleResult()) {
  9045. NamedDecl *PrevDecl = R.getFoundDecl();
  9046. if (PrevDecl->isTemplateParameter()) {
  9047. // Maybe we will complain about the shadowed template parameter.
  9048. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  9049. // Just pretend that we didn't see the previous declaration.
  9050. PrevDecl = nullptr;
  9051. } else if (S->isDeclScope(PrevDecl)) {
  9052. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  9053. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  9054. // Recover by removing the name
  9055. II = nullptr;
  9056. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  9057. D.setInvalidType(true);
  9058. }
  9059. }
  9060. }
  9061. // Temporarily put parameter variables in the translation unit, not
  9062. // the enclosing context. This prevents them from accidentally
  9063. // looking like class members in C++.
  9064. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  9065. D.getLocStart(),
  9066. D.getIdentifierLoc(), II,
  9067. parmDeclType, TInfo,
  9068. SC);
  9069. if (D.isInvalidType())
  9070. New->setInvalidDecl();
  9071. assert(S->isFunctionPrototypeScope());
  9072. assert(S->getFunctionPrototypeDepth() >= 1);
  9073. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  9074. S->getNextFunctionPrototypeIndex());
  9075. // Add the parameter declaration into this scope.
  9076. S->AddDecl(New);
  9077. if (II)
  9078. IdResolver.AddDecl(New);
  9079. ProcessDeclAttributes(S, New, D);
  9080. if (D.getDeclSpec().isModulePrivateSpecified())
  9081. Diag(New->getLocation(), diag::err_module_private_local)
  9082. << 1 << New->getDeclName()
  9083. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  9084. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  9085. if (New->hasAttr<BlocksAttr>()) {
  9086. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  9087. }
  9088. return New;
  9089. }
  9090. /// \brief Synthesizes a variable for a parameter arising from a
  9091. /// typedef.
  9092. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  9093. SourceLocation Loc,
  9094. QualType T) {
  9095. /* FIXME: setting StartLoc == Loc.
  9096. Would it be worth to modify callers so as to provide proper source
  9097. location for the unnamed parameters, embedding the parameter's type? */
  9098. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  9099. T, Context.getTrivialTypeSourceInfo(T, Loc),
  9100. SC_None, nullptr);
  9101. Param->setImplicit();
  9102. return Param;
  9103. }
  9104. void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
  9105. ParmVarDecl * const *ParamEnd) {
  9106. // Don't diagnose unused-parameter errors in template instantiations; we
  9107. // will already have done so in the template itself.
  9108. if (!ActiveTemplateInstantiations.empty())
  9109. return;
  9110. for (; Param != ParamEnd; ++Param) {
  9111. if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
  9112. !(*Param)->hasAttr<UnusedAttr>()) {
  9113. Diag((*Param)->getLocation(), diag::warn_unused_parameter)
  9114. << (*Param)->getDeclName();
  9115. }
  9116. }
  9117. }
  9118. void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
  9119. ParmVarDecl * const *ParamEnd,
  9120. QualType ReturnTy,
  9121. NamedDecl *D) {
  9122. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  9123. return;
  9124. // Warn if the return value is pass-by-value and larger than the specified
  9125. // threshold.
  9126. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  9127. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  9128. if (Size > LangOpts.NumLargeByValueCopy)
  9129. Diag(D->getLocation(), diag::warn_return_value_size)
  9130. << D->getDeclName() << Size;
  9131. }
  9132. // Warn if any parameter is pass-by-value and larger than the specified
  9133. // threshold.
  9134. for (; Param != ParamEnd; ++Param) {
  9135. QualType T = (*Param)->getType();
  9136. if (T->isDependentType() || !T.isPODType(Context))
  9137. continue;
  9138. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  9139. if (Size > LangOpts.NumLargeByValueCopy)
  9140. Diag((*Param)->getLocation(), diag::warn_parameter_size)
  9141. << (*Param)->getDeclName() << Size;
  9142. }
  9143. }
  9144. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  9145. SourceLocation NameLoc, IdentifierInfo *Name,
  9146. QualType T, TypeSourceInfo *TSInfo,
  9147. StorageClass SC) {
  9148. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  9149. if (getLangOpts().ObjCAutoRefCount &&
  9150. T.getObjCLifetime() == Qualifiers::OCL_None &&
  9151. T->isObjCLifetimeType()) {
  9152. Qualifiers::ObjCLifetime lifetime;
  9153. // Special cases for arrays:
  9154. // - if it's const, use __unsafe_unretained
  9155. // - otherwise, it's an error
  9156. if (T->isArrayType()) {
  9157. if (!T.isConstQualified()) {
  9158. DelayedDiagnostics.add(
  9159. sema::DelayedDiagnostic::makeForbiddenType(
  9160. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  9161. }
  9162. lifetime = Qualifiers::OCL_ExplicitNone;
  9163. } else {
  9164. lifetime = T->getObjCARCImplicitLifetime();
  9165. }
  9166. T = Context.getLifetimeQualifiedType(T, lifetime);
  9167. }
  9168. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  9169. Context.getAdjustedParameterType(T),
  9170. TSInfo, SC, nullptr);
  9171. // Parameters can not be abstract class types.
  9172. // For record types, this is done by the AbstractClassUsageDiagnoser once
  9173. // the class has been completely parsed.
  9174. if (!CurContext->isRecord() &&
  9175. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  9176. AbstractParamType))
  9177. New->setInvalidDecl();
  9178. // Parameter declarators cannot be interface types. All ObjC objects are
  9179. // passed by reference.
  9180. if (T->isObjCObjectType()) {
  9181. SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
  9182. Diag(NameLoc,
  9183. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  9184. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  9185. T = Context.getObjCObjectPointerType(T);
  9186. New->setType(T);
  9187. }
  9188. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  9189. // duration shall not be qualified by an address-space qualifier."
  9190. // Since all parameters have automatic store duration, they can not have
  9191. // an address space.
  9192. if (T.getAddressSpace() != 0) {
  9193. // OpenCL allows function arguments declared to be an array of a type
  9194. // to be qualified with an address space.
  9195. if (!(getLangOpts().OpenCL && T->isArrayType())) {
  9196. Diag(NameLoc, diag::err_arg_with_address_space);
  9197. New->setInvalidDecl();
  9198. }
  9199. }
  9200. return New;
  9201. }
  9202. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  9203. SourceLocation LocAfterDecls) {
  9204. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  9205. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  9206. // for a K&R function.
  9207. if (!FTI.hasPrototype) {
  9208. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  9209. --i;
  9210. if (FTI.Params[i].Param == nullptr) {
  9211. SmallString<256> Code;
  9212. llvm::raw_svector_ostream(Code)
  9213. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  9214. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  9215. << FTI.Params[i].Ident
  9216. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  9217. // Implicitly declare the argument as type 'int' for lack of a better
  9218. // type.
  9219. AttributeFactory attrs;
  9220. DeclSpec DS(attrs);
  9221. const char* PrevSpec; // unused
  9222. unsigned DiagID; // unused
  9223. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  9224. DiagID, Context.getPrintingPolicy());
  9225. // Use the identifier location for the type source range.
  9226. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  9227. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  9228. Declarator ParamD(DS, Declarator::KNRTypeListContext);
  9229. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  9230. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  9231. }
  9232. }
  9233. }
  9234. }
  9235. Decl *
  9236. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  9237. MultiTemplateParamsArg TemplateParameterLists,
  9238. SkipBodyInfo *SkipBody) {
  9239. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  9240. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  9241. Scope *ParentScope = FnBodyScope->getParent();
  9242. D.setFunctionDefinitionKind(FDK_Definition);
  9243. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  9244. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  9245. }
  9246. void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
  9247. Consumer.HandleInlineMethodDefinition(D);
  9248. }
  9249. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  9250. const FunctionDecl*& PossibleZeroParamPrototype) {
  9251. // Don't warn about invalid declarations.
  9252. if (FD->isInvalidDecl())
  9253. return false;
  9254. // Or declarations that aren't global.
  9255. if (!FD->isGlobal())
  9256. return false;
  9257. // Don't warn about C++ member functions.
  9258. if (isa<CXXMethodDecl>(FD))
  9259. return false;
  9260. // Don't warn about 'main'.
  9261. if (FD->isMain())
  9262. return false;
  9263. // Don't warn about inline functions.
  9264. if (FD->isInlined())
  9265. return false;
  9266. // Don't warn about function templates.
  9267. if (FD->getDescribedFunctionTemplate())
  9268. return false;
  9269. // Don't warn about function template specializations.
  9270. if (FD->isFunctionTemplateSpecialization())
  9271. return false;
  9272. // Don't warn for OpenCL kernels.
  9273. if (FD->hasAttr<OpenCLKernelAttr>())
  9274. return false;
  9275. // Don't warn on explicitly deleted functions.
  9276. if (FD->isDeleted())
  9277. return false;
  9278. bool MissingPrototype = true;
  9279. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  9280. Prev; Prev = Prev->getPreviousDecl()) {
  9281. // Ignore any declarations that occur in function or method
  9282. // scope, because they aren't visible from the header.
  9283. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  9284. continue;
  9285. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  9286. if (FD->getNumParams() == 0)
  9287. PossibleZeroParamPrototype = Prev;
  9288. break;
  9289. }
  9290. return MissingPrototype;
  9291. }
  9292. void
  9293. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  9294. const FunctionDecl *EffectiveDefinition,
  9295. SkipBodyInfo *SkipBody) {
  9296. // Don't complain if we're in GNU89 mode and the previous definition
  9297. // was an extern inline function.
  9298. const FunctionDecl *Definition = EffectiveDefinition;
  9299. if (!Definition)
  9300. if (!FD->isDefined(Definition))
  9301. return;
  9302. if (canRedefineFunction(Definition, getLangOpts()))
  9303. return;
  9304. // If we don't have a visible definition of the function, and it's inline or
  9305. // a template, skip the new definition.
  9306. if (SkipBody && !hasVisibleDefinition(Definition) &&
  9307. (Definition->getFormalLinkage() == InternalLinkage ||
  9308. Definition->isInlined() ||
  9309. Definition->getDescribedFunctionTemplate() ||
  9310. Definition->getNumTemplateParameterLists())) {
  9311. SkipBody->ShouldSkip = true;
  9312. if (auto *TD = Definition->getDescribedFunctionTemplate())
  9313. makeMergedDefinitionVisible(TD, FD->getLocation());
  9314. else
  9315. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
  9316. FD->getLocation());
  9317. return;
  9318. }
  9319. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  9320. Definition->getStorageClass() == SC_Extern)
  9321. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  9322. << FD->getDeclName() << getLangOpts().CPlusPlus;
  9323. else
  9324. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  9325. Diag(Definition->getLocation(), diag::note_previous_definition);
  9326. FD->setInvalidDecl();
  9327. }
  9328. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  9329. Sema &S) {
  9330. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  9331. LambdaScopeInfo *LSI = S.PushLambdaScope();
  9332. LSI->CallOperator = CallOperator;
  9333. LSI->Lambda = LambdaClass;
  9334. LSI->ReturnType = CallOperator->getReturnType();
  9335. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  9336. if (LCD == LCD_None)
  9337. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  9338. else if (LCD == LCD_ByCopy)
  9339. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  9340. else if (LCD == LCD_ByRef)
  9341. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  9342. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  9343. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  9344. LSI->Mutable = !CallOperator->isConst();
  9345. // Add the captures to the LSI so they can be noted as already
  9346. // captured within tryCaptureVar.
  9347. auto I = LambdaClass->field_begin();
  9348. for (const auto &C : LambdaClass->captures()) {
  9349. if (C.capturesVariable()) {
  9350. VarDecl *VD = C.getCapturedVar();
  9351. if (VD->isInitCapture())
  9352. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  9353. QualType CaptureType = VD->getType();
  9354. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  9355. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  9356. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  9357. /*EllipsisLoc*/C.isPackExpansion()
  9358. ? C.getEllipsisLoc() : SourceLocation(),
  9359. CaptureType, /*Expr*/ nullptr);
  9360. } else if (C.capturesThis()) {
  9361. LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
  9362. S.getCurrentThisType(), /*Expr*/ nullptr);
  9363. } else {
  9364. LSI->addVLATypeCapture(C.getLocation(), I->getType());
  9365. }
  9366. ++I;
  9367. }
  9368. }
  9369. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  9370. SkipBodyInfo *SkipBody) {
  9371. // Clear the last template instantiation error context.
  9372. LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
  9373. if (!D)
  9374. return D;
  9375. FunctionDecl *FD = nullptr;
  9376. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  9377. FD = FunTmpl->getTemplatedDecl();
  9378. else
  9379. FD = cast<FunctionDecl>(D);
  9380. // See if this is a redefinition.
  9381. if (!FD->isLateTemplateParsed()) {
  9382. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  9383. // If we're skipping the body, we're done. Don't enter the scope.
  9384. if (SkipBody && SkipBody->ShouldSkip)
  9385. return D;
  9386. }
  9387. // If we are instantiating a generic lambda call operator, push
  9388. // a LambdaScopeInfo onto the function stack. But use the information
  9389. // that's already been calculated (ActOnLambdaExpr) to prime the current
  9390. // LambdaScopeInfo.
  9391. // When the template operator is being specialized, the LambdaScopeInfo,
  9392. // has to be properly restored so that tryCaptureVariable doesn't try
  9393. // and capture any new variables. In addition when calculating potential
  9394. // captures during transformation of nested lambdas, it is necessary to
  9395. // have the LSI properly restored.
  9396. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  9397. assert(ActiveTemplateInstantiations.size() &&
  9398. "There should be an active template instantiation on the stack "
  9399. "when instantiating a generic lambda!");
  9400. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  9401. }
  9402. else
  9403. // Enter a new function scope
  9404. PushFunctionScope();
  9405. // Builtin functions cannot be defined.
  9406. if (unsigned BuiltinID = FD->getBuiltinID()) {
  9407. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  9408. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  9409. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  9410. FD->setInvalidDecl();
  9411. }
  9412. }
  9413. // The return type of a function definition must be complete
  9414. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  9415. QualType ResultType = FD->getReturnType();
  9416. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  9417. !FD->isInvalidDecl() &&
  9418. RequireCompleteType(FD->getLocation(), ResultType,
  9419. diag::err_func_def_incomplete_result))
  9420. FD->setInvalidDecl();
  9421. if (FnBodyScope)
  9422. PushDeclContext(FnBodyScope, FD);
  9423. // Check the validity of our function parameters
  9424. CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
  9425. /*CheckParameterNames=*/true);
  9426. // Introduce our parameters into the function scope
  9427. for (auto Param : FD->params()) {
  9428. Param->setOwningFunction(FD);
  9429. // If this has an identifier, add it to the scope stack.
  9430. if (Param->getIdentifier() && FnBodyScope) {
  9431. CheckShadow(FnBodyScope, Param);
  9432. PushOnScopeChains(Param, FnBodyScope);
  9433. }
  9434. }
  9435. // If we had any tags defined in the function prototype,
  9436. // introduce them into the function scope.
  9437. if (FnBodyScope) {
  9438. for (ArrayRef<NamedDecl *>::iterator
  9439. I = FD->getDeclsInPrototypeScope().begin(),
  9440. E = FD->getDeclsInPrototypeScope().end();
  9441. I != E; ++I) {
  9442. NamedDecl *D = *I;
  9443. // Some of these decls (like enums) may have been pinned to the
  9444. // translation unit for lack of a real context earlier. If so, remove
  9445. // from the translation unit and reattach to the current context.
  9446. if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
  9447. // Is the decl actually in the context?
  9448. for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
  9449. if (DI == D) {
  9450. Context.getTranslationUnitDecl()->removeDecl(D);
  9451. break;
  9452. }
  9453. }
  9454. // Either way, reassign the lexical decl context to our FunctionDecl.
  9455. D->setLexicalDeclContext(CurContext);
  9456. }
  9457. // If the decl has a non-null name, make accessible in the current scope.
  9458. if (!D->getName().empty())
  9459. PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
  9460. // Similarly, dive into enums and fish their constants out, making them
  9461. // accessible in this scope.
  9462. if (auto *ED = dyn_cast<EnumDecl>(D)) {
  9463. for (auto *EI : ED->enumerators())
  9464. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  9465. }
  9466. }
  9467. }
  9468. // Ensure that the function's exception specification is instantiated.
  9469. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  9470. ResolveExceptionSpec(D->getLocation(), FPT);
  9471. // dllimport cannot be applied to non-inline function definitions.
  9472. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  9473. !FD->isTemplateInstantiation()) {
  9474. assert(!FD->hasAttr<DLLExportAttr>());
  9475. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  9476. FD->setInvalidDecl();
  9477. return D;
  9478. }
  9479. // We want to attach documentation to original Decl (which might be
  9480. // a function template).
  9481. ActOnDocumentableDecl(D);
  9482. if (getCurLexicalContext()->isObjCContainer() &&
  9483. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  9484. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  9485. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  9486. return D;
  9487. }
  9488. /// \brief Given the set of return statements within a function body,
  9489. /// compute the variables that are subject to the named return value
  9490. /// optimization.
  9491. ///
  9492. /// Each of the variables that is subject to the named return value
  9493. /// optimization will be marked as NRVO variables in the AST, and any
  9494. /// return statement that has a marked NRVO variable as its NRVO candidate can
  9495. /// use the named return value optimization.
  9496. ///
  9497. /// This function applies a very simplistic algorithm for NRVO: if every return
  9498. /// statement in the scope of a variable has the same NRVO candidate, that
  9499. /// candidate is an NRVO variable.
  9500. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  9501. ReturnStmt **Returns = Scope->Returns.data();
  9502. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  9503. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  9504. if (!NRVOCandidate->isNRVOVariable())
  9505. Returns[I]->setNRVOCandidate(nullptr);
  9506. }
  9507. }
  9508. }
  9509. bool Sema::canDelayFunctionBody(const Declarator &D) {
  9510. // We can't delay parsing the body of a constexpr function template (yet).
  9511. if (D.getDeclSpec().isConstexprSpecified())
  9512. return false;
  9513. // We can't delay parsing the body of a function template with a deduced
  9514. // return type (yet).
  9515. if (D.getDeclSpec().containsPlaceholderType()) {
  9516. // If the placeholder introduces a non-deduced trailing return type,
  9517. // we can still delay parsing it.
  9518. if (D.getNumTypeObjects()) {
  9519. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  9520. if (Outer.Kind == DeclaratorChunk::Function &&
  9521. Outer.Fun.hasTrailingReturnType()) {
  9522. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  9523. return Ty.isNull() || !Ty->isUndeducedType();
  9524. }
  9525. }
  9526. return false;
  9527. }
  9528. return true;
  9529. }
  9530. bool Sema::canSkipFunctionBody(Decl *D) {
  9531. // We cannot skip the body of a function (or function template) which is
  9532. // constexpr, since we may need to evaluate its body in order to parse the
  9533. // rest of the file.
  9534. // We cannot skip the body of a function with an undeduced return type,
  9535. // because any callers of that function need to know the type.
  9536. if (const FunctionDecl *FD = D->getAsFunction())
  9537. if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
  9538. return false;
  9539. return Consumer.shouldSkipFunctionBody(D);
  9540. }
  9541. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  9542. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
  9543. FD->setHasSkippedBody();
  9544. else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
  9545. MD->setHasSkippedBody();
  9546. return ActOnFinishFunctionBody(Decl, nullptr);
  9547. }
  9548. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  9549. return ActOnFinishFunctionBody(D, BodyArg, false);
  9550. }
  9551. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  9552. bool IsInstantiation) {
  9553. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  9554. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  9555. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  9556. if (FD) {
  9557. FD->setBody(Body);
  9558. if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
  9559. !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
  9560. // If the function has a deduced result type but contains no 'return'
  9561. // statements, the result type as written must be exactly 'auto', and
  9562. // the deduced result type is 'void'.
  9563. if (!FD->getReturnType()->getAs<AutoType>()) {
  9564. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  9565. << FD->getReturnType();
  9566. FD->setInvalidDecl();
  9567. } else {
  9568. // Substitute 'void' for the 'auto' in the type.
  9569. TypeLoc ResultType = getReturnTypeLoc(FD);
  9570. Context.adjustDeducedFunctionResultType(
  9571. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  9572. }
  9573. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  9574. auto *LSI = getCurLambda();
  9575. if (LSI->HasImplicitReturnType) {
  9576. deduceClosureReturnType(*LSI);
  9577. // C++11 [expr.prim.lambda]p4:
  9578. // [...] if there are no return statements in the compound-statement
  9579. // [the deduced type is] the type void
  9580. QualType RetType =
  9581. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  9582. // Update the return type to the deduced type.
  9583. const FunctionProtoType *Proto =
  9584. FD->getType()->getAs<FunctionProtoType>();
  9585. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  9586. Proto->getExtProtoInfo()));
  9587. }
  9588. }
  9589. // The only way to be included in UndefinedButUsed is if there is an
  9590. // ODR use before the definition. Avoid the expensive map lookup if this
  9591. // is the first declaration.
  9592. if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
  9593. if (!FD->isExternallyVisible())
  9594. UndefinedButUsed.erase(FD);
  9595. else if (FD->isInlined() &&
  9596. !LangOpts.GNUInline &&
  9597. (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
  9598. UndefinedButUsed.erase(FD);
  9599. }
  9600. // If the function implicitly returns zero (like 'main') or is naked,
  9601. // don't complain about missing return statements.
  9602. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  9603. WP.disableCheckFallThrough();
  9604. // MSVC permits the use of pure specifier (=0) on function definition,
  9605. // defined at class scope, warn about this non-standard construct.
  9606. if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
  9607. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  9608. if (!FD->isInvalidDecl()) {
  9609. // Don't diagnose unused parameters of defaulted or deleted functions.
  9610. if (!FD->isDeleted() && !FD->isDefaulted())
  9611. DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
  9612. DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
  9613. FD->getReturnType(), FD);
  9614. // If this is a structor, we need a vtable.
  9615. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  9616. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  9617. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  9618. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  9619. // Try to apply the named return value optimization. We have to check
  9620. // if we can do this here because lambdas keep return statements around
  9621. // to deduce an implicit return type.
  9622. if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
  9623. !FD->isDependentContext())
  9624. computeNRVO(Body, getCurFunction());
  9625. }
  9626. // GNU warning -Wmissing-prototypes:
  9627. // Warn if a global function is defined without a previous
  9628. // prototype declaration. This warning is issued even if the
  9629. // definition itself provides a prototype. The aim is to detect
  9630. // global functions that fail to be declared in header files.
  9631. const FunctionDecl *PossibleZeroParamPrototype = nullptr;
  9632. if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
  9633. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  9634. if (PossibleZeroParamPrototype) {
  9635. // We found a declaration that is not a prototype,
  9636. // but that could be a zero-parameter prototype
  9637. if (TypeSourceInfo *TI =
  9638. PossibleZeroParamPrototype->getTypeSourceInfo()) {
  9639. TypeLoc TL = TI->getTypeLoc();
  9640. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  9641. Diag(PossibleZeroParamPrototype->getLocation(),
  9642. diag::note_declaration_not_a_prototype)
  9643. << PossibleZeroParamPrototype
  9644. << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
  9645. }
  9646. }
  9647. }
  9648. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  9649. const CXXMethodDecl *KeyFunction;
  9650. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  9651. MD->isVirtual() &&
  9652. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  9653. MD == KeyFunction->getCanonicalDecl()) {
  9654. // Update the key-function state if necessary for this ABI.
  9655. if (FD->isInlined() &&
  9656. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  9657. Context.setNonKeyFunction(MD);
  9658. // If the newly-chosen key function is already defined, then we
  9659. // need to mark the vtable as used retroactively.
  9660. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  9661. const FunctionDecl *Definition;
  9662. if (KeyFunction && KeyFunction->isDefined(Definition))
  9663. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  9664. } else {
  9665. // We just defined they key function; mark the vtable as used.
  9666. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  9667. }
  9668. }
  9669. }
  9670. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  9671. "Function parsing confused");
  9672. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  9673. assert(MD == getCurMethodDecl() && "Method parsing confused");
  9674. MD->setBody(Body);
  9675. if (!MD->isInvalidDecl()) {
  9676. DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
  9677. DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
  9678. MD->getReturnType(), MD);
  9679. if (Body)
  9680. computeNRVO(Body, getCurFunction());
  9681. }
  9682. if (getCurFunction()->ObjCShouldCallSuper) {
  9683. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
  9684. << MD->getSelector().getAsString();
  9685. getCurFunction()->ObjCShouldCallSuper = false;
  9686. }
  9687. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  9688. const ObjCMethodDecl *InitMethod = nullptr;
  9689. bool isDesignated =
  9690. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  9691. assert(isDesignated && InitMethod);
  9692. (void)isDesignated;
  9693. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  9694. auto IFace = MD->getClassInterface();
  9695. if (!IFace)
  9696. return false;
  9697. auto SuperD = IFace->getSuperClass();
  9698. if (!SuperD)
  9699. return false;
  9700. return SuperD->getIdentifier() ==
  9701. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  9702. };
  9703. // Don't issue this warning for unavailable inits or direct subclasses
  9704. // of NSObject.
  9705. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  9706. Diag(MD->getLocation(),
  9707. diag::warn_objc_designated_init_missing_super_call);
  9708. Diag(InitMethod->getLocation(),
  9709. diag::note_objc_designated_init_marked_here);
  9710. }
  9711. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  9712. }
  9713. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  9714. // Don't issue this warning for unavaialable inits.
  9715. if (!MD->isUnavailable())
  9716. Diag(MD->getLocation(),
  9717. diag::warn_objc_secondary_init_missing_init_call);
  9718. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  9719. }
  9720. } else {
  9721. return nullptr;
  9722. }
  9723. assert(!getCurFunction()->ObjCShouldCallSuper &&
  9724. "This should only be set for ObjC methods, which should have been "
  9725. "handled in the block above.");
  9726. // Verify and clean out per-function state.
  9727. if (Body && (!FD || !FD->isDefaulted())) {
  9728. // C++ constructors that have function-try-blocks can't have return
  9729. // statements in the handlers of that block. (C++ [except.handle]p14)
  9730. // Verify this.
  9731. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  9732. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  9733. // Verify that gotos and switch cases don't jump into scopes illegally.
  9734. if (getCurFunction()->NeedsScopeChecking() &&
  9735. !PP.isCodeCompletionEnabled())
  9736. DiagnoseInvalidJumps(Body);
  9737. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  9738. if (!Destructor->getParent()->isDependentType())
  9739. CheckDestructor(Destructor);
  9740. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  9741. Destructor->getParent());
  9742. }
  9743. // If any errors have occurred, clear out any temporaries that may have
  9744. // been leftover. This ensures that these temporaries won't be picked up for
  9745. // deletion in some later function.
  9746. if (getDiagnostics().hasErrorOccurred() ||
  9747. getDiagnostics().getSuppressAllDiagnostics()) {
  9748. DiscardCleanupsInEvaluationContext();
  9749. }
  9750. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  9751. !isa<FunctionTemplateDecl>(dcl)) {
  9752. // Since the body is valid, issue any analysis-based warnings that are
  9753. // enabled.
  9754. ActivePolicy = &WP;
  9755. }
  9756. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  9757. (!CheckConstexprFunctionDecl(FD) ||
  9758. !CheckConstexprFunctionBody(FD, Body)))
  9759. FD->setInvalidDecl();
  9760. if (FD && FD->hasAttr<NakedAttr>()) {
  9761. for (const Stmt *S : Body->children()) {
  9762. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  9763. Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
  9764. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  9765. FD->setInvalidDecl();
  9766. break;
  9767. }
  9768. }
  9769. }
  9770. assert(ExprCleanupObjects.size() ==
  9771. ExprEvalContexts.back().NumCleanupObjects &&
  9772. "Leftover temporaries in function");
  9773. assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
  9774. assert(MaybeODRUseExprs.empty() &&
  9775. "Leftover expressions for odr-use checking");
  9776. }
  9777. if (!IsInstantiation)
  9778. PopDeclContext();
  9779. PopFunctionScopeInfo(ActivePolicy, dcl);
  9780. // If any errors have occurred, clear out any temporaries that may have
  9781. // been leftover. This ensures that these temporaries won't be picked up for
  9782. // deletion in some later function.
  9783. if (getDiagnostics().hasErrorOccurred()) {
  9784. DiscardCleanupsInEvaluationContext();
  9785. }
  9786. return dcl;
  9787. }
  9788. /// When we finish delayed parsing of an attribute, we must attach it to the
  9789. /// relevant Decl.
  9790. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  9791. ParsedAttributes &Attrs) {
  9792. // Always attach attributes to the underlying decl.
  9793. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  9794. D = TD->getTemplatedDecl();
  9795. ProcessDeclAttributeList(S, D, Attrs.getList());
  9796. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  9797. if (Method->isStatic())
  9798. checkThisInStaticMemberFunctionAttributes(Method);
  9799. }
  9800. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  9801. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  9802. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  9803. IdentifierInfo &II, Scope *S) {
  9804. // Before we produce a declaration for an implicitly defined
  9805. // function, see whether there was a locally-scoped declaration of
  9806. // this name as a function or variable. If so, use that
  9807. // (non-visible) declaration, and complain about it.
  9808. if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
  9809. Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
  9810. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  9811. return ExternCPrev;
  9812. }
  9813. // Extension in C99. Legal in C90, but warn about it.
  9814. unsigned diag_id;
  9815. if (II.getName().startswith("__builtin_"))
  9816. diag_id = diag::warn_builtin_unknown;
  9817. else if (getLangOpts().C99)
  9818. diag_id = diag::ext_implicit_function_decl;
  9819. else
  9820. diag_id = diag::warn_implicit_function_decl;
  9821. Diag(Loc, diag_id) << &II;
  9822. // Because typo correction is expensive, only do it if the implicit
  9823. // function declaration is going to be treated as an error.
  9824. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  9825. TypoCorrection Corrected;
  9826. if (S &&
  9827. (Corrected = CorrectTypo(
  9828. DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
  9829. llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
  9830. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  9831. /*ErrorRecovery*/false);
  9832. }
  9833. // Set a Declarator for the implicit definition: int foo();
  9834. const char *Dummy;
  9835. AttributeFactory attrFactory;
  9836. DeclSpec DS(attrFactory);
  9837. unsigned DiagID;
  9838. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  9839. Context.getPrintingPolicy());
  9840. (void)Error; // Silence warning.
  9841. assert(!Error && "Error setting up implicit decl!");
  9842. SourceLocation NoLoc;
  9843. Declarator D(DS, Declarator::BlockContext);
  9844. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  9845. /*IsAmbiguous=*/false,
  9846. /*LParenLoc=*/NoLoc,
  9847. /*Params=*/nullptr,
  9848. /*NumParams=*/0,
  9849. /*EllipsisLoc=*/NoLoc,
  9850. /*RParenLoc=*/NoLoc,
  9851. /*TypeQuals=*/0,
  9852. /*RefQualifierIsLvalueRef=*/true,
  9853. /*RefQualifierLoc=*/NoLoc,
  9854. /*ConstQualifierLoc=*/NoLoc,
  9855. /*VolatileQualifierLoc=*/NoLoc,
  9856. /*RestrictQualifierLoc=*/NoLoc,
  9857. /*MutableLoc=*/NoLoc,
  9858. EST_None,
  9859. /*ESpecRange=*/SourceRange(),
  9860. /*Exceptions=*/nullptr,
  9861. /*ExceptionRanges=*/nullptr,
  9862. /*NumExceptions=*/0,
  9863. /*NoexceptExpr=*/nullptr,
  9864. /*ExceptionSpecTokens=*/nullptr,
  9865. Loc, Loc, D),
  9866. DS.getAttributes(),
  9867. SourceLocation());
  9868. D.SetIdentifier(&II, Loc);
  9869. // Insert this function into translation-unit scope.
  9870. DeclContext *PrevDC = CurContext;
  9871. CurContext = Context.getTranslationUnitDecl();
  9872. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
  9873. FD->setImplicit();
  9874. CurContext = PrevDC;
  9875. AddKnownFunctionAttributes(FD);
  9876. return FD;
  9877. }
  9878. /// \brief Adds any function attributes that we know a priori based on
  9879. /// the declaration of this function.
  9880. ///
  9881. /// These attributes can apply both to implicitly-declared builtins
  9882. /// (like __builtin___printf_chk) or to library-declared functions
  9883. /// like NSLog or printf.
  9884. ///
  9885. /// We need to check for duplicate attributes both here and where user-written
  9886. /// attributes are applied to declarations.
  9887. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  9888. if (FD->isInvalidDecl())
  9889. return;
  9890. // If this is a built-in function, map its builtin attributes to
  9891. // actual attributes.
  9892. if (unsigned BuiltinID = FD->getBuiltinID()) {
  9893. // Handle printf-formatting attributes.
  9894. unsigned FormatIdx;
  9895. bool HasVAListArg;
  9896. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  9897. if (!FD->hasAttr<FormatAttr>()) {
  9898. const char *fmt = "printf";
  9899. unsigned int NumParams = FD->getNumParams();
  9900. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  9901. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  9902. fmt = "NSString";
  9903. FD->addAttr(FormatAttr::CreateImplicit(Context,
  9904. &Context.Idents.get(fmt),
  9905. FormatIdx+1,
  9906. HasVAListArg ? 0 : FormatIdx+2,
  9907. FD->getLocation()));
  9908. }
  9909. }
  9910. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  9911. HasVAListArg)) {
  9912. if (!FD->hasAttr<FormatAttr>())
  9913. FD->addAttr(FormatAttr::CreateImplicit(Context,
  9914. &Context.Idents.get("scanf"),
  9915. FormatIdx+1,
  9916. HasVAListArg ? 0 : FormatIdx+2,
  9917. FD->getLocation()));
  9918. }
  9919. // Mark const if we don't care about errno and that is the only
  9920. // thing preventing the function from being const. This allows
  9921. // IRgen to use LLVM intrinsics for such functions.
  9922. if (!getLangOpts().MathErrno &&
  9923. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
  9924. if (!FD->hasAttr<ConstAttr>())
  9925. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  9926. }
  9927. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  9928. !FD->hasAttr<ReturnsTwiceAttr>())
  9929. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  9930. FD->getLocation()));
  9931. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  9932. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  9933. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  9934. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  9935. }
  9936. IdentifierInfo *Name = FD->getIdentifier();
  9937. if (!Name)
  9938. return;
  9939. if ((!getLangOpts().CPlusPlus &&
  9940. FD->getDeclContext()->isTranslationUnit()) ||
  9941. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  9942. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  9943. LinkageSpecDecl::lang_c)) {
  9944. // Okay: this could be a libc/libm/Objective-C function we know
  9945. // about.
  9946. } else
  9947. return;
  9948. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  9949. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  9950. // target-specific builtins, perhaps?
  9951. if (!FD->hasAttr<FormatAttr>())
  9952. FD->addAttr(FormatAttr::CreateImplicit(Context,
  9953. &Context.Idents.get("printf"), 2,
  9954. Name->isStr("vasprintf") ? 0 : 3,
  9955. FD->getLocation()));
  9956. }
  9957. if (Name->isStr("__CFStringMakeConstantString")) {
  9958. // We already have a __builtin___CFStringMakeConstantString,
  9959. // but builds that use -fno-constant-cfstrings don't go through that.
  9960. if (!FD->hasAttr<FormatArgAttr>())
  9961. FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
  9962. FD->getLocation()));
  9963. }
  9964. }
  9965. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  9966. TypeSourceInfo *TInfo) {
  9967. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  9968. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  9969. if (!TInfo) {
  9970. assert(D.isInvalidType() && "no declarator info for valid type");
  9971. TInfo = Context.getTrivialTypeSourceInfo(T);
  9972. }
  9973. // Scope manipulation handled by caller.
  9974. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  9975. D.getLocStart(),
  9976. D.getIdentifierLoc(),
  9977. D.getIdentifier(),
  9978. TInfo);
  9979. // Bail out immediately if we have an invalid declaration.
  9980. if (D.isInvalidType()) {
  9981. NewTD->setInvalidDecl();
  9982. return NewTD;
  9983. }
  9984. if (D.getDeclSpec().isModulePrivateSpecified()) {
  9985. if (CurContext->isFunctionOrMethod())
  9986. Diag(NewTD->getLocation(), diag::err_module_private_local)
  9987. << 2 << NewTD->getDeclName()
  9988. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  9989. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  9990. else
  9991. NewTD->setModulePrivate();
  9992. }
  9993. // C++ [dcl.typedef]p8:
  9994. // If the typedef declaration defines an unnamed class (or
  9995. // enum), the first typedef-name declared by the declaration
  9996. // to be that class type (or enum type) is used to denote the
  9997. // class type (or enum type) for linkage purposes only.
  9998. // We need to check whether the type was declared in the declaration.
  9999. switch (D.getDeclSpec().getTypeSpecType()) {
  10000. case TST_enum:
  10001. case TST_struct:
  10002. case TST_interface:
  10003. case TST_union:
  10004. case TST_class: {
  10005. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  10006. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  10007. break;
  10008. }
  10009. default:
  10010. break;
  10011. }
  10012. return NewTD;
  10013. }
  10014. /// \brief Check that this is a valid underlying type for an enum declaration.
  10015. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  10016. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  10017. QualType T = TI->getType();
  10018. if (T->isDependentType())
  10019. return false;
  10020. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  10021. if (BT->isInteger())
  10022. return false;
  10023. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  10024. return true;
  10025. }
  10026. /// Check whether this is a valid redeclaration of a previous enumeration.
  10027. /// \return true if the redeclaration was invalid.
  10028. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  10029. QualType EnumUnderlyingTy,
  10030. const EnumDecl *Prev) {
  10031. bool IsFixed = !EnumUnderlyingTy.isNull();
  10032. if (IsScoped != Prev->isScoped()) {
  10033. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  10034. << Prev->isScoped();
  10035. Diag(Prev->getLocation(), diag::note_previous_declaration);
  10036. return true;
  10037. }
  10038. if (IsFixed && Prev->isFixed()) {
  10039. if (!EnumUnderlyingTy->isDependentType() &&
  10040. !Prev->getIntegerType()->isDependentType() &&
  10041. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  10042. Prev->getIntegerType())) {
  10043. // TODO: Highlight the underlying type of the redeclaration.
  10044. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  10045. << EnumUnderlyingTy << Prev->getIntegerType();
  10046. Diag(Prev->getLocation(), diag::note_previous_declaration)
  10047. << Prev->getIntegerTypeRange();
  10048. return true;
  10049. }
  10050. } else if (IsFixed != Prev->isFixed()) {
  10051. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  10052. << Prev->isFixed();
  10053. Diag(Prev->getLocation(), diag::note_previous_declaration);
  10054. return true;
  10055. }
  10056. return false;
  10057. }
  10058. /// \brief Get diagnostic %select index for tag kind for
  10059. /// redeclaration diagnostic message.
  10060. /// WARNING: Indexes apply to particular diagnostics only!
  10061. ///
  10062. /// \returns diagnostic %select index.
  10063. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  10064. switch (Tag) {
  10065. case TTK_Struct: return 0;
  10066. case TTK_Interface: return 1;
  10067. case TTK_Class: return 2;
  10068. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  10069. }
  10070. }
  10071. /// \brief Determine if tag kind is a class-key compatible with
  10072. /// class for redeclaration (class, struct, or __interface).
  10073. ///
  10074. /// \returns true iff the tag kind is compatible.
  10075. static bool isClassCompatTagKind(TagTypeKind Tag)
  10076. {
  10077. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  10078. }
  10079. /// \brief Determine whether a tag with a given kind is acceptable
  10080. /// as a redeclaration of the given tag declaration.
  10081. ///
  10082. /// \returns true if the new tag kind is acceptable, false otherwise.
  10083. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  10084. TagTypeKind NewTag, bool isDefinition,
  10085. SourceLocation NewTagLoc,
  10086. const IdentifierInfo *Name) {
  10087. // C++ [dcl.type.elab]p3:
  10088. // The class-key or enum keyword present in the
  10089. // elaborated-type-specifier shall agree in kind with the
  10090. // declaration to which the name in the elaborated-type-specifier
  10091. // refers. This rule also applies to the form of
  10092. // elaborated-type-specifier that declares a class-name or
  10093. // friend class since it can be construed as referring to the
  10094. // definition of the class. Thus, in any
  10095. // elaborated-type-specifier, the enum keyword shall be used to
  10096. // refer to an enumeration (7.2), the union class-key shall be
  10097. // used to refer to a union (clause 9), and either the class or
  10098. // struct class-key shall be used to refer to a class (clause 9)
  10099. // declared using the class or struct class-key.
  10100. TagTypeKind OldTag = Previous->getTagKind();
  10101. if (!isDefinition || !isClassCompatTagKind(NewTag))
  10102. if (OldTag == NewTag)
  10103. return true;
  10104. if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
  10105. // Warn about the struct/class tag mismatch.
  10106. bool isTemplate = false;
  10107. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  10108. isTemplate = Record->getDescribedClassTemplate();
  10109. if (!ActiveTemplateInstantiations.empty()) {
  10110. // In a template instantiation, do not offer fix-its for tag mismatches
  10111. // since they usually mess up the template instead of fixing the problem.
  10112. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  10113. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  10114. << getRedeclDiagFromTagKind(OldTag);
  10115. return true;
  10116. }
  10117. if (isDefinition) {
  10118. // On definitions, check previous tags and issue a fix-it for each
  10119. // one that doesn't match the current tag.
  10120. if (Previous->getDefinition()) {
  10121. // Don't suggest fix-its for redefinitions.
  10122. return true;
  10123. }
  10124. bool previousMismatch = false;
  10125. for (auto I : Previous->redecls()) {
  10126. if (I->getTagKind() != NewTag) {
  10127. if (!previousMismatch) {
  10128. previousMismatch = true;
  10129. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  10130. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  10131. << getRedeclDiagFromTagKind(I->getTagKind());
  10132. }
  10133. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  10134. << getRedeclDiagFromTagKind(NewTag)
  10135. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  10136. TypeWithKeyword::getTagTypeKindName(NewTag));
  10137. }
  10138. }
  10139. return true;
  10140. }
  10141. // Check for a previous definition. If current tag and definition
  10142. // are same type, do nothing. If no definition, but disagree with
  10143. // with previous tag type, give a warning, but no fix-it.
  10144. const TagDecl *Redecl = Previous->getDefinition() ?
  10145. Previous->getDefinition() : Previous;
  10146. if (Redecl->getTagKind() == NewTag) {
  10147. return true;
  10148. }
  10149. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  10150. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  10151. << getRedeclDiagFromTagKind(OldTag);
  10152. Diag(Redecl->getLocation(), diag::note_previous_use);
  10153. // If there is a previous definition, suggest a fix-it.
  10154. if (Previous->getDefinition()) {
  10155. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  10156. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  10157. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  10158. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  10159. }
  10160. return true;
  10161. }
  10162. return false;
  10163. }
  10164. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  10165. /// from an outer enclosing namespace or file scope inside a friend declaration.
  10166. /// This should provide the commented out code in the following snippet:
  10167. /// namespace N {
  10168. /// struct X;
  10169. /// namespace M {
  10170. /// struct Y { friend struct /*N::*/ X; };
  10171. /// }
  10172. /// }
  10173. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  10174. SourceLocation NameLoc) {
  10175. // While the decl is in a namespace, do repeated lookup of that name and see
  10176. // if we get the same namespace back. If we do not, continue until
  10177. // translation unit scope, at which point we have a fully qualified NNS.
  10178. SmallVector<IdentifierInfo *, 4> Namespaces;
  10179. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  10180. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  10181. // This tag should be declared in a namespace, which can only be enclosed by
  10182. // other namespaces. Bail if there's an anonymous namespace in the chain.
  10183. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  10184. if (!Namespace || Namespace->isAnonymousNamespace())
  10185. return FixItHint();
  10186. IdentifierInfo *II = Namespace->getIdentifier();
  10187. Namespaces.push_back(II);
  10188. NamedDecl *Lookup = SemaRef.LookupSingleName(
  10189. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  10190. if (Lookup == Namespace)
  10191. break;
  10192. }
  10193. // Once we have all the namespaces, reverse them to go outermost first, and
  10194. // build an NNS.
  10195. SmallString<64> Insertion;
  10196. llvm::raw_svector_ostream OS(Insertion);
  10197. if (DC->isTranslationUnit())
  10198. OS << "::";
  10199. std::reverse(Namespaces.begin(), Namespaces.end());
  10200. for (auto *II : Namespaces)
  10201. OS << II->getName() << "::";
  10202. return FixItHint::CreateInsertion(NameLoc, Insertion);
  10203. }
  10204. /// \brief Determine whether a tag originally declared in context \p OldDC can
  10205. /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
  10206. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  10207. /// using-declaration).
  10208. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  10209. DeclContext *NewDC) {
  10210. OldDC = OldDC->getRedeclContext();
  10211. NewDC = NewDC->getRedeclContext();
  10212. if (OldDC->Equals(NewDC))
  10213. return true;
  10214. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  10215. // encloses the other).
  10216. if (S.getLangOpts().MSVCCompat &&
  10217. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  10218. return true;
  10219. return false;
  10220. }
  10221. /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
  10222. /// former case, Name will be non-null. In the later case, Name will be null.
  10223. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  10224. /// reference/declaration/definition of a tag.
  10225. ///
  10226. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  10227. /// trailing-type-specifier) other than one in an alias-declaration.
  10228. ///
  10229. /// \param SkipBody If non-null, will be set to indicate if the caller should
  10230. /// skip the definition of this tag and treat it as if it were a declaration.
  10231. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  10232. SourceLocation KWLoc, CXXScopeSpec &SS,
  10233. IdentifierInfo *Name, SourceLocation NameLoc,
  10234. AttributeList *Attr, AccessSpecifier AS,
  10235. SourceLocation ModulePrivateLoc,
  10236. MultiTemplateParamsArg TemplateParameterLists,
  10237. bool &OwnedDecl, bool &IsDependent,
  10238. SourceLocation ScopedEnumKWLoc,
  10239. bool ScopedEnumUsesClassTag,
  10240. TypeResult UnderlyingType,
  10241. bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
  10242. // If this is not a definition, it must have a name.
  10243. IdentifierInfo *OrigName = Name;
  10244. assert((Name != nullptr || TUK == TUK_Definition) &&
  10245. "Nameless record must be a definition!");
  10246. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  10247. OwnedDecl = false;
  10248. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  10249. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  10250. // FIXME: Check explicit specializations more carefully.
  10251. bool isExplicitSpecialization = false;
  10252. bool Invalid = false;
  10253. // We only need to do this matching if we have template parameters
  10254. // or a scope specifier, which also conveniently avoids this work
  10255. // for non-C++ cases.
  10256. if (TemplateParameterLists.size() > 0 ||
  10257. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  10258. if (TemplateParameterList *TemplateParams =
  10259. MatchTemplateParametersToScopeSpecifier(
  10260. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  10261. TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
  10262. if (Kind == TTK_Enum) {
  10263. Diag(KWLoc, diag::err_enum_template);
  10264. return nullptr;
  10265. }
  10266. if (TemplateParams->size() > 0) {
  10267. // This is a declaration or definition of a class template (which may
  10268. // be a member of another template).
  10269. if (Invalid)
  10270. return nullptr;
  10271. OwnedDecl = false;
  10272. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  10273. SS, Name, NameLoc, Attr,
  10274. TemplateParams, AS,
  10275. ModulePrivateLoc,
  10276. /*FriendLoc*/SourceLocation(),
  10277. TemplateParameterLists.size()-1,
  10278. TemplateParameterLists.data(),
  10279. SkipBody);
  10280. return Result.get();
  10281. } else {
  10282. // The "template<>" header is extraneous.
  10283. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  10284. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  10285. isExplicitSpecialization = true;
  10286. }
  10287. }
  10288. }
  10289. // Figure out the underlying type if this a enum declaration. We need to do
  10290. // this early, because it's needed to detect if this is an incompatible
  10291. // redeclaration.
  10292. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  10293. if (Kind == TTK_Enum) {
  10294. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
  10295. // No underlying type explicitly specified, or we failed to parse the
  10296. // type, default to int.
  10297. EnumUnderlying = Context.IntTy.getTypePtr();
  10298. else if (UnderlyingType.get()) {
  10299. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  10300. // integral type; any cv-qualification is ignored.
  10301. TypeSourceInfo *TI = nullptr;
  10302. GetTypeFromParser(UnderlyingType.get(), &TI);
  10303. EnumUnderlying = TI;
  10304. if (CheckEnumUnderlyingType(TI))
  10305. // Recover by falling back to int.
  10306. EnumUnderlying = Context.IntTy.getTypePtr();
  10307. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  10308. UPPC_FixedUnderlyingType))
  10309. EnumUnderlying = Context.IntTy.getTypePtr();
  10310. } else if (getLangOpts().MSVCCompat)
  10311. // Microsoft enums are always of int type.
  10312. EnumUnderlying = Context.IntTy.getTypePtr();
  10313. }
  10314. DeclContext *SearchDC = CurContext;
  10315. DeclContext *DC = CurContext;
  10316. bool isStdBadAlloc = false;
  10317. RedeclarationKind Redecl = ForRedeclaration;
  10318. if (TUK == TUK_Friend || TUK == TUK_Reference)
  10319. Redecl = NotForRedeclaration;
  10320. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  10321. if (Name && SS.isNotEmpty()) {
  10322. // We have a nested-name tag ('struct foo::bar').
  10323. // Check for invalid 'foo::'.
  10324. if (SS.isInvalid()) {
  10325. Name = nullptr;
  10326. goto CreateNewDecl;
  10327. }
  10328. // If this is a friend or a reference to a class in a dependent
  10329. // context, don't try to make a decl for it.
  10330. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  10331. DC = computeDeclContext(SS, false);
  10332. if (!DC) {
  10333. IsDependent = true;
  10334. return nullptr;
  10335. }
  10336. } else {
  10337. DC = computeDeclContext(SS, true);
  10338. if (!DC) {
  10339. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  10340. << SS.getRange();
  10341. return nullptr;
  10342. }
  10343. }
  10344. if (RequireCompleteDeclContext(SS, DC))
  10345. return nullptr;
  10346. SearchDC = DC;
  10347. // Look-up name inside 'foo::'.
  10348. LookupQualifiedName(Previous, DC);
  10349. if (Previous.isAmbiguous())
  10350. return nullptr;
  10351. if (Previous.empty()) {
  10352. // Name lookup did not find anything. However, if the
  10353. // nested-name-specifier refers to the current instantiation,
  10354. // and that current instantiation has any dependent base
  10355. // classes, we might find something at instantiation time: treat
  10356. // this as a dependent elaborated-type-specifier.
  10357. // But this only makes any sense for reference-like lookups.
  10358. if (Previous.wasNotFoundInCurrentInstantiation() &&
  10359. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  10360. IsDependent = true;
  10361. return nullptr;
  10362. }
  10363. // A tag 'foo::bar' must already exist.
  10364. Diag(NameLoc, diag::err_not_tag_in_scope)
  10365. << Kind << Name << DC << SS.getRange();
  10366. Name = nullptr;
  10367. Invalid = true;
  10368. goto CreateNewDecl;
  10369. }
  10370. } else if (Name) {
  10371. // C++14 [class.mem]p14:
  10372. // If T is the name of a class, then each of the following shall have a
  10373. // name different from T:
  10374. // -- every member of class T that is itself a type
  10375. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  10376. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  10377. return nullptr;
  10378. // If this is a named struct, check to see if there was a previous forward
  10379. // declaration or definition.
  10380. // FIXME: We're looking into outer scopes here, even when we
  10381. // shouldn't be. Doing so can result in ambiguities that we
  10382. // shouldn't be diagnosing.
  10383. LookupName(Previous, S);
  10384. // When declaring or defining a tag, ignore ambiguities introduced
  10385. // by types using'ed into this scope.
  10386. if (Previous.isAmbiguous() &&
  10387. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  10388. LookupResult::Filter F = Previous.makeFilter();
  10389. while (F.hasNext()) {
  10390. NamedDecl *ND = F.next();
  10391. if (ND->getDeclContext()->getRedeclContext() != SearchDC)
  10392. F.erase();
  10393. }
  10394. F.done();
  10395. }
  10396. // C++11 [namespace.memdef]p3:
  10397. // If the name in a friend declaration is neither qualified nor
  10398. // a template-id and the declaration is a function or an
  10399. // elaborated-type-specifier, the lookup to determine whether
  10400. // the entity has been previously declared shall not consider
  10401. // any scopes outside the innermost enclosing namespace.
  10402. //
  10403. // MSVC doesn't implement the above rule for types, so a friend tag
  10404. // declaration may be a redeclaration of a type declared in an enclosing
  10405. // scope. They do implement this rule for friend functions.
  10406. //
  10407. // Does it matter that this should be by scope instead of by
  10408. // semantic context?
  10409. if (!Previous.empty() && TUK == TUK_Friend) {
  10410. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  10411. LookupResult::Filter F = Previous.makeFilter();
  10412. bool FriendSawTagOutsideEnclosingNamespace = false;
  10413. while (F.hasNext()) {
  10414. NamedDecl *ND = F.next();
  10415. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  10416. if (DC->isFileContext() &&
  10417. !EnclosingNS->Encloses(ND->getDeclContext())) {
  10418. if (getLangOpts().MSVCCompat)
  10419. FriendSawTagOutsideEnclosingNamespace = true;
  10420. else
  10421. F.erase();
  10422. }
  10423. }
  10424. F.done();
  10425. // Diagnose this MSVC extension in the easy case where lookup would have
  10426. // unambiguously found something outside the enclosing namespace.
  10427. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  10428. NamedDecl *ND = Previous.getFoundDecl();
  10429. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  10430. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  10431. }
  10432. }
  10433. // Note: there used to be some attempt at recovery here.
  10434. if (Previous.isAmbiguous())
  10435. return nullptr;
  10436. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  10437. // FIXME: This makes sure that we ignore the contexts associated
  10438. // with C structs, unions, and enums when looking for a matching
  10439. // tag declaration or definition. See the similar lookup tweak
  10440. // in Sema::LookupName; is there a better way to deal with this?
  10441. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  10442. SearchDC = SearchDC->getParent();
  10443. }
  10444. }
  10445. if (Previous.isSingleResult() &&
  10446. Previous.getFoundDecl()->isTemplateParameter()) {
  10447. // Maybe we will complain about the shadowed template parameter.
  10448. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  10449. // Just pretend that we didn't see the previous declaration.
  10450. Previous.clear();
  10451. }
  10452. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  10453. DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
  10454. // This is a declaration of or a reference to "std::bad_alloc".
  10455. isStdBadAlloc = true;
  10456. if (Previous.empty() && StdBadAlloc) {
  10457. // std::bad_alloc has been implicitly declared (but made invisible to
  10458. // name lookup). Fill in this implicit declaration as the previous
  10459. // declaration, so that the declarations get chained appropriately.
  10460. Previous.addDecl(getStdBadAlloc());
  10461. }
  10462. }
  10463. // If we didn't find a previous declaration, and this is a reference
  10464. // (or friend reference), move to the correct scope. In C++, we
  10465. // also need to do a redeclaration lookup there, just in case
  10466. // there's a shadow friend decl.
  10467. if (Name && Previous.empty() &&
  10468. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  10469. if (Invalid) goto CreateNewDecl;
  10470. assert(SS.isEmpty());
  10471. if (TUK == TUK_Reference) {
  10472. // C++ [basic.scope.pdecl]p5:
  10473. // -- for an elaborated-type-specifier of the form
  10474. //
  10475. // class-key identifier
  10476. //
  10477. // if the elaborated-type-specifier is used in the
  10478. // decl-specifier-seq or parameter-declaration-clause of a
  10479. // function defined in namespace scope, the identifier is
  10480. // declared as a class-name in the namespace that contains
  10481. // the declaration; otherwise, except as a friend
  10482. // declaration, the identifier is declared in the smallest
  10483. // non-class, non-function-prototype scope that contains the
  10484. // declaration.
  10485. //
  10486. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  10487. // C structs and unions.
  10488. //
  10489. // It is an error in C++ to declare (rather than define) an enum
  10490. // type, including via an elaborated type specifier. We'll
  10491. // diagnose that later; for now, declare the enum in the same
  10492. // scope as we would have picked for any other tag type.
  10493. //
  10494. // GNU C also supports this behavior as part of its incomplete
  10495. // enum types extension, while GNU C++ does not.
  10496. //
  10497. // Find the context where we'll be declaring the tag.
  10498. // FIXME: We would like to maintain the current DeclContext as the
  10499. // lexical context,
  10500. while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
  10501. SearchDC = SearchDC->getParent();
  10502. // Find the scope where we'll be declaring the tag.
  10503. while (S->isClassScope() ||
  10504. (getLangOpts().CPlusPlus &&
  10505. S->isFunctionPrototypeScope()) ||
  10506. ((S->getFlags() & Scope::DeclScope) == 0) ||
  10507. (S->getEntity() && S->getEntity()->isTransparentContext()))
  10508. S = S->getParent();
  10509. } else {
  10510. assert(TUK == TUK_Friend);
  10511. // C++ [namespace.memdef]p3:
  10512. // If a friend declaration in a non-local class first declares a
  10513. // class or function, the friend class or function is a member of
  10514. // the innermost enclosing namespace.
  10515. SearchDC = SearchDC->getEnclosingNamespaceContext();
  10516. }
  10517. // In C++, we need to do a redeclaration lookup to properly
  10518. // diagnose some problems.
  10519. if (getLangOpts().CPlusPlus) {
  10520. Previous.setRedeclarationKind(ForRedeclaration);
  10521. LookupQualifiedName(Previous, SearchDC);
  10522. }
  10523. }
  10524. // If we have a known previous declaration to use, then use it.
  10525. if (Previous.empty() && SkipBody && SkipBody->Previous)
  10526. Previous.addDecl(SkipBody->Previous);
  10527. if (!Previous.empty()) {
  10528. NamedDecl *PrevDecl = Previous.getFoundDecl();
  10529. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  10530. // It's okay to have a tag decl in the same scope as a typedef
  10531. // which hides a tag decl in the same scope. Finding this
  10532. // insanity with a redeclaration lookup can only actually happen
  10533. // in C++.
  10534. //
  10535. // This is also okay for elaborated-type-specifiers, which is
  10536. // technically forbidden by the current standard but which is
  10537. // okay according to the likely resolution of an open issue;
  10538. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  10539. if (getLangOpts().CPlusPlus) {
  10540. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  10541. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  10542. TagDecl *Tag = TT->getDecl();
  10543. if (Tag->getDeclName() == Name &&
  10544. Tag->getDeclContext()->getRedeclContext()
  10545. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  10546. PrevDecl = Tag;
  10547. Previous.clear();
  10548. Previous.addDecl(Tag);
  10549. Previous.resolveKind();
  10550. }
  10551. }
  10552. }
  10553. }
  10554. // If this is a redeclaration of a using shadow declaration, it must
  10555. // declare a tag in the same context. In MSVC mode, we allow a
  10556. // redefinition if either context is within the other.
  10557. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  10558. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  10559. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  10560. isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
  10561. !(OldTag && isAcceptableTagRedeclContext(
  10562. *this, OldTag->getDeclContext(), SearchDC))) {
  10563. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  10564. Diag(Shadow->getTargetDecl()->getLocation(),
  10565. diag::note_using_decl_target);
  10566. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  10567. << 0;
  10568. // Recover by ignoring the old declaration.
  10569. Previous.clear();
  10570. goto CreateNewDecl;
  10571. }
  10572. }
  10573. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  10574. // If this is a use of a previous tag, or if the tag is already declared
  10575. // in the same scope (so that the definition/declaration completes or
  10576. // rementions the tag), reuse the decl.
  10577. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  10578. isDeclInScope(DirectPrevDecl, SearchDC, S,
  10579. SS.isNotEmpty() || isExplicitSpecialization)) {
  10580. // Make sure that this wasn't declared as an enum and now used as a
  10581. // struct or something similar.
  10582. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  10583. TUK == TUK_Definition, KWLoc,
  10584. Name)) {
  10585. bool SafeToContinue
  10586. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  10587. Kind != TTK_Enum);
  10588. if (SafeToContinue)
  10589. Diag(KWLoc, diag::err_use_with_wrong_tag)
  10590. << Name
  10591. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  10592. PrevTagDecl->getKindName());
  10593. else
  10594. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  10595. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  10596. if (SafeToContinue)
  10597. Kind = PrevTagDecl->getTagKind();
  10598. else {
  10599. // Recover by making this an anonymous redefinition.
  10600. Name = nullptr;
  10601. Previous.clear();
  10602. Invalid = true;
  10603. }
  10604. }
  10605. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  10606. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  10607. // If this is an elaborated-type-specifier for a scoped enumeration,
  10608. // the 'class' keyword is not necessary and not permitted.
  10609. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  10610. if (ScopedEnum)
  10611. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  10612. << PrevEnum->isScoped()
  10613. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  10614. return PrevTagDecl;
  10615. }
  10616. QualType EnumUnderlyingTy;
  10617. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  10618. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  10619. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  10620. EnumUnderlyingTy = QualType(T, 0);
  10621. // All conflicts with previous declarations are recovered by
  10622. // returning the previous declaration, unless this is a definition,
  10623. // in which case we want the caller to bail out.
  10624. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  10625. ScopedEnum, EnumUnderlyingTy, PrevEnum))
  10626. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  10627. }
  10628. // C++11 [class.mem]p1:
  10629. // A member shall not be declared twice in the member-specification,
  10630. // except that a nested class or member class template can be declared
  10631. // and then later defined.
  10632. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  10633. S->isDeclScope(PrevDecl)) {
  10634. Diag(NameLoc, diag::ext_member_redeclared);
  10635. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  10636. }
  10637. if (!Invalid) {
  10638. // If this is a use, just return the declaration we found, unless
  10639. // we have attributes.
  10640. // FIXME: In the future, return a variant or some other clue
  10641. // for the consumer of this Decl to know it doesn't own it.
  10642. // For our current ASTs this shouldn't be a problem, but will
  10643. // need to be changed with DeclGroups.
  10644. if (!Attr &&
  10645. ((TUK == TUK_Reference &&
  10646. (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
  10647. || TUK == TUK_Friend))
  10648. return PrevTagDecl;
  10649. // Diagnose attempts to redefine a tag.
  10650. if (TUK == TUK_Definition) {
  10651. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  10652. // If we're defining a specialization and the previous definition
  10653. // is from an implicit instantiation, don't emit an error
  10654. // here; we'll catch this in the general case below.
  10655. bool IsExplicitSpecializationAfterInstantiation = false;
  10656. if (isExplicitSpecialization) {
  10657. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  10658. IsExplicitSpecializationAfterInstantiation =
  10659. RD->getTemplateSpecializationKind() !=
  10660. TSK_ExplicitSpecialization;
  10661. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  10662. IsExplicitSpecializationAfterInstantiation =
  10663. ED->getTemplateSpecializationKind() !=
  10664. TSK_ExplicitSpecialization;
  10665. }
  10666. NamedDecl *Hidden = nullptr;
  10667. if (SkipBody && getLangOpts().CPlusPlus &&
  10668. !hasVisibleDefinition(Def, &Hidden)) {
  10669. // There is a definition of this tag, but it is not visible. We
  10670. // explicitly make use of C++'s one definition rule here, and
  10671. // assume that this definition is identical to the hidden one
  10672. // we already have. Make the existing definition visible and
  10673. // use it in place of this one.
  10674. SkipBody->ShouldSkip = true;
  10675. makeMergedDefinitionVisible(Hidden, KWLoc);
  10676. return Def;
  10677. } else if (!IsExplicitSpecializationAfterInstantiation) {
  10678. // A redeclaration in function prototype scope in C isn't
  10679. // visible elsewhere, so merely issue a warning.
  10680. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  10681. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  10682. else
  10683. Diag(NameLoc, diag::err_redefinition) << Name;
  10684. Diag(Def->getLocation(), diag::note_previous_definition);
  10685. // If this is a redefinition, recover by making this
  10686. // struct be anonymous, which will make any later
  10687. // references get the previous definition.
  10688. Name = nullptr;
  10689. Previous.clear();
  10690. Invalid = true;
  10691. }
  10692. } else {
  10693. // If the type is currently being defined, complain
  10694. // about a nested redefinition.
  10695. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  10696. if (TD->isBeingDefined()) {
  10697. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  10698. Diag(PrevTagDecl->getLocation(),
  10699. diag::note_previous_definition);
  10700. Name = nullptr;
  10701. Previous.clear();
  10702. Invalid = true;
  10703. }
  10704. }
  10705. // Okay, this is definition of a previously declared or referenced
  10706. // tag. We're going to create a new Decl for it.
  10707. }
  10708. // Okay, we're going to make a redeclaration. If this is some kind
  10709. // of reference, make sure we build the redeclaration in the same DC
  10710. // as the original, and ignore the current access specifier.
  10711. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  10712. SearchDC = PrevTagDecl->getDeclContext();
  10713. AS = AS_none;
  10714. }
  10715. }
  10716. // If we get here we have (another) forward declaration or we
  10717. // have a definition. Just create a new decl.
  10718. } else {
  10719. // If we get here, this is a definition of a new tag type in a nested
  10720. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  10721. // new decl/type. We set PrevDecl to NULL so that the entities
  10722. // have distinct types.
  10723. Previous.clear();
  10724. }
  10725. // If we get here, we're going to create a new Decl. If PrevDecl
  10726. // is non-NULL, it's a definition of the tag declared by
  10727. // PrevDecl. If it's NULL, we have a new definition.
  10728. // Otherwise, PrevDecl is not a tag, but was found with tag
  10729. // lookup. This is only actually possible in C++, where a few
  10730. // things like templates still live in the tag namespace.
  10731. } else {
  10732. // Use a better diagnostic if an elaborated-type-specifier
  10733. // found the wrong kind of type on the first
  10734. // (non-redeclaration) lookup.
  10735. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  10736. !Previous.isForRedeclaration()) {
  10737. unsigned Kind = 0;
  10738. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  10739. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  10740. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  10741. Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
  10742. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  10743. Invalid = true;
  10744. // Otherwise, only diagnose if the declaration is in scope.
  10745. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  10746. SS.isNotEmpty() || isExplicitSpecialization)) {
  10747. // do nothing
  10748. // Diagnose implicit declarations introduced by elaborated types.
  10749. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  10750. unsigned Kind = 0;
  10751. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  10752. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  10753. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  10754. Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
  10755. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  10756. Invalid = true;
  10757. // Otherwise it's a declaration. Call out a particularly common
  10758. // case here.
  10759. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  10760. unsigned Kind = 0;
  10761. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  10762. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  10763. << Name << Kind << TND->getUnderlyingType();
  10764. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  10765. Invalid = true;
  10766. // Otherwise, diagnose.
  10767. } else {
  10768. // The tag name clashes with something else in the target scope,
  10769. // issue an error and recover by making this tag be anonymous.
  10770. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  10771. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  10772. Name = nullptr;
  10773. Invalid = true;
  10774. }
  10775. // The existing declaration isn't relevant to us; we're in a
  10776. // new scope, so clear out the previous declaration.
  10777. Previous.clear();
  10778. }
  10779. }
  10780. CreateNewDecl:
  10781. TagDecl *PrevDecl = nullptr;
  10782. if (Previous.isSingleResult())
  10783. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  10784. // If there is an identifier, use the location of the identifier as the
  10785. // location of the decl, otherwise use the location of the struct/union
  10786. // keyword.
  10787. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  10788. // Otherwise, create a new declaration. If there is a previous
  10789. // declaration of the same entity, the two will be linked via
  10790. // PrevDecl.
  10791. TagDecl *New;
  10792. bool IsForwardReference = false;
  10793. if (Kind == TTK_Enum) {
  10794. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  10795. // enum X { A, B, C } D; D should chain to X.
  10796. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  10797. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  10798. ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
  10799. // If this is an undefined enum, warn.
  10800. if (TUK != TUK_Definition && !Invalid) {
  10801. TagDecl *Def;
  10802. if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
  10803. cast<EnumDecl>(New)->isFixed()) {
  10804. // C++0x: 7.2p2: opaque-enum-declaration.
  10805. // Conflicts are diagnosed above. Do nothing.
  10806. }
  10807. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  10808. Diag(Loc, diag::ext_forward_ref_enum_def)
  10809. << New;
  10810. Diag(Def->getLocation(), diag::note_previous_definition);
  10811. } else {
  10812. unsigned DiagID = diag::ext_forward_ref_enum;
  10813. if (getLangOpts().MSVCCompat)
  10814. DiagID = diag::ext_ms_forward_ref_enum;
  10815. else if (getLangOpts().CPlusPlus)
  10816. DiagID = diag::err_forward_ref_enum;
  10817. Diag(Loc, DiagID);
  10818. // If this is a forward-declared reference to an enumeration, make a
  10819. // note of it; we won't actually be introducing the declaration into
  10820. // the declaration context.
  10821. if (TUK == TUK_Reference)
  10822. IsForwardReference = true;
  10823. }
  10824. }
  10825. if (EnumUnderlying) {
  10826. EnumDecl *ED = cast<EnumDecl>(New);
  10827. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  10828. ED->setIntegerTypeSourceInfo(TI);
  10829. else
  10830. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  10831. ED->setPromotionType(ED->getIntegerType());
  10832. }
  10833. } else {
  10834. // struct/union/class
  10835. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  10836. // struct X { int A; } D; D should chain to X.
  10837. if (getLangOpts().CPlusPlus) {
  10838. // FIXME: Look for a way to use RecordDecl for simple structs.
  10839. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  10840. cast_or_null<CXXRecordDecl>(PrevDecl));
  10841. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  10842. StdBadAlloc = cast<CXXRecordDecl>(New);
  10843. } else
  10844. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  10845. cast_or_null<RecordDecl>(PrevDecl));
  10846. }
  10847. // C++11 [dcl.type]p3:
  10848. // A type-specifier-seq shall not define a class or enumeration [...].
  10849. if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
  10850. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  10851. << Context.getTagDeclType(New);
  10852. Invalid = true;
  10853. }
  10854. // Maybe add qualifier info.
  10855. if (SS.isNotEmpty()) {
  10856. if (SS.isSet()) {
  10857. // If this is either a declaration or a definition, check the
  10858. // nested-name-specifier against the current context. We don't do this
  10859. // for explicit specializations, because they have similar checking
  10860. // (with more specific diagnostics) in the call to
  10861. // CheckMemberSpecialization, below.
  10862. if (!isExplicitSpecialization &&
  10863. (TUK == TUK_Definition || TUK == TUK_Declaration) &&
  10864. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
  10865. Invalid = true;
  10866. New->setQualifierInfo(SS.getWithLocInContext(Context));
  10867. if (TemplateParameterLists.size() > 0) {
  10868. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  10869. }
  10870. }
  10871. else
  10872. Invalid = true;
  10873. }
  10874. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  10875. // Add alignment attributes if necessary; these attributes are checked when
  10876. // the ASTContext lays out the structure.
  10877. //
  10878. // It is important for implementing the correct semantics that this
  10879. // happen here (in act on tag decl). The #pragma pack stack is
  10880. // maintained as a result of parser callbacks which can occur at
  10881. // many points during the parsing of a struct declaration (because
  10882. // the #pragma tokens are effectively skipped over during the
  10883. // parsing of the struct).
  10884. if (TUK == TUK_Definition) {
  10885. AddAlignmentAttributesForRecord(RD);
  10886. AddMsStructLayoutForRecord(RD);
  10887. }
  10888. }
  10889. if (ModulePrivateLoc.isValid()) {
  10890. if (isExplicitSpecialization)
  10891. Diag(New->getLocation(), diag::err_module_private_specialization)
  10892. << 2
  10893. << FixItHint::CreateRemoval(ModulePrivateLoc);
  10894. // __module_private__ does not apply to local classes. However, we only
  10895. // diagnose this as an error when the declaration specifiers are
  10896. // freestanding. Here, we just ignore the __module_private__.
  10897. else if (!SearchDC->isFunctionOrMethod())
  10898. New->setModulePrivate();
  10899. }
  10900. // If this is a specialization of a member class (of a class template),
  10901. // check the specialization.
  10902. if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
  10903. Invalid = true;
  10904. // If we're declaring or defining a tag in function prototype scope in C,
  10905. // note that this type can only be used within the function and add it to
  10906. // the list of decls to inject into the function definition scope.
  10907. if ((Name || Kind == TTK_Enum) &&
  10908. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  10909. if (getLangOpts().CPlusPlus) {
  10910. // C++ [dcl.fct]p6:
  10911. // Types shall not be defined in return or parameter types.
  10912. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  10913. Diag(Loc, diag::err_type_defined_in_param_type)
  10914. << Name;
  10915. Invalid = true;
  10916. }
  10917. } else {
  10918. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  10919. }
  10920. DeclsInPrototypeScope.push_back(New);
  10921. }
  10922. if (Invalid)
  10923. New->setInvalidDecl();
  10924. if (Attr)
  10925. ProcessDeclAttributeList(S, New, Attr);
  10926. // Set the lexical context. If the tag has a C++ scope specifier, the
  10927. // lexical context will be different from the semantic context.
  10928. New->setLexicalDeclContext(CurContext);
  10929. // Mark this as a friend decl if applicable.
  10930. // In Microsoft mode, a friend declaration also acts as a forward
  10931. // declaration so we always pass true to setObjectOfFriendDecl to make
  10932. // the tag name visible.
  10933. if (TUK == TUK_Friend)
  10934. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  10935. // Set the access specifier.
  10936. if (!Invalid && SearchDC->isRecord())
  10937. SetMemberAccessSpecifier(New, PrevDecl, AS);
  10938. if (TUK == TUK_Definition)
  10939. New->startDefinition();
  10940. // If this has an identifier, add it to the scope stack.
  10941. if (TUK == TUK_Friend) {
  10942. // We might be replacing an existing declaration in the lookup tables;
  10943. // if so, borrow its access specifier.
  10944. if (PrevDecl)
  10945. New->setAccess(PrevDecl->getAccess());
  10946. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  10947. DC->makeDeclVisibleInContext(New);
  10948. if (Name) // can be null along some error paths
  10949. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  10950. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  10951. } else if (Name) {
  10952. S = getNonFieldDeclScope(S);
  10953. PushOnScopeChains(New, S, !IsForwardReference);
  10954. if (IsForwardReference)
  10955. SearchDC->makeDeclVisibleInContext(New);
  10956. } else {
  10957. CurContext->addDecl(New);
  10958. }
  10959. // If this is the C FILE type, notify the AST context.
  10960. if (IdentifierInfo *II = New->getIdentifier())
  10961. if (!New->isInvalidDecl() &&
  10962. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  10963. II->isStr("FILE"))
  10964. Context.setFILEDecl(New);
  10965. if (PrevDecl)
  10966. mergeDeclAttributes(New, PrevDecl);
  10967. // If there's a #pragma GCC visibility in scope, set the visibility of this
  10968. // record.
  10969. AddPushedVisibilityAttribute(New);
  10970. OwnedDecl = true;
  10971. // In C++, don't return an invalid declaration. We can't recover well from
  10972. // the cases where we make the type anonymous.
  10973. return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
  10974. }
  10975. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  10976. AdjustDeclIfTemplate(TagD);
  10977. TagDecl *Tag = cast<TagDecl>(TagD);
  10978. // Enter the tag context.
  10979. PushDeclContext(S, Tag);
  10980. ActOnDocumentableDecl(TagD);
  10981. // If there's a #pragma GCC visibility in scope, set the visibility of this
  10982. // record.
  10983. AddPushedVisibilityAttribute(Tag);
  10984. }
  10985. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  10986. assert(isa<ObjCContainerDecl>(IDecl) &&
  10987. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  10988. DeclContext *OCD = cast<DeclContext>(IDecl);
  10989. assert(getContainingDC(OCD) == CurContext &&
  10990. "The next DeclContext should be lexically contained in the current one.");
  10991. CurContext = OCD;
  10992. return IDecl;
  10993. }
  10994. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  10995. SourceLocation FinalLoc,
  10996. bool IsFinalSpelledSealed,
  10997. SourceLocation LBraceLoc) {
  10998. AdjustDeclIfTemplate(TagD);
  10999. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  11000. FieldCollector->StartClass();
  11001. if (!Record->getIdentifier())
  11002. return;
  11003. if (FinalLoc.isValid())
  11004. Record->addAttr(new (Context)
  11005. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  11006. // C++ [class]p2:
  11007. // [...] The class-name is also inserted into the scope of the
  11008. // class itself; this is known as the injected-class-name. For
  11009. // purposes of access checking, the injected-class-name is treated
  11010. // as if it were a public member name.
  11011. CXXRecordDecl *InjectedClassName
  11012. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  11013. Record->getLocStart(), Record->getLocation(),
  11014. Record->getIdentifier(),
  11015. /*PrevDecl=*/nullptr,
  11016. /*DelayTypeCreation=*/true);
  11017. Context.getTypeDeclType(InjectedClassName, Record);
  11018. InjectedClassName->setImplicit();
  11019. InjectedClassName->setAccess(AS_public);
  11020. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  11021. InjectedClassName->setDescribedClassTemplate(Template);
  11022. PushOnScopeChains(InjectedClassName, S);
  11023. assert(InjectedClassName->isInjectedClassName() &&
  11024. "Broken injected-class-name");
  11025. }
  11026. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  11027. SourceLocation RBraceLoc) {
  11028. AdjustDeclIfTemplate(TagD);
  11029. TagDecl *Tag = cast<TagDecl>(TagD);
  11030. Tag->setRBraceLoc(RBraceLoc);
  11031. // Make sure we "complete" the definition even it is invalid.
  11032. if (Tag->isBeingDefined()) {
  11033. assert(Tag->isInvalidDecl() && "We should already have completed it");
  11034. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  11035. RD->completeDefinition();
  11036. }
  11037. if (isa<CXXRecordDecl>(Tag))
  11038. FieldCollector->FinishClass();
  11039. // Exit this scope of this tag's definition.
  11040. PopDeclContext();
  11041. if (getCurLexicalContext()->isObjCContainer() &&
  11042. Tag->getDeclContext()->isFileContext())
  11043. Tag->setTopLevelDeclInObjCContainer();
  11044. // Notify the consumer that we've defined a tag.
  11045. if (!Tag->isInvalidDecl())
  11046. Consumer.HandleTagDeclDefinition(Tag);
  11047. }
  11048. void Sema::ActOnObjCContainerFinishDefinition() {
  11049. // Exit this scope of this interface definition.
  11050. PopDeclContext();
  11051. }
  11052. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  11053. assert(DC == CurContext && "Mismatch of container contexts");
  11054. OriginalLexicalContext = DC;
  11055. ActOnObjCContainerFinishDefinition();
  11056. }
  11057. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  11058. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  11059. OriginalLexicalContext = nullptr;
  11060. }
  11061. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  11062. AdjustDeclIfTemplate(TagD);
  11063. TagDecl *Tag = cast<TagDecl>(TagD);
  11064. Tag->setInvalidDecl();
  11065. // Make sure we "complete" the definition even it is invalid.
  11066. if (Tag->isBeingDefined()) {
  11067. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  11068. RD->completeDefinition();
  11069. }
  11070. // We're undoing ActOnTagStartDefinition here, not
  11071. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  11072. // the FieldCollector.
  11073. PopDeclContext();
  11074. }
  11075. // Note that FieldName may be null for anonymous bitfields.
  11076. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  11077. IdentifierInfo *FieldName,
  11078. QualType FieldTy, bool IsMsStruct,
  11079. Expr *BitWidth, bool *ZeroWidth) {
  11080. // Default to true; that shouldn't confuse checks for emptiness
  11081. if (ZeroWidth)
  11082. *ZeroWidth = true;
  11083. // C99 6.7.2.1p4 - verify the field type.
  11084. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  11085. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  11086. // Handle incomplete types with specific error.
  11087. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  11088. return ExprError();
  11089. if (FieldName)
  11090. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  11091. << FieldName << FieldTy << BitWidth->getSourceRange();
  11092. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  11093. << FieldTy << BitWidth->getSourceRange();
  11094. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  11095. UPPC_BitFieldWidth))
  11096. return ExprError();
  11097. // If the bit-width is type- or value-dependent, don't try to check
  11098. // it now.
  11099. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  11100. return BitWidth;
  11101. llvm::APSInt Value;
  11102. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  11103. if (ICE.isInvalid())
  11104. return ICE;
  11105. BitWidth = ICE.get();
  11106. if (Value != 0 && ZeroWidth)
  11107. *ZeroWidth = false;
  11108. // Zero-width bitfield is ok for anonymous field.
  11109. if (Value == 0 && FieldName)
  11110. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  11111. if (Value.isSigned() && Value.isNegative()) {
  11112. if (FieldName)
  11113. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  11114. << FieldName << Value.toString(10);
  11115. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  11116. << Value.toString(10);
  11117. }
  11118. if (!FieldTy->isDependentType()) {
  11119. bool UseMSBitfieldSemantics =
  11120. IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft();
  11121. bool UseStorageSize = getLangOpts().CPlusPlus && UseMSBitfieldSemantics;
  11122. uint64_t TypeWidth = UseStorageSize ? Context.getTypeSize(FieldTy)
  11123. : Context.getIntWidth(FieldTy);
  11124. if (Value.ugt(TypeWidth)) {
  11125. if (!getLangOpts().CPlusPlus || UseMSBitfieldSemantics) {
  11126. if (FieldName)
  11127. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  11128. << FieldName << (unsigned)Value.getZExtValue()
  11129. << (unsigned)TypeWidth;
  11130. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  11131. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  11132. }
  11133. if (FieldName)
  11134. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  11135. << FieldName << (unsigned)Value.getZExtValue()
  11136. << (unsigned)TypeWidth;
  11137. else
  11138. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  11139. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  11140. }
  11141. }
  11142. return BitWidth;
  11143. }
  11144. /// ActOnField - Each field of a C struct/union is passed into this in order
  11145. /// to create a FieldDecl object for it.
  11146. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  11147. Declarator &D, Expr *BitfieldWidth) {
  11148. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  11149. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  11150. /*InitStyle=*/ICIS_NoInit, AS_public);
  11151. return Res;
  11152. }
  11153. /// HandleField - Analyze a field of a C struct or a C++ data member.
  11154. ///
  11155. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  11156. SourceLocation DeclStart,
  11157. Declarator &D, Expr *BitWidth,
  11158. InClassInitStyle InitStyle,
  11159. AccessSpecifier AS) {
  11160. IdentifierInfo *II = D.getIdentifier();
  11161. SourceLocation Loc = DeclStart;
  11162. if (II) Loc = D.getIdentifierLoc();
  11163. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11164. QualType T = TInfo->getType();
  11165. if (getLangOpts().CPlusPlus) {
  11166. CheckExtraCXXDefaultArguments(D);
  11167. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  11168. UPPC_DataMemberType)) {
  11169. D.setInvalidType();
  11170. T = Context.IntTy;
  11171. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  11172. }
  11173. }
  11174. // TR 18037 does not allow fields to be declared with address spaces.
  11175. if (T.getQualifiers().hasAddressSpace()) {
  11176. Diag(Loc, diag::err_field_with_address_space);
  11177. D.setInvalidType();
  11178. }
  11179. // OpenCL 1.2 spec, s6.9 r:
  11180. // The event type cannot be used to declare a structure or union field.
  11181. if (LangOpts.OpenCL && T->isEventT()) {
  11182. Diag(Loc, diag::err_event_t_struct_field);
  11183. D.setInvalidType();
  11184. }
  11185. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  11186. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  11187. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  11188. diag::err_invalid_thread)
  11189. << DeclSpec::getSpecifierName(TSCS);
  11190. // Check to see if this name was declared as a member previously
  11191. NamedDecl *PrevDecl = nullptr;
  11192. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  11193. LookupName(Previous, S);
  11194. switch (Previous.getResultKind()) {
  11195. case LookupResult::Found:
  11196. case LookupResult::FoundUnresolvedValue:
  11197. PrevDecl = Previous.getAsSingle<NamedDecl>();
  11198. break;
  11199. case LookupResult::FoundOverloaded:
  11200. PrevDecl = Previous.getRepresentativeDecl();
  11201. break;
  11202. case LookupResult::NotFound:
  11203. case LookupResult::NotFoundInCurrentInstantiation:
  11204. case LookupResult::Ambiguous:
  11205. break;
  11206. }
  11207. Previous.suppressDiagnostics();
  11208. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  11209. // Maybe we will complain about the shadowed template parameter.
  11210. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11211. // Just pretend that we didn't see the previous declaration.
  11212. PrevDecl = nullptr;
  11213. }
  11214. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  11215. PrevDecl = nullptr;
  11216. bool Mutable
  11217. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  11218. SourceLocation TSSL = D.getLocStart();
  11219. FieldDecl *NewFD
  11220. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  11221. TSSL, AS, PrevDecl, &D);
  11222. if (NewFD->isInvalidDecl())
  11223. Record->setInvalidDecl();
  11224. if (D.getDeclSpec().isModulePrivateSpecified())
  11225. NewFD->setModulePrivate();
  11226. if (NewFD->isInvalidDecl() && PrevDecl) {
  11227. // Don't introduce NewFD into scope; there's already something
  11228. // with the same name in the same scope.
  11229. } else if (II) {
  11230. PushOnScopeChains(NewFD, S);
  11231. } else
  11232. Record->addDecl(NewFD);
  11233. return NewFD;
  11234. }
  11235. /// \brief Build a new FieldDecl and check its well-formedness.
  11236. ///
  11237. /// This routine builds a new FieldDecl given the fields name, type,
  11238. /// record, etc. \p PrevDecl should refer to any previous declaration
  11239. /// with the same name and in the same scope as the field to be
  11240. /// created.
  11241. ///
  11242. /// \returns a new FieldDecl.
  11243. ///
  11244. /// \todo The Declarator argument is a hack. It will be removed once
  11245. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  11246. TypeSourceInfo *TInfo,
  11247. RecordDecl *Record, SourceLocation Loc,
  11248. bool Mutable, Expr *BitWidth,
  11249. InClassInitStyle InitStyle,
  11250. SourceLocation TSSL,
  11251. AccessSpecifier AS, NamedDecl *PrevDecl,
  11252. Declarator *D) {
  11253. IdentifierInfo *II = Name.getAsIdentifierInfo();
  11254. bool InvalidDecl = false;
  11255. if (D) InvalidDecl = D->isInvalidType();
  11256. // If we receive a broken type, recover by assuming 'int' and
  11257. // marking this declaration as invalid.
  11258. if (T.isNull()) {
  11259. InvalidDecl = true;
  11260. T = Context.IntTy;
  11261. }
  11262. QualType EltTy = Context.getBaseElementType(T);
  11263. if (!EltTy->isDependentType()) {
  11264. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  11265. // Fields of incomplete type force their record to be invalid.
  11266. Record->setInvalidDecl();
  11267. InvalidDecl = true;
  11268. } else {
  11269. NamedDecl *Def;
  11270. EltTy->isIncompleteType(&Def);
  11271. if (Def && Def->isInvalidDecl()) {
  11272. Record->setInvalidDecl();
  11273. InvalidDecl = true;
  11274. }
  11275. }
  11276. }
  11277. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  11278. if (BitWidth && getLangOpts().OpenCL) {
  11279. Diag(Loc, diag::err_opencl_bitfields);
  11280. InvalidDecl = true;
  11281. }
  11282. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  11283. // than a variably modified type.
  11284. if (!InvalidDecl && T->isVariablyModifiedType()) {
  11285. bool SizeIsNegative;
  11286. llvm::APSInt Oversized;
  11287. TypeSourceInfo *FixedTInfo =
  11288. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  11289. SizeIsNegative,
  11290. Oversized);
  11291. if (FixedTInfo) {
  11292. Diag(Loc, diag::warn_illegal_constant_array_size);
  11293. TInfo = FixedTInfo;
  11294. T = FixedTInfo->getType();
  11295. } else {
  11296. if (SizeIsNegative)
  11297. Diag(Loc, diag::err_typecheck_negative_array_size);
  11298. else if (Oversized.getBoolValue())
  11299. Diag(Loc, diag::err_array_too_large)
  11300. << Oversized.toString(10);
  11301. else
  11302. Diag(Loc, diag::err_typecheck_field_variable_size);
  11303. InvalidDecl = true;
  11304. }
  11305. }
  11306. // Fields can not have abstract class types
  11307. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  11308. diag::err_abstract_type_in_decl,
  11309. AbstractFieldType))
  11310. InvalidDecl = true;
  11311. bool ZeroWidth = false;
  11312. if (InvalidDecl)
  11313. BitWidth = nullptr;
  11314. // If this is declared as a bit-field, check the bit-field.
  11315. if (BitWidth) {
  11316. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  11317. &ZeroWidth).get();
  11318. if (!BitWidth) {
  11319. InvalidDecl = true;
  11320. BitWidth = nullptr;
  11321. ZeroWidth = false;
  11322. }
  11323. }
  11324. // Check that 'mutable' is consistent with the type of the declaration.
  11325. if (!InvalidDecl && Mutable) {
  11326. unsigned DiagID = 0;
  11327. if (T->isReferenceType())
  11328. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  11329. : diag::err_mutable_reference;
  11330. else if (T.isConstQualified())
  11331. DiagID = diag::err_mutable_const;
  11332. if (DiagID) {
  11333. SourceLocation ErrLoc = Loc;
  11334. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  11335. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  11336. Diag(ErrLoc, DiagID);
  11337. if (DiagID != diag::ext_mutable_reference) {
  11338. Mutable = false;
  11339. InvalidDecl = true;
  11340. }
  11341. }
  11342. }
  11343. // C++11 [class.union]p8 (DR1460):
  11344. // At most one variant member of a union may have a
  11345. // brace-or-equal-initializer.
  11346. if (InitStyle != ICIS_NoInit)
  11347. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  11348. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  11349. BitWidth, Mutable, InitStyle);
  11350. if (InvalidDecl)
  11351. NewFD->setInvalidDecl();
  11352. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  11353. Diag(Loc, diag::err_duplicate_member) << II;
  11354. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  11355. NewFD->setInvalidDecl();
  11356. }
  11357. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  11358. if (Record->isUnion()) {
  11359. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  11360. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  11361. if (RDecl->getDefinition()) {
  11362. // C++ [class.union]p1: An object of a class with a non-trivial
  11363. // constructor, a non-trivial copy constructor, a non-trivial
  11364. // destructor, or a non-trivial copy assignment operator
  11365. // cannot be a member of a union, nor can an array of such
  11366. // objects.
  11367. if (CheckNontrivialField(NewFD))
  11368. NewFD->setInvalidDecl();
  11369. }
  11370. }
  11371. // C++ [class.union]p1: If a union contains a member of reference type,
  11372. // the program is ill-formed, except when compiling with MSVC extensions
  11373. // enabled.
  11374. if (EltTy->isReferenceType()) {
  11375. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  11376. diag::ext_union_member_of_reference_type :
  11377. diag::err_union_member_of_reference_type)
  11378. << NewFD->getDeclName() << EltTy;
  11379. if (!getLangOpts().MicrosoftExt)
  11380. NewFD->setInvalidDecl();
  11381. }
  11382. }
  11383. }
  11384. // FIXME: We need to pass in the attributes given an AST
  11385. // representation, not a parser representation.
  11386. if (D) {
  11387. // FIXME: The current scope is almost... but not entirely... correct here.
  11388. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  11389. if (NewFD->hasAttrs())
  11390. CheckAlignasUnderalignment(NewFD);
  11391. }
  11392. // In auto-retain/release, infer strong retension for fields of
  11393. // retainable type.
  11394. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  11395. NewFD->setInvalidDecl();
  11396. if (T.isObjCGCWeak())
  11397. Diag(Loc, diag::warn_attribute_weak_on_field);
  11398. NewFD->setAccess(AS);
  11399. return NewFD;
  11400. }
  11401. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  11402. assert(FD);
  11403. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  11404. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  11405. return false;
  11406. QualType EltTy = Context.getBaseElementType(FD->getType());
  11407. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  11408. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  11409. if (RDecl->getDefinition()) {
  11410. // We check for copy constructors before constructors
  11411. // because otherwise we'll never get complaints about
  11412. // copy constructors.
  11413. CXXSpecialMember member = CXXInvalid;
  11414. // We're required to check for any non-trivial constructors. Since the
  11415. // implicit default constructor is suppressed if there are any
  11416. // user-declared constructors, we just need to check that there is a
  11417. // trivial default constructor and a trivial copy constructor. (We don't
  11418. // worry about move constructors here, since this is a C++98 check.)
  11419. if (RDecl->hasNonTrivialCopyConstructor())
  11420. member = CXXCopyConstructor;
  11421. else if (!RDecl->hasTrivialDefaultConstructor())
  11422. member = CXXDefaultConstructor;
  11423. else if (RDecl->hasNonTrivialCopyAssignment())
  11424. member = CXXCopyAssignment;
  11425. else if (RDecl->hasNonTrivialDestructor())
  11426. member = CXXDestructor;
  11427. if (member != CXXInvalid) {
  11428. if (!getLangOpts().CPlusPlus11 &&
  11429. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  11430. // Objective-C++ ARC: it is an error to have a non-trivial field of
  11431. // a union. However, system headers in Objective-C programs
  11432. // occasionally have Objective-C lifetime objects within unions,
  11433. // and rather than cause the program to fail, we make those
  11434. // members unavailable.
  11435. SourceLocation Loc = FD->getLocation();
  11436. if (getSourceManager().isInSystemHeader(Loc)) {
  11437. if (!FD->hasAttr<UnavailableAttr>())
  11438. FD->addAttr(UnavailableAttr::CreateImplicit(Context,
  11439. "this system field has retaining ownership",
  11440. Loc));
  11441. return false;
  11442. }
  11443. }
  11444. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  11445. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  11446. diag::err_illegal_union_or_anon_struct_member)
  11447. << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
  11448. DiagnoseNontrivial(RDecl, member);
  11449. return !getLangOpts().CPlusPlus11;
  11450. }
  11451. }
  11452. }
  11453. return false;
  11454. }
  11455. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  11456. /// AST enum value.
  11457. static ObjCIvarDecl::AccessControl
  11458. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  11459. switch (ivarVisibility) {
  11460. default: llvm_unreachable("Unknown visitibility kind");
  11461. case tok::objc_private: return ObjCIvarDecl::Private;
  11462. case tok::objc_public: return ObjCIvarDecl::Public;
  11463. case tok::objc_protected: return ObjCIvarDecl::Protected;
  11464. case tok::objc_package: return ObjCIvarDecl::Package;
  11465. }
  11466. }
  11467. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  11468. /// in order to create an IvarDecl object for it.
  11469. Decl *Sema::ActOnIvar(Scope *S,
  11470. SourceLocation DeclStart,
  11471. Declarator &D, Expr *BitfieldWidth,
  11472. tok::ObjCKeywordKind Visibility) {
  11473. IdentifierInfo *II = D.getIdentifier();
  11474. Expr *BitWidth = (Expr*)BitfieldWidth;
  11475. SourceLocation Loc = DeclStart;
  11476. if (II) Loc = D.getIdentifierLoc();
  11477. // FIXME: Unnamed fields can be handled in various different ways, for
  11478. // example, unnamed unions inject all members into the struct namespace!
  11479. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11480. QualType T = TInfo->getType();
  11481. if (BitWidth) {
  11482. // 6.7.2.1p3, 6.7.2.1p4
  11483. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  11484. if (!BitWidth)
  11485. D.setInvalidType();
  11486. } else {
  11487. // Not a bitfield.
  11488. // validate II.
  11489. }
  11490. if (T->isReferenceType()) {
  11491. Diag(Loc, diag::err_ivar_reference_type);
  11492. D.setInvalidType();
  11493. }
  11494. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  11495. // than a variably modified type.
  11496. else if (T->isVariablyModifiedType()) {
  11497. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  11498. D.setInvalidType();
  11499. }
  11500. // Get the visibility (access control) for this ivar.
  11501. ObjCIvarDecl::AccessControl ac =
  11502. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  11503. : ObjCIvarDecl::None;
  11504. // Must set ivar's DeclContext to its enclosing interface.
  11505. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  11506. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  11507. return nullptr;
  11508. ObjCContainerDecl *EnclosingContext;
  11509. if (ObjCImplementationDecl *IMPDecl =
  11510. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  11511. if (LangOpts.ObjCRuntime.isFragile()) {
  11512. // Case of ivar declared in an implementation. Context is that of its class.
  11513. EnclosingContext = IMPDecl->getClassInterface();
  11514. assert(EnclosingContext && "Implementation has no class interface!");
  11515. }
  11516. else
  11517. EnclosingContext = EnclosingDecl;
  11518. } else {
  11519. if (ObjCCategoryDecl *CDecl =
  11520. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  11521. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  11522. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  11523. return nullptr;
  11524. }
  11525. }
  11526. EnclosingContext = EnclosingDecl;
  11527. }
  11528. // Construct the decl.
  11529. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  11530. DeclStart, Loc, II, T,
  11531. TInfo, ac, (Expr *)BitfieldWidth);
  11532. if (II) {
  11533. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  11534. ForRedeclaration);
  11535. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  11536. && !isa<TagDecl>(PrevDecl)) {
  11537. Diag(Loc, diag::err_duplicate_member) << II;
  11538. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  11539. NewID->setInvalidDecl();
  11540. }
  11541. }
  11542. // Process attributes attached to the ivar.
  11543. ProcessDeclAttributes(S, NewID, D);
  11544. if (D.isInvalidType())
  11545. NewID->setInvalidDecl();
  11546. // In ARC, infer 'retaining' for ivars of retainable type.
  11547. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  11548. NewID->setInvalidDecl();
  11549. if (D.getDeclSpec().isModulePrivateSpecified())
  11550. NewID->setModulePrivate();
  11551. if (II) {
  11552. // FIXME: When interfaces are DeclContexts, we'll need to add
  11553. // these to the interface.
  11554. S->AddDecl(NewID);
  11555. IdResolver.AddDecl(NewID);
  11556. }
  11557. if (LangOpts.ObjCRuntime.isNonFragile() &&
  11558. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  11559. Diag(Loc, diag::warn_ivars_in_interface);
  11560. return NewID;
  11561. }
  11562. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  11563. /// class and class extensions. For every class \@interface and class
  11564. /// extension \@interface, if the last ivar is a bitfield of any type,
  11565. /// then add an implicit `char :0` ivar to the end of that interface.
  11566. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  11567. SmallVectorImpl<Decl *> &AllIvarDecls) {
  11568. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  11569. return;
  11570. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  11571. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  11572. if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
  11573. return;
  11574. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  11575. if (!ID) {
  11576. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  11577. if (!CD->IsClassExtension())
  11578. return;
  11579. }
  11580. // No need to add this to end of @implementation.
  11581. else
  11582. return;
  11583. }
  11584. // All conditions are met. Add a new bitfield to the tail end of ivars.
  11585. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  11586. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  11587. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  11588. DeclLoc, DeclLoc, nullptr,
  11589. Context.CharTy,
  11590. Context.getTrivialTypeSourceInfo(Context.CharTy,
  11591. DeclLoc),
  11592. ObjCIvarDecl::Private, BW,
  11593. true);
  11594. AllIvarDecls.push_back(Ivar);
  11595. }
  11596. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  11597. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  11598. SourceLocation RBrac, AttributeList *Attr) {
  11599. assert(EnclosingDecl && "missing record or interface decl");
  11600. // If this is an Objective-C @implementation or category and we have
  11601. // new fields here we should reset the layout of the interface since
  11602. // it will now change.
  11603. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  11604. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  11605. switch (DC->getKind()) {
  11606. default: break;
  11607. case Decl::ObjCCategory:
  11608. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  11609. break;
  11610. case Decl::ObjCImplementation:
  11611. Context.
  11612. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  11613. break;
  11614. }
  11615. }
  11616. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  11617. // Start counting up the number of named members; make sure to include
  11618. // members of anonymous structs and unions in the total.
  11619. unsigned NumNamedMembers = 0;
  11620. if (Record) {
  11621. for (const auto *I : Record->decls()) {
  11622. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  11623. if (IFD->getDeclName())
  11624. ++NumNamedMembers;
  11625. }
  11626. }
  11627. // Verify that all the fields are okay.
  11628. SmallVector<FieldDecl*, 32> RecFields;
  11629. bool ARCErrReported = false;
  11630. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  11631. i != end; ++i) {
  11632. FieldDecl *FD = cast<FieldDecl>(*i);
  11633. // Get the type for the field.
  11634. const Type *FDTy = FD->getType().getTypePtr();
  11635. if (!FD->isAnonymousStructOrUnion()) {
  11636. // Remember all fields written by the user.
  11637. RecFields.push_back(FD);
  11638. }
  11639. // If the field is already invalid for some reason, don't emit more
  11640. // diagnostics about it.
  11641. if (FD->isInvalidDecl()) {
  11642. EnclosingDecl->setInvalidDecl();
  11643. continue;
  11644. }
  11645. // C99 6.7.2.1p2:
  11646. // A structure or union shall not contain a member with
  11647. // incomplete or function type (hence, a structure shall not
  11648. // contain an instance of itself, but may contain a pointer to
  11649. // an instance of itself), except that the last member of a
  11650. // structure with more than one named member may have incomplete
  11651. // array type; such a structure (and any union containing,
  11652. // possibly recursively, a member that is such a structure)
  11653. // shall not be a member of a structure or an element of an
  11654. // array.
  11655. if (FDTy->isFunctionType()) {
  11656. // Field declared as a function.
  11657. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  11658. << FD->getDeclName();
  11659. FD->setInvalidDecl();
  11660. EnclosingDecl->setInvalidDecl();
  11661. continue;
  11662. } else if (FDTy->isIncompleteArrayType() && Record &&
  11663. ((i + 1 == Fields.end() && !Record->isUnion()) ||
  11664. ((getLangOpts().MicrosoftExt ||
  11665. getLangOpts().CPlusPlus) &&
  11666. (i + 1 == Fields.end() || Record->isUnion())))) {
  11667. // Flexible array member.
  11668. // Microsoft and g++ is more permissive regarding flexible array.
  11669. // It will accept flexible array in union and also
  11670. // as the sole element of a struct/class.
  11671. unsigned DiagID = 0;
  11672. if (Record->isUnion())
  11673. DiagID = getLangOpts().MicrosoftExt
  11674. ? diag::ext_flexible_array_union_ms
  11675. : getLangOpts().CPlusPlus
  11676. ? diag::ext_flexible_array_union_gnu
  11677. : diag::err_flexible_array_union;
  11678. else if (Fields.size() == 1)
  11679. DiagID = getLangOpts().MicrosoftExt
  11680. ? diag::ext_flexible_array_empty_aggregate_ms
  11681. : getLangOpts().CPlusPlus
  11682. ? diag::ext_flexible_array_empty_aggregate_gnu
  11683. : NumNamedMembers < 1
  11684. ? diag::err_flexible_array_empty_aggregate
  11685. : 0;
  11686. if (DiagID)
  11687. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  11688. << Record->getTagKind();
  11689. // While the layout of types that contain virtual bases is not specified
  11690. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  11691. // virtual bases after the derived members. This would make a flexible
  11692. // array member declared at the end of an object not adjacent to the end
  11693. // of the type.
  11694. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
  11695. if (RD->getNumVBases() != 0)
  11696. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  11697. << FD->getDeclName() << Record->getTagKind();
  11698. if (!getLangOpts().C99)
  11699. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  11700. << FD->getDeclName() << Record->getTagKind();
  11701. // If the element type has a non-trivial destructor, we would not
  11702. // implicitly destroy the elements, so disallow it for now.
  11703. //
  11704. // FIXME: GCC allows this. We should probably either implicitly delete
  11705. // the destructor of the containing class, or just allow this.
  11706. QualType BaseElem = Context.getBaseElementType(FD->getType());
  11707. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  11708. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  11709. << FD->getDeclName() << FD->getType();
  11710. FD->setInvalidDecl();
  11711. EnclosingDecl->setInvalidDecl();
  11712. continue;
  11713. }
  11714. // Okay, we have a legal flexible array member at the end of the struct.
  11715. Record->setHasFlexibleArrayMember(true);
  11716. } else if (!FDTy->isDependentType() &&
  11717. RequireCompleteType(FD->getLocation(), FD->getType(),
  11718. diag::err_field_incomplete)) {
  11719. // Incomplete type
  11720. FD->setInvalidDecl();
  11721. EnclosingDecl->setInvalidDecl();
  11722. continue;
  11723. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  11724. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  11725. // A type which contains a flexible array member is considered to be a
  11726. // flexible array member.
  11727. Record->setHasFlexibleArrayMember(true);
  11728. if (!Record->isUnion()) {
  11729. // If this is a struct/class and this is not the last element, reject
  11730. // it. Note that GCC supports variable sized arrays in the middle of
  11731. // structures.
  11732. if (i + 1 != Fields.end())
  11733. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  11734. << FD->getDeclName() << FD->getType();
  11735. else {
  11736. // We support flexible arrays at the end of structs in
  11737. // other structs as an extension.
  11738. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  11739. << FD->getDeclName();
  11740. }
  11741. }
  11742. }
  11743. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  11744. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  11745. diag::err_abstract_type_in_decl,
  11746. AbstractIvarType)) {
  11747. // Ivars can not have abstract class types
  11748. FD->setInvalidDecl();
  11749. }
  11750. if (Record && FDTTy->getDecl()->hasObjectMember())
  11751. Record->setHasObjectMember(true);
  11752. if (Record && FDTTy->getDecl()->hasVolatileMember())
  11753. Record->setHasVolatileMember(true);
  11754. } else if (FDTy->isObjCObjectType()) {
  11755. /// A field cannot be an Objective-c object
  11756. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  11757. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  11758. QualType T = Context.getObjCObjectPointerType(FD->getType());
  11759. FD->setType(T);
  11760. } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
  11761. (!getLangOpts().CPlusPlus || Record->isUnion())) {
  11762. // It's an error in ARC if a field has lifetime.
  11763. // We don't want to report this in a system header, though,
  11764. // so we just make the field unavailable.
  11765. // FIXME: that's really not sufficient; we need to make the type
  11766. // itself invalid to, say, initialize or copy.
  11767. QualType T = FD->getType();
  11768. Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
  11769. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
  11770. SourceLocation loc = FD->getLocation();
  11771. if (getSourceManager().isInSystemHeader(loc)) {
  11772. if (!FD->hasAttr<UnavailableAttr>()) {
  11773. FD->addAttr(UnavailableAttr::CreateImplicit(Context,
  11774. "this system field has retaining ownership",
  11775. loc));
  11776. }
  11777. } else {
  11778. Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
  11779. << T->isBlockPointerType() << Record->getTagKind();
  11780. }
  11781. ARCErrReported = true;
  11782. }
  11783. } else if (getLangOpts().ObjC1 &&
  11784. getLangOpts().getGC() != LangOptions::NonGC &&
  11785. Record && !Record->hasObjectMember()) {
  11786. if (FD->getType()->isObjCObjectPointerType() ||
  11787. FD->getType().isObjCGCStrong())
  11788. Record->setHasObjectMember(true);
  11789. else if (Context.getAsArrayType(FD->getType())) {
  11790. QualType BaseType = Context.getBaseElementType(FD->getType());
  11791. if (BaseType->isRecordType() &&
  11792. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  11793. Record->setHasObjectMember(true);
  11794. else if (BaseType->isObjCObjectPointerType() ||
  11795. BaseType.isObjCGCStrong())
  11796. Record->setHasObjectMember(true);
  11797. }
  11798. }
  11799. if (Record && FD->getType().isVolatileQualified())
  11800. Record->setHasVolatileMember(true);
  11801. // Keep track of the number of named members.
  11802. if (FD->getIdentifier())
  11803. ++NumNamedMembers;
  11804. }
  11805. // Okay, we successfully defined 'Record'.
  11806. if (Record) {
  11807. bool Completed = false;
  11808. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  11809. if (!CXXRecord->isInvalidDecl()) {
  11810. // Set access bits correctly on the directly-declared conversions.
  11811. for (CXXRecordDecl::conversion_iterator
  11812. I = CXXRecord->conversion_begin(),
  11813. E = CXXRecord->conversion_end(); I != E; ++I)
  11814. I.setAccess((*I)->getAccess());
  11815. if (!CXXRecord->isDependentType()) {
  11816. if (CXXRecord->hasUserDeclaredDestructor()) {
  11817. // Adjust user-defined destructor exception spec.
  11818. if (getLangOpts().CPlusPlus11)
  11819. AdjustDestructorExceptionSpec(CXXRecord,
  11820. CXXRecord->getDestructor());
  11821. }
  11822. // Add any implicitly-declared members to this class.
  11823. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  11824. // If we have virtual base classes, we may end up finding multiple
  11825. // final overriders for a given virtual function. Check for this
  11826. // problem now.
  11827. if (CXXRecord->getNumVBases()) {
  11828. CXXFinalOverriderMap FinalOverriders;
  11829. CXXRecord->getFinalOverriders(FinalOverriders);
  11830. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  11831. MEnd = FinalOverriders.end();
  11832. M != MEnd; ++M) {
  11833. for (OverridingMethods::iterator SO = M->second.begin(),
  11834. SOEnd = M->second.end();
  11835. SO != SOEnd; ++SO) {
  11836. assert(SO->second.size() > 0 &&
  11837. "Virtual function without overridding functions?");
  11838. if (SO->second.size() == 1)
  11839. continue;
  11840. // C++ [class.virtual]p2:
  11841. // In a derived class, if a virtual member function of a base
  11842. // class subobject has more than one final overrider the
  11843. // program is ill-formed.
  11844. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  11845. << (const NamedDecl *)M->first << Record;
  11846. Diag(M->first->getLocation(),
  11847. diag::note_overridden_virtual_function);
  11848. for (OverridingMethods::overriding_iterator
  11849. OM = SO->second.begin(),
  11850. OMEnd = SO->second.end();
  11851. OM != OMEnd; ++OM)
  11852. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  11853. << (const NamedDecl *)M->first << OM->Method->getParent();
  11854. Record->setInvalidDecl();
  11855. }
  11856. }
  11857. CXXRecord->completeDefinition(&FinalOverriders);
  11858. Completed = true;
  11859. }
  11860. }
  11861. }
  11862. }
  11863. if (!Completed)
  11864. Record->completeDefinition();
  11865. if (Record->hasAttrs()) {
  11866. CheckAlignasUnderalignment(Record);
  11867. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  11868. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  11869. IA->getRange(), IA->getBestCase(),
  11870. IA->getSemanticSpelling());
  11871. }
  11872. // Check if the structure/union declaration is a type that can have zero
  11873. // size in C. For C this is a language extension, for C++ it may cause
  11874. // compatibility problems.
  11875. bool CheckForZeroSize;
  11876. if (!getLangOpts().CPlusPlus) {
  11877. CheckForZeroSize = true;
  11878. } else {
  11879. // For C++ filter out types that cannot be referenced in C code.
  11880. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  11881. CheckForZeroSize =
  11882. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  11883. !CXXRecord->isDependentType() &&
  11884. CXXRecord->isCLike();
  11885. }
  11886. if (CheckForZeroSize) {
  11887. bool ZeroSize = true;
  11888. bool IsEmpty = true;
  11889. unsigned NonBitFields = 0;
  11890. for (RecordDecl::field_iterator I = Record->field_begin(),
  11891. E = Record->field_end();
  11892. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  11893. IsEmpty = false;
  11894. if (I->isUnnamedBitfield()) {
  11895. if (I->getBitWidthValue(Context) > 0)
  11896. ZeroSize = false;
  11897. } else {
  11898. ++NonBitFields;
  11899. QualType FieldType = I->getType();
  11900. if (FieldType->isIncompleteType() ||
  11901. !Context.getTypeSizeInChars(FieldType).isZero())
  11902. ZeroSize = false;
  11903. }
  11904. }
  11905. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  11906. // allowed in C++, but warn if its declaration is inside
  11907. // extern "C" block.
  11908. if (ZeroSize) {
  11909. Diag(RecLoc, getLangOpts().CPlusPlus ?
  11910. diag::warn_zero_size_struct_union_in_extern_c :
  11911. diag::warn_zero_size_struct_union_compat)
  11912. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  11913. }
  11914. // Structs without named members are extension in C (C99 6.7.2.1p7),
  11915. // but are accepted by GCC.
  11916. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  11917. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  11918. diag::ext_no_named_members_in_struct_union)
  11919. << Record->isUnion();
  11920. }
  11921. }
  11922. } else {
  11923. ObjCIvarDecl **ClsFields =
  11924. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  11925. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  11926. ID->setEndOfDefinitionLoc(RBrac);
  11927. // Add ivar's to class's DeclContext.
  11928. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  11929. ClsFields[i]->setLexicalDeclContext(ID);
  11930. ID->addDecl(ClsFields[i]);
  11931. }
  11932. // Must enforce the rule that ivars in the base classes may not be
  11933. // duplicates.
  11934. if (ID->getSuperClass())
  11935. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  11936. } else if (ObjCImplementationDecl *IMPDecl =
  11937. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  11938. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  11939. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  11940. // Ivar declared in @implementation never belongs to the implementation.
  11941. // Only it is in implementation's lexical context.
  11942. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  11943. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  11944. IMPDecl->setIvarLBraceLoc(LBrac);
  11945. IMPDecl->setIvarRBraceLoc(RBrac);
  11946. } else if (ObjCCategoryDecl *CDecl =
  11947. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  11948. // case of ivars in class extension; all other cases have been
  11949. // reported as errors elsewhere.
  11950. // FIXME. Class extension does not have a LocEnd field.
  11951. // CDecl->setLocEnd(RBrac);
  11952. // Add ivar's to class extension's DeclContext.
  11953. // Diagnose redeclaration of private ivars.
  11954. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  11955. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  11956. if (IDecl) {
  11957. if (const ObjCIvarDecl *ClsIvar =
  11958. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  11959. Diag(ClsFields[i]->getLocation(),
  11960. diag::err_duplicate_ivar_declaration);
  11961. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  11962. continue;
  11963. }
  11964. for (const auto *Ext : IDecl->known_extensions()) {
  11965. if (const ObjCIvarDecl *ClsExtIvar
  11966. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  11967. Diag(ClsFields[i]->getLocation(),
  11968. diag::err_duplicate_ivar_declaration);
  11969. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  11970. continue;
  11971. }
  11972. }
  11973. }
  11974. ClsFields[i]->setLexicalDeclContext(CDecl);
  11975. CDecl->addDecl(ClsFields[i]);
  11976. }
  11977. CDecl->setIvarLBraceLoc(LBrac);
  11978. CDecl->setIvarRBraceLoc(RBrac);
  11979. }
  11980. }
  11981. if (Attr)
  11982. ProcessDeclAttributeList(S, Record, Attr);
  11983. }
  11984. /// \brief Determine whether the given integral value is representable within
  11985. /// the given type T.
  11986. static bool isRepresentableIntegerValue(ASTContext &Context,
  11987. llvm::APSInt &Value,
  11988. QualType T) {
  11989. assert(T->isIntegralType(Context) && "Integral type required!");
  11990. unsigned BitWidth = Context.getIntWidth(T);
  11991. if (Value.isUnsigned() || Value.isNonNegative()) {
  11992. if (T->isSignedIntegerOrEnumerationType())
  11993. --BitWidth;
  11994. return Value.getActiveBits() <= BitWidth;
  11995. }
  11996. return Value.getMinSignedBits() <= BitWidth;
  11997. }
  11998. // \brief Given an integral type, return the next larger integral type
  11999. // (or a NULL type of no such type exists).
  12000. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  12001. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  12002. // enum checking below.
  12003. assert(T->isIntegralType(Context) && "Integral type required!");
  12004. const unsigned NumTypes = 4;
  12005. QualType SignedIntegralTypes[NumTypes] = {
  12006. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  12007. };
  12008. QualType UnsignedIntegralTypes[NumTypes] = {
  12009. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  12010. Context.UnsignedLongLongTy
  12011. };
  12012. unsigned BitWidth = Context.getTypeSize(T);
  12013. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  12014. : UnsignedIntegralTypes;
  12015. for (unsigned I = 0; I != NumTypes; ++I)
  12016. if (Context.getTypeSize(Types[I]) > BitWidth)
  12017. return Types[I];
  12018. return QualType();
  12019. }
  12020. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  12021. EnumConstantDecl *LastEnumConst,
  12022. SourceLocation IdLoc,
  12023. IdentifierInfo *Id,
  12024. Expr *Val) {
  12025. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  12026. llvm::APSInt EnumVal(IntWidth);
  12027. QualType EltTy;
  12028. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  12029. Val = nullptr;
  12030. if (Val)
  12031. Val = DefaultLvalueConversion(Val).get();
  12032. if (Val) {
  12033. if (Enum->isDependentType() || Val->isTypeDependent())
  12034. EltTy = Context.DependentTy;
  12035. else {
  12036. SourceLocation ExpLoc;
  12037. if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
  12038. !getLangOpts().MSVCCompat) {
  12039. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  12040. // constant-expression in the enumerator-definition shall be a converted
  12041. // constant expression of the underlying type.
  12042. EltTy = Enum->getIntegerType();
  12043. ExprResult Converted =
  12044. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  12045. CCEK_Enumerator);
  12046. if (Converted.isInvalid())
  12047. Val = nullptr;
  12048. else
  12049. Val = Converted.get();
  12050. } else if (!Val->isValueDependent() &&
  12051. !(Val = VerifyIntegerConstantExpression(Val,
  12052. &EnumVal).get())) {
  12053. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  12054. } else {
  12055. if (Enum->isFixed()) {
  12056. EltTy = Enum->getIntegerType();
  12057. // In Obj-C and Microsoft mode, require the enumeration value to be
  12058. // representable in the underlying type of the enumeration. In C++11,
  12059. // we perform a non-narrowing conversion as part of converted constant
  12060. // expression checking.
  12061. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  12062. if (getLangOpts().MSVCCompat) {
  12063. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  12064. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  12065. } else
  12066. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  12067. } else
  12068. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  12069. } else if (getLangOpts().CPlusPlus) {
  12070. // C++11 [dcl.enum]p5:
  12071. // If the underlying type is not fixed, the type of each enumerator
  12072. // is the type of its initializing value:
  12073. // - If an initializer is specified for an enumerator, the
  12074. // initializing value has the same type as the expression.
  12075. EltTy = Val->getType();
  12076. } else {
  12077. // C99 6.7.2.2p2:
  12078. // The expression that defines the value of an enumeration constant
  12079. // shall be an integer constant expression that has a value
  12080. // representable as an int.
  12081. // Complain if the value is not representable in an int.
  12082. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  12083. Diag(IdLoc, diag::ext_enum_value_not_int)
  12084. << EnumVal.toString(10) << Val->getSourceRange()
  12085. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  12086. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  12087. // Force the type of the expression to 'int'.
  12088. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  12089. }
  12090. EltTy = Val->getType();
  12091. }
  12092. }
  12093. }
  12094. }
  12095. if (!Val) {
  12096. if (Enum->isDependentType())
  12097. EltTy = Context.DependentTy;
  12098. else if (!LastEnumConst) {
  12099. // C++0x [dcl.enum]p5:
  12100. // If the underlying type is not fixed, the type of each enumerator
  12101. // is the type of its initializing value:
  12102. // - If no initializer is specified for the first enumerator, the
  12103. // initializing value has an unspecified integral type.
  12104. //
  12105. // GCC uses 'int' for its unspecified integral type, as does
  12106. // C99 6.7.2.2p3.
  12107. if (Enum->isFixed()) {
  12108. EltTy = Enum->getIntegerType();
  12109. }
  12110. else {
  12111. EltTy = Context.IntTy;
  12112. }
  12113. } else {
  12114. // Assign the last value + 1.
  12115. EnumVal = LastEnumConst->getInitVal();
  12116. ++EnumVal;
  12117. EltTy = LastEnumConst->getType();
  12118. // Check for overflow on increment.
  12119. if (EnumVal < LastEnumConst->getInitVal()) {
  12120. // C++0x [dcl.enum]p5:
  12121. // If the underlying type is not fixed, the type of each enumerator
  12122. // is the type of its initializing value:
  12123. //
  12124. // - Otherwise the type of the initializing value is the same as
  12125. // the type of the initializing value of the preceding enumerator
  12126. // unless the incremented value is not representable in that type,
  12127. // in which case the type is an unspecified integral type
  12128. // sufficient to contain the incremented value. If no such type
  12129. // exists, the program is ill-formed.
  12130. QualType T = getNextLargerIntegralType(Context, EltTy);
  12131. if (T.isNull() || Enum->isFixed()) {
  12132. // There is no integral type larger enough to represent this
  12133. // value. Complain, then allow the value to wrap around.
  12134. EnumVal = LastEnumConst->getInitVal();
  12135. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  12136. ++EnumVal;
  12137. if (Enum->isFixed())
  12138. // When the underlying type is fixed, this is ill-formed.
  12139. Diag(IdLoc, diag::err_enumerator_wrapped)
  12140. << EnumVal.toString(10)
  12141. << EltTy;
  12142. else
  12143. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  12144. << EnumVal.toString(10);
  12145. } else {
  12146. EltTy = T;
  12147. }
  12148. // Retrieve the last enumerator's value, extent that type to the
  12149. // type that is supposed to be large enough to represent the incremented
  12150. // value, then increment.
  12151. EnumVal = LastEnumConst->getInitVal();
  12152. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  12153. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  12154. ++EnumVal;
  12155. // If we're not in C++, diagnose the overflow of enumerator values,
  12156. // which in C99 means that the enumerator value is not representable in
  12157. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  12158. // permits enumerator values that are representable in some larger
  12159. // integral type.
  12160. if (!getLangOpts().CPlusPlus && !T.isNull())
  12161. Diag(IdLoc, diag::warn_enum_value_overflow);
  12162. } else if (!getLangOpts().CPlusPlus &&
  12163. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  12164. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  12165. Diag(IdLoc, diag::ext_enum_value_not_int)
  12166. << EnumVal.toString(10) << 1;
  12167. }
  12168. }
  12169. }
  12170. if (!EltTy->isDependentType()) {
  12171. // Make the enumerator value match the signedness and size of the
  12172. // enumerator's type.
  12173. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  12174. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  12175. }
  12176. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  12177. Val, EnumVal);
  12178. }
  12179. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  12180. SourceLocation IILoc) {
  12181. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  12182. !getLangOpts().CPlusPlus)
  12183. return SkipBodyInfo();
  12184. // We have an anonymous enum definition. Look up the first enumerator to
  12185. // determine if we should merge the definition with an existing one and
  12186. // skip the body.
  12187. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  12188. ForRedeclaration);
  12189. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  12190. NamedDecl *Hidden;
  12191. if (PrevECD &&
  12192. !hasVisibleDefinition(cast<NamedDecl>(PrevECD->getDeclContext()),
  12193. &Hidden)) {
  12194. SkipBodyInfo Skip;
  12195. Skip.Previous = Hidden;
  12196. return Skip;
  12197. }
  12198. return SkipBodyInfo();
  12199. }
  12200. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  12201. SourceLocation IdLoc, IdentifierInfo *Id,
  12202. AttributeList *Attr,
  12203. SourceLocation EqualLoc, Expr *Val) {
  12204. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  12205. EnumConstantDecl *LastEnumConst =
  12206. cast_or_null<EnumConstantDecl>(lastEnumConst);
  12207. // The scope passed in may not be a decl scope. Zip up the scope tree until
  12208. // we find one that is.
  12209. S = getNonFieldDeclScope(S);
  12210. // Verify that there isn't already something declared with this name in this
  12211. // scope.
  12212. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  12213. ForRedeclaration);
  12214. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  12215. // Maybe we will complain about the shadowed template parameter.
  12216. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  12217. // Just pretend that we didn't see the previous declaration.
  12218. PrevDecl = nullptr;
  12219. }
  12220. if (PrevDecl) {
  12221. // When in C++, we may get a TagDecl with the same name; in this case the
  12222. // enum constant will 'hide' the tag.
  12223. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  12224. "Received TagDecl when not in C++!");
  12225. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  12226. if (isa<EnumConstantDecl>(PrevDecl))
  12227. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  12228. else
  12229. Diag(IdLoc, diag::err_redefinition) << Id;
  12230. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  12231. return nullptr;
  12232. }
  12233. }
  12234. // C++ [class.mem]p15:
  12235. // If T is the name of a class, then each of the following shall have a name
  12236. // different from T:
  12237. // - every enumerator of every member of class T that is an unscoped
  12238. // enumerated type
  12239. if (!TheEnumDecl->isScoped())
  12240. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  12241. DeclarationNameInfo(Id, IdLoc));
  12242. EnumConstantDecl *New =
  12243. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  12244. if (New) {
  12245. // Process attributes.
  12246. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  12247. // Register this decl in the current scope stack.
  12248. New->setAccess(TheEnumDecl->getAccess());
  12249. PushOnScopeChains(New, S);
  12250. }
  12251. ActOnDocumentableDecl(New);
  12252. return New;
  12253. }
  12254. // Returns true when the enum initial expression does not trigger the
  12255. // duplicate enum warning. A few common cases are exempted as follows:
  12256. // Element2 = Element1
  12257. // Element2 = Element1 + 1
  12258. // Element2 = Element1 - 1
  12259. // Where Element2 and Element1 are from the same enum.
  12260. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  12261. Expr *InitExpr = ECD->getInitExpr();
  12262. if (!InitExpr)
  12263. return true;
  12264. InitExpr = InitExpr->IgnoreImpCasts();
  12265. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  12266. if (!BO->isAdditiveOp())
  12267. return true;
  12268. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  12269. if (!IL)
  12270. return true;
  12271. if (IL->getValue() != 1)
  12272. return true;
  12273. InitExpr = BO->getLHS();
  12274. }
  12275. // This checks if the elements are from the same enum.
  12276. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  12277. if (!DRE)
  12278. return true;
  12279. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  12280. if (!EnumConstant)
  12281. return true;
  12282. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  12283. Enum)
  12284. return true;
  12285. return false;
  12286. }
  12287. struct DupKey {
  12288. int64_t val;
  12289. bool isTombstoneOrEmptyKey;
  12290. DupKey(int64_t val, bool isTombstoneOrEmptyKey)
  12291. : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
  12292. };
  12293. static DupKey GetDupKey(const llvm::APSInt& Val) {
  12294. return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
  12295. false);
  12296. }
  12297. struct DenseMapInfoDupKey {
  12298. static DupKey getEmptyKey() { return DupKey(0, true); }
  12299. static DupKey getTombstoneKey() { return DupKey(1, true); }
  12300. static unsigned getHashValue(const DupKey Key) {
  12301. return (unsigned)(Key.val * 37);
  12302. }
  12303. static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
  12304. return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
  12305. LHS.val == RHS.val;
  12306. }
  12307. };
  12308. // Emits a warning when an element is implicitly set a value that
  12309. // a previous element has already been set to.
  12310. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  12311. EnumDecl *Enum,
  12312. QualType EnumType) {
  12313. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  12314. return;
  12315. // Avoid anonymous enums
  12316. if (!Enum->getIdentifier())
  12317. return;
  12318. // Only check for small enums.
  12319. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  12320. return;
  12321. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  12322. typedef SmallVector<ECDVector *, 3> DuplicatesVector;
  12323. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  12324. typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
  12325. ValueToVectorMap;
  12326. DuplicatesVector DupVector;
  12327. ValueToVectorMap EnumMap;
  12328. // Populate the EnumMap with all values represented by enum constants without
  12329. // an initialier.
  12330. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  12331. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  12332. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  12333. // this constant. Skip this enum since it may be ill-formed.
  12334. if (!ECD) {
  12335. return;
  12336. }
  12337. if (ECD->getInitExpr())
  12338. continue;
  12339. DupKey Key = GetDupKey(ECD->getInitVal());
  12340. DeclOrVector &Entry = EnumMap[Key];
  12341. // First time encountering this value.
  12342. if (Entry.isNull())
  12343. Entry = ECD;
  12344. }
  12345. // Create vectors for any values that has duplicates.
  12346. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  12347. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
  12348. if (!ValidDuplicateEnum(ECD, Enum))
  12349. continue;
  12350. DupKey Key = GetDupKey(ECD->getInitVal());
  12351. DeclOrVector& Entry = EnumMap[Key];
  12352. if (Entry.isNull())
  12353. continue;
  12354. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  12355. // Ensure constants are different.
  12356. if (D == ECD)
  12357. continue;
  12358. // Create new vector and push values onto it.
  12359. ECDVector *Vec = new ECDVector();
  12360. Vec->push_back(D);
  12361. Vec->push_back(ECD);
  12362. // Update entry to point to the duplicates vector.
  12363. Entry = Vec;
  12364. // Store the vector somewhere we can consult later for quick emission of
  12365. // diagnostics.
  12366. DupVector.push_back(Vec);
  12367. continue;
  12368. }
  12369. ECDVector *Vec = Entry.get<ECDVector*>();
  12370. // Make sure constants are not added more than once.
  12371. if (*Vec->begin() == ECD)
  12372. continue;
  12373. Vec->push_back(ECD);
  12374. }
  12375. // Emit diagnostics.
  12376. for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
  12377. DupVectorEnd = DupVector.end();
  12378. DupVectorIter != DupVectorEnd; ++DupVectorIter) {
  12379. ECDVector *Vec = *DupVectorIter;
  12380. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  12381. // Emit warning for one enum constant.
  12382. ECDVector::iterator I = Vec->begin();
  12383. S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
  12384. << (*I)->getName() << (*I)->getInitVal().toString(10)
  12385. << (*I)->getSourceRange();
  12386. ++I;
  12387. // Emit one note for each of the remaining enum constants with
  12388. // the same value.
  12389. for (ECDVector::iterator E = Vec->end(); I != E; ++I)
  12390. S.Diag((*I)->getLocation(), diag::note_duplicate_element)
  12391. << (*I)->getName() << (*I)->getInitVal().toString(10)
  12392. << (*I)->getSourceRange();
  12393. delete Vec;
  12394. }
  12395. }
  12396. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  12397. bool AllowMask) const {
  12398. assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
  12399. assert(ED->isCompleteDefinition() && "expected enum definition");
  12400. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  12401. llvm::APInt &FlagBits = R.first->second;
  12402. if (R.second) {
  12403. for (auto *E : ED->enumerators()) {
  12404. const auto &EVal = E->getInitVal();
  12405. // Only single-bit enumerators introduce new flag values.
  12406. if (EVal.isPowerOf2())
  12407. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  12408. }
  12409. }
  12410. // A value is in a flag enum if either its bits are a subset of the enum's
  12411. // flag bits (the first condition) or we are allowing masks and the same is
  12412. // true of its complement (the second condition). When masks are allowed, we
  12413. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  12414. //
  12415. // While it's true that any value could be used as a mask, the assumption is
  12416. // that a mask will have all of the insignificant bits set. Anything else is
  12417. // likely a logic error.
  12418. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  12419. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  12420. }
  12421. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
  12422. SourceLocation RBraceLoc, Decl *EnumDeclX,
  12423. ArrayRef<Decl *> Elements,
  12424. Scope *S, AttributeList *Attr) {
  12425. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  12426. QualType EnumType = Context.getTypeDeclType(Enum);
  12427. if (Attr)
  12428. ProcessDeclAttributeList(S, Enum, Attr);
  12429. if (Enum->isDependentType()) {
  12430. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  12431. EnumConstantDecl *ECD =
  12432. cast_or_null<EnumConstantDecl>(Elements[i]);
  12433. if (!ECD) continue;
  12434. ECD->setType(EnumType);
  12435. }
  12436. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  12437. return;
  12438. }
  12439. // TODO: If the result value doesn't fit in an int, it must be a long or long
  12440. // long value. ISO C does not support this, but GCC does as an extension,
  12441. // emit a warning.
  12442. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  12443. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  12444. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  12445. // Verify that all the values are okay, compute the size of the values, and
  12446. // reverse the list.
  12447. unsigned NumNegativeBits = 0;
  12448. unsigned NumPositiveBits = 0;
  12449. // Keep track of whether all elements have type int.
  12450. bool AllElementsInt = true;
  12451. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  12452. EnumConstantDecl *ECD =
  12453. cast_or_null<EnumConstantDecl>(Elements[i]);
  12454. if (!ECD) continue; // Already issued a diagnostic.
  12455. const llvm::APSInt &InitVal = ECD->getInitVal();
  12456. // Keep track of the size of positive and negative values.
  12457. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  12458. NumPositiveBits = std::max(NumPositiveBits,
  12459. (unsigned)InitVal.getActiveBits());
  12460. else
  12461. NumNegativeBits = std::max(NumNegativeBits,
  12462. (unsigned)InitVal.getMinSignedBits());
  12463. // Keep track of whether every enum element has type int (very commmon).
  12464. if (AllElementsInt)
  12465. AllElementsInt = ECD->getType() == Context.IntTy;
  12466. }
  12467. // Figure out the type that should be used for this enum.
  12468. QualType BestType;
  12469. unsigned BestWidth;
  12470. // C++0x N3000 [conv.prom]p3:
  12471. // An rvalue of an unscoped enumeration type whose underlying
  12472. // type is not fixed can be converted to an rvalue of the first
  12473. // of the following types that can represent all the values of
  12474. // the enumeration: int, unsigned int, long int, unsigned long
  12475. // int, long long int, or unsigned long long int.
  12476. // C99 6.4.4.3p2:
  12477. // An identifier declared as an enumeration constant has type int.
  12478. // The C99 rule is modified by a gcc extension
  12479. QualType BestPromotionType;
  12480. bool Packed = Enum->hasAttr<PackedAttr>();
  12481. // -fshort-enums is the equivalent to specifying the packed attribute on all
  12482. // enum definitions.
  12483. if (LangOpts.ShortEnums)
  12484. Packed = true;
  12485. if (Enum->isFixed()) {
  12486. BestType = Enum->getIntegerType();
  12487. if (BestType->isPromotableIntegerType())
  12488. BestPromotionType = Context.getPromotedIntegerType(BestType);
  12489. else
  12490. BestPromotionType = BestType;
  12491. BestWidth = Context.getIntWidth(BestType);
  12492. }
  12493. else if (NumNegativeBits) {
  12494. // If there is a negative value, figure out the smallest integer type (of
  12495. // int/long/longlong) that fits.
  12496. // If it's packed, check also if it fits a char or a short.
  12497. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  12498. BestType = Context.SignedCharTy;
  12499. BestWidth = CharWidth;
  12500. } else if (Packed && NumNegativeBits <= ShortWidth &&
  12501. NumPositiveBits < ShortWidth) {
  12502. BestType = Context.ShortTy;
  12503. BestWidth = ShortWidth;
  12504. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  12505. BestType = Context.IntTy;
  12506. BestWidth = IntWidth;
  12507. } else {
  12508. BestWidth = Context.getTargetInfo().getLongWidth();
  12509. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  12510. BestType = Context.LongTy;
  12511. } else {
  12512. BestWidth = Context.getTargetInfo().getLongLongWidth();
  12513. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  12514. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  12515. BestType = Context.LongLongTy;
  12516. }
  12517. }
  12518. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  12519. } else {
  12520. // If there is no negative value, figure out the smallest type that fits
  12521. // all of the enumerator values.
  12522. // If it's packed, check also if it fits a char or a short.
  12523. if (Packed && NumPositiveBits <= CharWidth) {
  12524. BestType = Context.UnsignedCharTy;
  12525. BestPromotionType = Context.IntTy;
  12526. BestWidth = CharWidth;
  12527. } else if (Packed && NumPositiveBits <= ShortWidth) {
  12528. BestType = Context.UnsignedShortTy;
  12529. BestPromotionType = Context.IntTy;
  12530. BestWidth = ShortWidth;
  12531. } else if (NumPositiveBits <= IntWidth) {
  12532. BestType = Context.UnsignedIntTy;
  12533. BestWidth = IntWidth;
  12534. BestPromotionType
  12535. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  12536. ? Context.UnsignedIntTy : Context.IntTy;
  12537. } else if (NumPositiveBits <=
  12538. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  12539. BestType = Context.UnsignedLongTy;
  12540. BestPromotionType
  12541. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  12542. ? Context.UnsignedLongTy : Context.LongTy;
  12543. } else {
  12544. BestWidth = Context.getTargetInfo().getLongLongWidth();
  12545. assert(NumPositiveBits <= BestWidth &&
  12546. "How could an initializer get larger than ULL?");
  12547. BestType = Context.UnsignedLongLongTy;
  12548. BestPromotionType
  12549. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  12550. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  12551. }
  12552. }
  12553. // Loop over all of the enumerator constants, changing their types to match
  12554. // the type of the enum if needed.
  12555. for (auto *D : Elements) {
  12556. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  12557. if (!ECD) continue; // Already issued a diagnostic.
  12558. // Standard C says the enumerators have int type, but we allow, as an
  12559. // extension, the enumerators to be larger than int size. If each
  12560. // enumerator value fits in an int, type it as an int, otherwise type it the
  12561. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  12562. // that X has type 'int', not 'unsigned'.
  12563. // Determine whether the value fits into an int.
  12564. llvm::APSInt InitVal = ECD->getInitVal();
  12565. // If it fits into an integer type, force it. Otherwise force it to match
  12566. // the enum decl type.
  12567. QualType NewTy;
  12568. unsigned NewWidth;
  12569. bool NewSign;
  12570. if (!getLangOpts().CPlusPlus &&
  12571. !Enum->isFixed() &&
  12572. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  12573. NewTy = Context.IntTy;
  12574. NewWidth = IntWidth;
  12575. NewSign = true;
  12576. } else if (ECD->getType() == BestType) {
  12577. // Already the right type!
  12578. if (getLangOpts().CPlusPlus)
  12579. // C++ [dcl.enum]p4: Following the closing brace of an
  12580. // enum-specifier, each enumerator has the type of its
  12581. // enumeration.
  12582. ECD->setType(EnumType);
  12583. continue;
  12584. } else {
  12585. NewTy = BestType;
  12586. NewWidth = BestWidth;
  12587. NewSign = BestType->isSignedIntegerOrEnumerationType();
  12588. }
  12589. // Adjust the APSInt value.
  12590. InitVal = InitVal.extOrTrunc(NewWidth);
  12591. InitVal.setIsSigned(NewSign);
  12592. ECD->setInitVal(InitVal);
  12593. // Adjust the Expr initializer and type.
  12594. if (ECD->getInitExpr() &&
  12595. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  12596. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  12597. CK_IntegralCast,
  12598. ECD->getInitExpr(),
  12599. /*base paths*/ nullptr,
  12600. VK_RValue));
  12601. if (getLangOpts().CPlusPlus)
  12602. // C++ [dcl.enum]p4: Following the closing brace of an
  12603. // enum-specifier, each enumerator has the type of its
  12604. // enumeration.
  12605. ECD->setType(EnumType);
  12606. else
  12607. ECD->setType(NewTy);
  12608. }
  12609. Enum->completeDefinition(BestType, BestPromotionType,
  12610. NumPositiveBits, NumNegativeBits);
  12611. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  12612. if (Enum->hasAttr<FlagEnumAttr>()) {
  12613. for (Decl *D : Elements) {
  12614. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  12615. if (!ECD) continue; // Already issued a diagnostic.
  12616. llvm::APSInt InitVal = ECD->getInitVal();
  12617. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  12618. !IsValueInFlagEnum(Enum, InitVal, true))
  12619. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  12620. << ECD << Enum;
  12621. }
  12622. }
  12623. // Now that the enum type is defined, ensure it's not been underaligned.
  12624. if (Enum->hasAttrs())
  12625. CheckAlignasUnderalignment(Enum);
  12626. }
  12627. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  12628. SourceLocation StartLoc,
  12629. SourceLocation EndLoc) {
  12630. StringLiteral *AsmString = cast<StringLiteral>(expr);
  12631. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  12632. AsmString, StartLoc,
  12633. EndLoc);
  12634. CurContext->addDecl(New);
  12635. return New;
  12636. }
  12637. static void checkModuleImportContext(Sema &S, Module *M,
  12638. SourceLocation ImportLoc,
  12639. DeclContext *DC) {
  12640. if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
  12641. switch (LSD->getLanguage()) {
  12642. case LinkageSpecDecl::lang_c:
  12643. if (!M->IsExternC) {
  12644. S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
  12645. << M->getFullModuleName();
  12646. S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
  12647. return;
  12648. }
  12649. break;
  12650. case LinkageSpecDecl::lang_cxx:
  12651. break;
  12652. }
  12653. DC = LSD->getParent();
  12654. }
  12655. while (isa<LinkageSpecDecl>(DC))
  12656. DC = DC->getParent();
  12657. if (!isa<TranslationUnitDecl>(DC)) {
  12658. S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
  12659. << M->getFullModuleName() << DC;
  12660. S.Diag(cast<Decl>(DC)->getLocStart(),
  12661. diag::note_module_import_not_at_top_level)
  12662. << DC;
  12663. }
  12664. }
  12665. DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
  12666. SourceLocation ImportLoc,
  12667. ModuleIdPath Path) {
  12668. Module *Mod =
  12669. getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
  12670. /*IsIncludeDirective=*/false);
  12671. if (!Mod)
  12672. return true;
  12673. VisibleModules.setVisible(Mod, ImportLoc);
  12674. checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
  12675. // FIXME: we should support importing a submodule within a different submodule
  12676. // of the same top-level module. Until we do, make it an error rather than
  12677. // silently ignoring the import.
  12678. if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
  12679. Diag(ImportLoc, diag::err_module_self_import)
  12680. << Mod->getFullModuleName() << getLangOpts().CurrentModule;
  12681. else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
  12682. Diag(ImportLoc, diag::err_module_import_in_implementation)
  12683. << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
  12684. SmallVector<SourceLocation, 2> IdentifierLocs;
  12685. Module *ModCheck = Mod;
  12686. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  12687. // If we've run out of module parents, just drop the remaining identifiers.
  12688. // We need the length to be consistent.
  12689. if (!ModCheck)
  12690. break;
  12691. ModCheck = ModCheck->Parent;
  12692. IdentifierLocs.push_back(Path[I].second);
  12693. }
  12694. ImportDecl *Import = ImportDecl::Create(Context,
  12695. Context.getTranslationUnitDecl(),
  12696. AtLoc.isValid()? AtLoc : ImportLoc,
  12697. Mod, IdentifierLocs);
  12698. Context.getTranslationUnitDecl()->addDecl(Import);
  12699. return Import;
  12700. }
  12701. void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  12702. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
  12703. // Determine whether we're in the #include buffer for a module. The #includes
  12704. // in that buffer do not qualify as module imports; they're just an
  12705. // implementation detail of us building the module.
  12706. //
  12707. // FIXME: Should we even get ActOnModuleInclude calls for those?
  12708. bool IsInModuleIncludes =
  12709. TUKind == TU_Module &&
  12710. getSourceManager().isWrittenInMainFile(DirectiveLoc);
  12711. // If this module import was due to an inclusion directive, create an
  12712. // implicit import declaration to capture it in the AST.
  12713. if (!IsInModuleIncludes) {
  12714. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  12715. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  12716. DirectiveLoc, Mod,
  12717. DirectiveLoc);
  12718. TU->addDecl(ImportD);
  12719. Consumer.HandleImplicitImportDecl(ImportD);
  12720. }
  12721. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
  12722. VisibleModules.setVisible(Mod, DirectiveLoc);
  12723. }
  12724. void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
  12725. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
  12726. if (getLangOpts().ModulesLocalVisibility)
  12727. VisibleModulesStack.push_back(std::move(VisibleModules));
  12728. VisibleModules.setVisible(Mod, DirectiveLoc);
  12729. }
  12730. void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
  12731. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
  12732. if (getLangOpts().ModulesLocalVisibility) {
  12733. VisibleModules = std::move(VisibleModulesStack.back());
  12734. VisibleModulesStack.pop_back();
  12735. VisibleModules.setVisible(Mod, DirectiveLoc);
  12736. }
  12737. }
  12738. void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
  12739. Module *Mod) {
  12740. // Bail if we're not allowed to implicitly import a module here.
  12741. if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
  12742. return;
  12743. // Create the implicit import declaration.
  12744. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  12745. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  12746. Loc, Mod, Loc);
  12747. TU->addDecl(ImportD);
  12748. Consumer.HandleImplicitImportDecl(ImportD);
  12749. // Make the module visible.
  12750. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
  12751. VisibleModules.setVisible(Mod, Loc);
  12752. }
  12753. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  12754. IdentifierInfo* AliasName,
  12755. SourceLocation PragmaLoc,
  12756. SourceLocation NameLoc,
  12757. SourceLocation AliasNameLoc) {
  12758. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  12759. LookupOrdinaryName);
  12760. AsmLabelAttr *Attr =
  12761. AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
  12762. // If a declaration that:
  12763. // 1) declares a function or a variable
  12764. // 2) has external linkage
  12765. // already exists, add a label attribute to it.
  12766. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  12767. if (isDeclExternC(PrevDecl))
  12768. PrevDecl->addAttr(Attr);
  12769. else
  12770. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  12771. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  12772. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  12773. } else
  12774. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  12775. }
  12776. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  12777. SourceLocation PragmaLoc,
  12778. SourceLocation NameLoc) {
  12779. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  12780. if (PrevDecl) {
  12781. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  12782. } else {
  12783. (void)WeakUndeclaredIdentifiers.insert(
  12784. std::pair<IdentifierInfo*,WeakInfo>
  12785. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  12786. }
  12787. }
  12788. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  12789. IdentifierInfo* AliasName,
  12790. SourceLocation PragmaLoc,
  12791. SourceLocation NameLoc,
  12792. SourceLocation AliasNameLoc) {
  12793. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  12794. LookupOrdinaryName);
  12795. WeakInfo W = WeakInfo(Name, NameLoc);
  12796. if (PrevDecl) {
  12797. if (!PrevDecl->hasAttr<AliasAttr>())
  12798. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  12799. DeclApplyPragmaWeak(TUScope, ND, W);
  12800. } else {
  12801. (void)WeakUndeclaredIdentifiers.insert(
  12802. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  12803. }
  12804. }
  12805. Decl *Sema::getObjCDeclContext() const {
  12806. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  12807. }
  12808. AvailabilityResult Sema::getCurContextAvailability() const {
  12809. const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
  12810. if (!D)
  12811. return AR_Available;
  12812. // If we are within an Objective-C method, we should consult
  12813. // both the availability of the method as well as the
  12814. // enclosing class. If the class is (say) deprecated,
  12815. // the entire method is considered deprecated from the
  12816. // purpose of checking if the current context is deprecated.
  12817. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  12818. AvailabilityResult R = MD->getAvailability();
  12819. if (R != AR_Available)
  12820. return R;
  12821. D = MD->getClassInterface();
  12822. }
  12823. // If we are within an Objective-c @implementation, it
  12824. // gets the same availability context as the @interface.
  12825. else if (const ObjCImplementationDecl *ID =
  12826. dyn_cast<ObjCImplementationDecl>(D)) {
  12827. D = ID->getClassInterface();
  12828. }
  12829. // Recover from user error.
  12830. return D ? D->getAvailability() : AR_Available;
  12831. }