SemaDecl.cpp 416 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847
  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 "clang/Sema/Initialization.h"
  15. #include "clang/Sema/Lookup.h"
  16. #include "clang/Sema/CXXFieldCollector.h"
  17. #include "clang/Sema/Scope.h"
  18. #include "clang/Sema/ScopeInfo.h"
  19. #include "TypeLocBuilder.h"
  20. #include "clang/AST/ASTConsumer.h"
  21. #include "clang/AST/ASTContext.h"
  22. #include "clang/AST/CXXInheritance.h"
  23. #include "clang/AST/CommentDiagnostic.h"
  24. #include "clang/AST/DeclCXX.h"
  25. #include "clang/AST/DeclObjC.h"
  26. #include "clang/AST/DeclTemplate.h"
  27. #include "clang/AST/EvaluatedExprVisitor.h"
  28. #include "clang/AST/ExprCXX.h"
  29. #include "clang/AST/StmtCXX.h"
  30. #include "clang/AST/CharUnits.h"
  31. #include "clang/Sema/DeclSpec.h"
  32. #include "clang/Sema/ParsedTemplate.h"
  33. #include "clang/Parse/ParseDiagnostic.h"
  34. #include "clang/Basic/PartialDiagnostic.h"
  35. #include "clang/Sema/DelayedDiagnostic.h"
  36. #include "clang/Basic/SourceManager.h"
  37. #include "clang/Basic/TargetInfo.h"
  38. // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
  39. #include "clang/Lex/Preprocessor.h"
  40. #include "clang/Lex/HeaderSearch.h"
  41. #include "clang/Lex/ModuleLoader.h"
  42. #include "llvm/ADT/SmallString.h"
  43. #include "llvm/ADT/Triple.h"
  44. #include <algorithm>
  45. #include <cstring>
  46. #include <functional>
  47. using namespace clang;
  48. using namespace sema;
  49. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  50. if (OwnedType) {
  51. Decl *Group[2] = { OwnedType, Ptr };
  52. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  53. }
  54. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  55. }
  56. namespace {
  57. class TypeNameValidatorCCC : public CorrectionCandidateCallback {
  58. public:
  59. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
  60. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
  61. WantExpressionKeywords = false;
  62. WantCXXNamedCasts = false;
  63. WantRemainingKeywords = false;
  64. }
  65. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  66. if (NamedDecl *ND = candidate.getCorrectionDecl())
  67. return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
  68. (AllowInvalidDecl || !ND->isInvalidDecl());
  69. else
  70. return !WantClassName && candidate.isKeyword();
  71. }
  72. private:
  73. bool AllowInvalidDecl;
  74. bool WantClassName;
  75. };
  76. }
  77. /// \brief Determine whether the token kind starts a simple-type-specifier.
  78. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  79. switch (Kind) {
  80. // FIXME: Take into account the current language when deciding whether a
  81. // token kind is a valid type specifier
  82. case tok::kw_short:
  83. case tok::kw_long:
  84. case tok::kw___int64:
  85. case tok::kw___int128:
  86. case tok::kw_signed:
  87. case tok::kw_unsigned:
  88. case tok::kw_void:
  89. case tok::kw_char:
  90. case tok::kw_int:
  91. case tok::kw_half:
  92. case tok::kw_float:
  93. case tok::kw_double:
  94. case tok::kw_wchar_t:
  95. case tok::kw_bool:
  96. case tok::kw___underlying_type:
  97. return true;
  98. case tok::annot_typename:
  99. case tok::kw_char16_t:
  100. case tok::kw_char32_t:
  101. case tok::kw_typeof:
  102. case tok::kw_decltype:
  103. return getLangOpts().CPlusPlus;
  104. default:
  105. break;
  106. }
  107. return false;
  108. }
  109. /// \brief If the identifier refers to a type name within this scope,
  110. /// return the declaration of that type.
  111. ///
  112. /// This routine performs ordinary name lookup of the identifier II
  113. /// within the given scope, with optional C++ scope specifier SS, to
  114. /// determine whether the name refers to a type. If so, returns an
  115. /// opaque pointer (actually a QualType) corresponding to that
  116. /// type. Otherwise, returns NULL.
  117. ///
  118. /// If name lookup results in an ambiguity, this routine will complain
  119. /// and then return NULL.
  120. ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
  121. Scope *S, CXXScopeSpec *SS,
  122. bool isClassName, bool HasTrailingDot,
  123. ParsedType ObjectTypePtr,
  124. bool IsCtorOrDtorName,
  125. bool WantNontrivialTypeSourceInfo,
  126. IdentifierInfo **CorrectedII) {
  127. // Determine where we will perform name lookup.
  128. DeclContext *LookupCtx = 0;
  129. if (ObjectTypePtr) {
  130. QualType ObjectType = ObjectTypePtr.get();
  131. if (ObjectType->isRecordType())
  132. LookupCtx = computeDeclContext(ObjectType);
  133. } else if (SS && SS->isNotEmpty()) {
  134. LookupCtx = computeDeclContext(*SS, false);
  135. if (!LookupCtx) {
  136. if (isDependentScopeSpecifier(*SS)) {
  137. // C++ [temp.res]p3:
  138. // A qualified-id that refers to a type and in which the
  139. // nested-name-specifier depends on a template-parameter (14.6.2)
  140. // shall be prefixed by the keyword typename to indicate that the
  141. // qualified-id denotes a type, forming an
  142. // elaborated-type-specifier (7.1.5.3).
  143. //
  144. // We therefore do not perform any name lookup if the result would
  145. // refer to a member of an unknown specialization.
  146. if (!isClassName && !IsCtorOrDtorName)
  147. return ParsedType();
  148. // We know from the grammar that this name refers to a type,
  149. // so build a dependent node to describe the type.
  150. if (WantNontrivialTypeSourceInfo)
  151. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  152. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  153. QualType T =
  154. CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  155. II, NameLoc);
  156. return ParsedType::make(T);
  157. }
  158. return ParsedType();
  159. }
  160. if (!LookupCtx->isDependentContext() &&
  161. RequireCompleteDeclContext(*SS, LookupCtx))
  162. return ParsedType();
  163. }
  164. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  165. // lookup for class-names.
  166. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  167. LookupOrdinaryName;
  168. LookupResult Result(*this, &II, NameLoc, Kind);
  169. if (LookupCtx) {
  170. // Perform "qualified" name lookup into the declaration context we
  171. // computed, which is either the type of the base of a member access
  172. // expression or the declaration context associated with a prior
  173. // nested-name-specifier.
  174. LookupQualifiedName(Result, LookupCtx);
  175. if (ObjectTypePtr && Result.empty()) {
  176. // C++ [basic.lookup.classref]p3:
  177. // If the unqualified-id is ~type-name, the type-name is looked up
  178. // in the context of the entire postfix-expression. If the type T of
  179. // the object expression is of a class type C, the type-name is also
  180. // looked up in the scope of class C. At least one of the lookups shall
  181. // find a name that refers to (possibly cv-qualified) T.
  182. LookupName(Result, S);
  183. }
  184. } else {
  185. // Perform unqualified name lookup.
  186. LookupName(Result, S);
  187. }
  188. NamedDecl *IIDecl = 0;
  189. switch (Result.getResultKind()) {
  190. case LookupResult::NotFound:
  191. case LookupResult::NotFoundInCurrentInstantiation:
  192. if (CorrectedII) {
  193. TypeNameValidatorCCC Validator(true, isClassName);
  194. TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
  195. Kind, S, SS, Validator);
  196. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  197. TemplateTy Template;
  198. bool MemberOfUnknownSpecialization;
  199. UnqualifiedId TemplateName;
  200. TemplateName.setIdentifier(NewII, NameLoc);
  201. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  202. CXXScopeSpec NewSS, *NewSSPtr = SS;
  203. if (SS && NNS) {
  204. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  205. NewSSPtr = &NewSS;
  206. }
  207. if (Correction && (NNS || NewII != &II) &&
  208. // Ignore a correction to a template type as the to-be-corrected
  209. // identifier is not a template (typo correction for template names
  210. // is handled elsewhere).
  211. !(getLangOpts().CPlusPlus && NewSSPtr &&
  212. isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
  213. false, Template, MemberOfUnknownSpecialization))) {
  214. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  215. isClassName, HasTrailingDot, ObjectTypePtr,
  216. IsCtorOrDtorName,
  217. WantNontrivialTypeSourceInfo);
  218. if (Ty) {
  219. std::string CorrectedStr(Correction.getAsString(getLangOpts()));
  220. std::string CorrectedQuotedStr(
  221. Correction.getQuoted(getLangOpts()));
  222. Diag(NameLoc, diag::err_unknown_type_or_class_name_suggest)
  223. << Result.getLookupName() << CorrectedQuotedStr << isClassName
  224. << FixItHint::CreateReplacement(SourceRange(NameLoc),
  225. CorrectedStr);
  226. if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
  227. Diag(FirstDecl->getLocation(), diag::note_previous_decl)
  228. << CorrectedQuotedStr;
  229. if (SS && NNS)
  230. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  231. *CorrectedII = NewII;
  232. return Ty;
  233. }
  234. }
  235. }
  236. // If typo correction failed or was not performed, fall through
  237. case LookupResult::FoundOverloaded:
  238. case LookupResult::FoundUnresolvedValue:
  239. Result.suppressDiagnostics();
  240. return ParsedType();
  241. case LookupResult::Ambiguous:
  242. // Recover from type-hiding ambiguities by hiding the type. We'll
  243. // do the lookup again when looking for an object, and we can
  244. // diagnose the error then. If we don't do this, then the error
  245. // about hiding the type will be immediately followed by an error
  246. // that only makes sense if the identifier was treated like a type.
  247. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  248. Result.suppressDiagnostics();
  249. return ParsedType();
  250. }
  251. // Look to see if we have a type anywhere in the list of results.
  252. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  253. Res != ResEnd; ++Res) {
  254. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
  255. if (!IIDecl ||
  256. (*Res)->getLocation().getRawEncoding() <
  257. IIDecl->getLocation().getRawEncoding())
  258. IIDecl = *Res;
  259. }
  260. }
  261. if (!IIDecl) {
  262. // None of the entities we found is a type, so there is no way
  263. // to even assume that the result is a type. In this case, don't
  264. // complain about the ambiguity. The parser will either try to
  265. // perform this lookup again (e.g., as an object name), which
  266. // will produce the ambiguity, or will complain that it expected
  267. // a type name.
  268. Result.suppressDiagnostics();
  269. return ParsedType();
  270. }
  271. // We found a type within the ambiguous lookup; diagnose the
  272. // ambiguity and then return that type. This might be the right
  273. // answer, or it might not be, but it suppresses any attempt to
  274. // perform the name lookup again.
  275. break;
  276. case LookupResult::Found:
  277. IIDecl = Result.getFoundDecl();
  278. break;
  279. }
  280. assert(IIDecl && "Didn't find decl");
  281. QualType T;
  282. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  283. DiagnoseUseOfDecl(IIDecl, NameLoc);
  284. if (T.isNull())
  285. T = Context.getTypeDeclType(TD);
  286. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  287. // constructor or destructor name (in such a case, the scope specifier
  288. // will be attached to the enclosing Expr or Decl node).
  289. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
  290. if (WantNontrivialTypeSourceInfo) {
  291. // Construct a type with type-source information.
  292. TypeLocBuilder Builder;
  293. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  294. T = getElaboratedType(ETK_None, *SS, T);
  295. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  296. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  297. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  298. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  299. } else {
  300. T = getElaboratedType(ETK_None, *SS, T);
  301. }
  302. }
  303. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  304. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  305. if (!HasTrailingDot)
  306. T = Context.getObjCInterfaceType(IDecl);
  307. }
  308. if (T.isNull()) {
  309. // If it's not plausibly a type, suppress diagnostics.
  310. Result.suppressDiagnostics();
  311. return ParsedType();
  312. }
  313. return ParsedType::make(T);
  314. }
  315. /// isTagName() - This method is called *for error recovery purposes only*
  316. /// to determine if the specified name is a valid tag name ("struct foo"). If
  317. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  318. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  319. /// cases in C where the user forgot to specify the tag.
  320. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  321. // Do a tag name lookup in this scope.
  322. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  323. LookupName(R, S, false);
  324. R.suppressDiagnostics();
  325. if (R.getResultKind() == LookupResult::Found)
  326. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  327. switch (TD->getTagKind()) {
  328. case TTK_Struct: return DeclSpec::TST_struct;
  329. case TTK_Interface: return DeclSpec::TST_interface;
  330. case TTK_Union: return DeclSpec::TST_union;
  331. case TTK_Class: return DeclSpec::TST_class;
  332. case TTK_Enum: return DeclSpec::TST_enum;
  333. }
  334. }
  335. return DeclSpec::TST_unspecified;
  336. }
  337. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  338. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  339. /// then downgrade the missing typename error to a warning.
  340. /// This is needed for MSVC compatibility; Example:
  341. /// @code
  342. /// template<class T> class A {
  343. /// public:
  344. /// typedef int TYPE;
  345. /// };
  346. /// template<class T> class B : public A<T> {
  347. /// public:
  348. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  349. /// };
  350. /// @endcode
  351. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  352. if (CurContext->isRecord()) {
  353. const Type *Ty = SS->getScopeRep()->getAsType();
  354. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  355. for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
  356. BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
  357. if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
  358. return true;
  359. return S->isFunctionPrototypeScope();
  360. }
  361. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  362. }
  363. bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  364. SourceLocation IILoc,
  365. Scope *S,
  366. CXXScopeSpec *SS,
  367. ParsedType &SuggestedType) {
  368. // We don't have anything to suggest (yet).
  369. SuggestedType = ParsedType();
  370. // There may have been a typo in the name of the type. Look up typo
  371. // results, in case we have something that we can suggest.
  372. TypeNameValidatorCCC Validator(false);
  373. if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
  374. LookupOrdinaryName, S, SS,
  375. Validator)) {
  376. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  377. std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
  378. if (Corrected.isKeyword()) {
  379. // We corrected to a keyword.
  380. IdentifierInfo *NewII = Corrected.getCorrectionAsIdentifierInfo();
  381. if (!isSimpleTypeSpecifier(NewII->getTokenID()))
  382. CorrectedQuotedStr = "the keyword " + CorrectedQuotedStr;
  383. Diag(IILoc, diag::err_unknown_typename_suggest)
  384. << II << CorrectedQuotedStr
  385. << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
  386. II = NewII;
  387. } else {
  388. NamedDecl *Result = Corrected.getCorrectionDecl();
  389. // We found a similarly-named type or interface; suggest that.
  390. if (!SS || !SS->isSet())
  391. Diag(IILoc, diag::err_unknown_typename_suggest)
  392. << II << CorrectedQuotedStr
  393. << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
  394. else if (DeclContext *DC = computeDeclContext(*SS, false))
  395. Diag(IILoc, diag::err_unknown_nested_typename_suggest)
  396. << II << DC << CorrectedQuotedStr << SS->getRange()
  397. << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
  398. else
  399. llvm_unreachable("could not have corrected a typo here");
  400. Diag(Result->getLocation(), diag::note_previous_decl)
  401. << CorrectedQuotedStr;
  402. SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
  403. false, false, ParsedType(),
  404. /*IsCtorOrDtorName=*/false,
  405. /*NonTrivialTypeSourceInfo=*/true);
  406. }
  407. return true;
  408. }
  409. if (getLangOpts().CPlusPlus) {
  410. // See if II is a class template that the user forgot to pass arguments to.
  411. UnqualifiedId Name;
  412. Name.setIdentifier(II, IILoc);
  413. CXXScopeSpec EmptySS;
  414. TemplateTy TemplateResult;
  415. bool MemberOfUnknownSpecialization;
  416. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  417. Name, ParsedType(), true, TemplateResult,
  418. MemberOfUnknownSpecialization) == TNK_Type_template) {
  419. TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
  420. Diag(IILoc, diag::err_template_missing_args) << TplName;
  421. if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
  422. Diag(TplDecl->getLocation(), diag::note_template_decl_here)
  423. << TplDecl->getTemplateParameters()->getSourceRange();
  424. }
  425. return true;
  426. }
  427. }
  428. // FIXME: Should we move the logic that tries to recover from a missing tag
  429. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  430. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  431. Diag(IILoc, diag::err_unknown_typename) << II;
  432. else if (DeclContext *DC = computeDeclContext(*SS, false))
  433. Diag(IILoc, diag::err_typename_nested_not_found)
  434. << II << DC << SS->getRange();
  435. else if (isDependentScopeSpecifier(*SS)) {
  436. unsigned DiagID = diag::err_typename_missing;
  437. if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
  438. DiagID = diag::warn_typename_missing;
  439. Diag(SS->getRange().getBegin(), DiagID)
  440. << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
  441. << SourceRange(SS->getRange().getBegin(), IILoc)
  442. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  443. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  444. *SS, *II, IILoc).get();
  445. } else {
  446. assert(SS && SS->isInvalid() &&
  447. "Invalid scope specifier has already been diagnosed");
  448. }
  449. return true;
  450. }
  451. /// \brief Determine whether the given result set contains either a type name
  452. /// or
  453. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  454. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  455. NextToken.is(tok::less);
  456. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  457. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  458. return true;
  459. if (CheckTemplate && isa<TemplateDecl>(*I))
  460. return true;
  461. }
  462. return false;
  463. }
  464. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  465. Scope *S, CXXScopeSpec &SS,
  466. IdentifierInfo *&Name,
  467. SourceLocation NameLoc) {
  468. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  469. SemaRef.LookupParsedName(R, S, &SS);
  470. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  471. const char *TagName = 0;
  472. const char *FixItTagName = 0;
  473. switch (Tag->getTagKind()) {
  474. case TTK_Class:
  475. TagName = "class";
  476. FixItTagName = "class ";
  477. break;
  478. case TTK_Enum:
  479. TagName = "enum";
  480. FixItTagName = "enum ";
  481. break;
  482. case TTK_Struct:
  483. TagName = "struct";
  484. FixItTagName = "struct ";
  485. break;
  486. case TTK_Interface:
  487. TagName = "__interface";
  488. FixItTagName = "__interface ";
  489. break;
  490. case TTK_Union:
  491. TagName = "union";
  492. FixItTagName = "union ";
  493. break;
  494. }
  495. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  496. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  497. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  498. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  499. I != IEnd; ++I)
  500. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  501. << Name << TagName;
  502. // Replace lookup results with just the tag decl.
  503. Result.clear(Sema::LookupTagName);
  504. SemaRef.LookupParsedName(Result, S, &SS);
  505. return true;
  506. }
  507. return false;
  508. }
  509. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  510. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  511. QualType T, SourceLocation NameLoc) {
  512. ASTContext &Context = S.Context;
  513. TypeLocBuilder Builder;
  514. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  515. T = S.getElaboratedType(ETK_None, SS, T);
  516. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  517. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  518. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  519. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  520. }
  521. Sema::NameClassification Sema::ClassifyName(Scope *S,
  522. CXXScopeSpec &SS,
  523. IdentifierInfo *&Name,
  524. SourceLocation NameLoc,
  525. const Token &NextToken,
  526. bool IsAddressOfOperand,
  527. CorrectionCandidateCallback *CCC) {
  528. DeclarationNameInfo NameInfo(Name, NameLoc);
  529. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  530. if (NextToken.is(tok::coloncolon)) {
  531. BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
  532. QualType(), false, SS, 0, false);
  533. }
  534. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  535. LookupParsedName(Result, S, &SS, !CurMethod);
  536. // Perform lookup for Objective-C instance variables (including automatically
  537. // synthesized instance variables), if we're in an Objective-C method.
  538. // FIXME: This lookup really, really needs to be folded in to the normal
  539. // unqualified lookup mechanism.
  540. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  541. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  542. if (E.get() || E.isInvalid())
  543. return E;
  544. }
  545. bool SecondTry = false;
  546. bool IsFilteredTemplateName = false;
  547. Corrected:
  548. switch (Result.getResultKind()) {
  549. case LookupResult::NotFound:
  550. // If an unqualified-id is followed by a '(', then we have a function
  551. // call.
  552. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  553. // In C++, this is an ADL-only call.
  554. // FIXME: Reference?
  555. if (getLangOpts().CPlusPlus)
  556. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  557. // C90 6.3.2.2:
  558. // If the expression that precedes the parenthesized argument list in a
  559. // function call consists solely of an identifier, and if no
  560. // declaration is visible for this identifier, the identifier is
  561. // implicitly declared exactly as if, in the innermost block containing
  562. // the function call, the declaration
  563. //
  564. // extern int identifier ();
  565. //
  566. // appeared.
  567. //
  568. // We also allow this in C99 as an extension.
  569. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  570. Result.addDecl(D);
  571. Result.resolveKind();
  572. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  573. }
  574. }
  575. // In C, we first see whether there is a tag type by the same name, in
  576. // which case it's likely that the user just forget to write "enum",
  577. // "struct", or "union".
  578. if (!getLangOpts().CPlusPlus && !SecondTry &&
  579. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  580. break;
  581. }
  582. // Perform typo correction to determine if there is another name that is
  583. // close to this name.
  584. if (!SecondTry && CCC) {
  585. SecondTry = true;
  586. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  587. Result.getLookupKind(), S,
  588. &SS, *CCC)) {
  589. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  590. unsigned QualifiedDiag = diag::err_no_member_suggest;
  591. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  592. std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
  593. NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
  594. NamedDecl *UnderlyingFirstDecl
  595. = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
  596. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  597. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  598. UnqualifiedDiag = diag::err_no_template_suggest;
  599. QualifiedDiag = diag::err_no_member_template_suggest;
  600. } else if (UnderlyingFirstDecl &&
  601. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  602. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  603. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  604. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  605. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  606. }
  607. if (SS.isEmpty())
  608. Diag(NameLoc, UnqualifiedDiag)
  609. << Name << CorrectedQuotedStr
  610. << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
  611. else
  612. Diag(NameLoc, QualifiedDiag)
  613. << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
  614. << SS.getRange()
  615. << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
  616. // Update the name, so that the caller has the new name.
  617. Name = Corrected.getCorrectionAsIdentifierInfo();
  618. // Typo correction corrected to a keyword.
  619. if (Corrected.isKeyword())
  620. return Corrected.getCorrectionAsIdentifierInfo();
  621. // Also update the LookupResult...
  622. // FIXME: This should probably go away at some point
  623. Result.clear();
  624. Result.setLookupName(Corrected.getCorrection());
  625. if (FirstDecl) {
  626. Result.addDecl(FirstDecl);
  627. Diag(FirstDecl->getLocation(), diag::note_previous_decl)
  628. << CorrectedQuotedStr;
  629. }
  630. // If we found an Objective-C instance variable, let
  631. // LookupInObjCMethod build the appropriate expression to
  632. // reference the ivar.
  633. // FIXME: This is a gross hack.
  634. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  635. Result.clear();
  636. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  637. return E;
  638. }
  639. goto Corrected;
  640. }
  641. }
  642. // We failed to correct; just fall through and let the parser deal with it.
  643. Result.suppressDiagnostics();
  644. return NameClassification::Unknown();
  645. case LookupResult::NotFoundInCurrentInstantiation: {
  646. // We performed name lookup into the current instantiation, and there were
  647. // dependent bases, so we treat this result the same way as any other
  648. // dependent nested-name-specifier.
  649. // C++ [temp.res]p2:
  650. // A name used in a template declaration or definition and that is
  651. // dependent on a template-parameter is assumed not to name a type
  652. // unless the applicable name lookup finds a type name or the name is
  653. // qualified by the keyword typename.
  654. //
  655. // FIXME: If the next token is '<', we might want to ask the parser to
  656. // perform some heroics to see if we actually have a
  657. // template-argument-list, which would indicate a missing 'template'
  658. // keyword here.
  659. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  660. NameInfo, IsAddressOfOperand,
  661. /*TemplateArgs=*/0);
  662. }
  663. case LookupResult::Found:
  664. case LookupResult::FoundOverloaded:
  665. case LookupResult::FoundUnresolvedValue:
  666. break;
  667. case LookupResult::Ambiguous:
  668. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  669. hasAnyAcceptableTemplateNames(Result)) {
  670. // C++ [temp.local]p3:
  671. // A lookup that finds an injected-class-name (10.2) can result in an
  672. // ambiguity in certain cases (for example, if it is found in more than
  673. // one base class). If all of the injected-class-names that are found
  674. // refer to specializations of the same class template, and if the name
  675. // is followed by a template-argument-list, the reference refers to the
  676. // class template itself and not a specialization thereof, and is not
  677. // ambiguous.
  678. //
  679. // This filtering can make an ambiguous result into an unambiguous one,
  680. // so try again after filtering out template names.
  681. FilterAcceptableTemplateNames(Result);
  682. if (!Result.isAmbiguous()) {
  683. IsFilteredTemplateName = true;
  684. break;
  685. }
  686. }
  687. // Diagnose the ambiguity and return an error.
  688. return NameClassification::Error();
  689. }
  690. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  691. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  692. // C++ [temp.names]p3:
  693. // After name lookup (3.4) finds that a name is a template-name or that
  694. // an operator-function-id or a literal- operator-id refers to a set of
  695. // overloaded functions any member of which is a function template if
  696. // this is followed by a <, the < is always taken as the delimiter of a
  697. // template-argument-list and never as the less-than operator.
  698. if (!IsFilteredTemplateName)
  699. FilterAcceptableTemplateNames(Result);
  700. if (!Result.empty()) {
  701. bool IsFunctionTemplate;
  702. TemplateName Template;
  703. if (Result.end() - Result.begin() > 1) {
  704. IsFunctionTemplate = true;
  705. Template = Context.getOverloadedTemplateName(Result.begin(),
  706. Result.end());
  707. } else {
  708. TemplateDecl *TD
  709. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  710. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  711. if (SS.isSet() && !SS.isInvalid())
  712. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  713. /*TemplateKeyword=*/false,
  714. TD);
  715. else
  716. Template = TemplateName(TD);
  717. }
  718. if (IsFunctionTemplate) {
  719. // Function templates always go through overload resolution, at which
  720. // point we'll perform the various checks (e.g., accessibility) we need
  721. // to based on which function we selected.
  722. Result.suppressDiagnostics();
  723. return NameClassification::FunctionTemplate(Template);
  724. }
  725. return NameClassification::TypeTemplate(Template);
  726. }
  727. }
  728. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  729. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  730. DiagnoseUseOfDecl(Type, NameLoc);
  731. QualType T = Context.getTypeDeclType(Type);
  732. if (SS.isNotEmpty())
  733. return buildNestedType(*this, SS, T, NameLoc);
  734. return ParsedType::make(T);
  735. }
  736. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  737. if (!Class) {
  738. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  739. if (ObjCCompatibleAliasDecl *Alias
  740. = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  741. Class = Alias->getClassInterface();
  742. }
  743. if (Class) {
  744. DiagnoseUseOfDecl(Class, NameLoc);
  745. if (NextToken.is(tok::period)) {
  746. // Interface. <something> is parsed as a property reference expression.
  747. // Just return "unknown" as a fall-through for now.
  748. Result.suppressDiagnostics();
  749. return NameClassification::Unknown();
  750. }
  751. QualType T = Context.getObjCInterfaceType(Class);
  752. return ParsedType::make(T);
  753. }
  754. // We can have a type template here if we're classifying a template argument.
  755. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
  756. return NameClassification::TypeTemplate(
  757. TemplateName(cast<TemplateDecl>(FirstDecl)));
  758. // Check for a tag type hidden by a non-type decl in a few cases where it
  759. // seems likely a type is wanted instead of the non-type that was found.
  760. if (!getLangOpts().ObjC1) {
  761. bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
  762. if ((NextToken.is(tok::identifier) ||
  763. (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
  764. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  765. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  766. DiagnoseUseOfDecl(Type, NameLoc);
  767. QualType T = Context.getTypeDeclType(Type);
  768. if (SS.isNotEmpty())
  769. return buildNestedType(*this, SS, T, NameLoc);
  770. return ParsedType::make(T);
  771. }
  772. }
  773. if (FirstDecl->isCXXClassMember())
  774. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
  775. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  776. return BuildDeclarationNameExpr(SS, Result, ADL);
  777. }
  778. // Determines the context to return to after temporarily entering a
  779. // context. This depends in an unnecessarily complicated way on the
  780. // exact ordering of callbacks from the parser.
  781. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  782. // Functions defined inline within classes aren't parsed until we've
  783. // finished parsing the top-level class, so the top-level class is
  784. // the context we'll need to return to.
  785. if (isa<FunctionDecl>(DC)) {
  786. DC = DC->getLexicalParent();
  787. // A function not defined within a class will always return to its
  788. // lexical context.
  789. if (!isa<CXXRecordDecl>(DC))
  790. return DC;
  791. // A C++ inline method/friend is parsed *after* the topmost class
  792. // it was declared in is fully parsed ("complete"); the topmost
  793. // class is the context we need to return to.
  794. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  795. DC = RD;
  796. // Return the declaration context of the topmost class the inline method is
  797. // declared in.
  798. return DC;
  799. }
  800. return DC->getLexicalParent();
  801. }
  802. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  803. assert(getContainingDC(DC) == CurContext &&
  804. "The next DeclContext should be lexically contained in the current one.");
  805. CurContext = DC;
  806. S->setEntity(DC);
  807. }
  808. void Sema::PopDeclContext() {
  809. assert(CurContext && "DeclContext imbalance!");
  810. CurContext = getContainingDC(CurContext);
  811. assert(CurContext && "Popped translation unit!");
  812. }
  813. /// EnterDeclaratorContext - Used when we must lookup names in the context
  814. /// of a declarator's nested name specifier.
  815. ///
  816. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  817. // C++0x [basic.lookup.unqual]p13:
  818. // A name used in the definition of a static data member of class
  819. // X (after the qualified-id of the static member) is looked up as
  820. // if the name was used in a member function of X.
  821. // C++0x [basic.lookup.unqual]p14:
  822. // If a variable member of a namespace is defined outside of the
  823. // scope of its namespace then any name used in the definition of
  824. // the variable member (after the declarator-id) is looked up as
  825. // if the definition of the variable member occurred in its
  826. // namespace.
  827. // Both of these imply that we should push a scope whose context
  828. // is the semantic context of the declaration. We can't use
  829. // PushDeclContext here because that context is not necessarily
  830. // lexically contained in the current context. Fortunately,
  831. // the containing scope should have the appropriate information.
  832. assert(!S->getEntity() && "scope already has entity");
  833. #ifndef NDEBUG
  834. Scope *Ancestor = S->getParent();
  835. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  836. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  837. #endif
  838. CurContext = DC;
  839. S->setEntity(DC);
  840. }
  841. void Sema::ExitDeclaratorContext(Scope *S) {
  842. assert(S->getEntity() == CurContext && "Context imbalance!");
  843. // Switch back to the lexical context. The safety of this is
  844. // enforced by an assert in EnterDeclaratorContext.
  845. Scope *Ancestor = S->getParent();
  846. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  847. CurContext = (DeclContext*) Ancestor->getEntity();
  848. // We don't need to do anything with the scope, which is going to
  849. // disappear.
  850. }
  851. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  852. FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  853. if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
  854. // We assume that the caller has already called
  855. // ActOnReenterTemplateScope
  856. FD = TFD->getTemplatedDecl();
  857. }
  858. if (!FD)
  859. return;
  860. // Same implementation as PushDeclContext, but enters the context
  861. // from the lexical parent, rather than the top-level class.
  862. assert(CurContext == FD->getLexicalParent() &&
  863. "The next DeclContext should be lexically contained in the current one.");
  864. CurContext = FD;
  865. S->setEntity(CurContext);
  866. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  867. ParmVarDecl *Param = FD->getParamDecl(P);
  868. // If the parameter has an identifier, then add it to the scope
  869. if (Param->getIdentifier()) {
  870. S->AddDecl(Param);
  871. IdResolver.AddDecl(Param);
  872. }
  873. }
  874. }
  875. void Sema::ActOnExitFunctionContext() {
  876. // Same implementation as PopDeclContext, but returns to the lexical parent,
  877. // rather than the top-level class.
  878. assert(CurContext && "DeclContext imbalance!");
  879. CurContext = CurContext->getLexicalParent();
  880. assert(CurContext && "Popped translation unit!");
  881. }
  882. /// \brief Determine whether we allow overloading of the function
  883. /// PrevDecl with another declaration.
  884. ///
  885. /// This routine determines whether overloading is possible, not
  886. /// whether some new function is actually an overload. It will return
  887. /// true in C++ (where we can always provide overloads) or, as an
  888. /// extension, in C when the previous function is already an
  889. /// overloaded function declaration or has the "overloadable"
  890. /// attribute.
  891. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  892. ASTContext &Context) {
  893. if (Context.getLangOpts().CPlusPlus)
  894. return true;
  895. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  896. return true;
  897. return (Previous.getResultKind() == LookupResult::Found
  898. && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
  899. }
  900. /// Add this decl to the scope shadowed decl chains.
  901. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  902. // Move up the scope chain until we find the nearest enclosing
  903. // non-transparent context. The declaration will be introduced into this
  904. // scope.
  905. while (S->getEntity() &&
  906. ((DeclContext *)S->getEntity())->isTransparentContext())
  907. S = S->getParent();
  908. // Add scoped declarations into their context, so that they can be
  909. // found later. Declarations without a context won't be inserted
  910. // into any context.
  911. if (AddToContext)
  912. CurContext->addDecl(D);
  913. // Out-of-line definitions shouldn't be pushed into scope in C++.
  914. // Out-of-line variable and function definitions shouldn't even in C.
  915. if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
  916. D->isOutOfLine() &&
  917. !D->getDeclContext()->getRedeclContext()->Equals(
  918. D->getLexicalDeclContext()->getRedeclContext()))
  919. return;
  920. // Template instantiations should also not be pushed into scope.
  921. if (isa<FunctionDecl>(D) &&
  922. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  923. return;
  924. // If this replaces anything in the current scope,
  925. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  926. IEnd = IdResolver.end();
  927. for (; I != IEnd; ++I) {
  928. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  929. S->RemoveDecl(*I);
  930. IdResolver.RemoveDecl(*I);
  931. // Should only need to replace one decl.
  932. break;
  933. }
  934. }
  935. S->AddDecl(D);
  936. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  937. // Implicitly-generated labels may end up getting generated in an order that
  938. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  939. // the label at the appropriate place in the identifier chain.
  940. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  941. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  942. if (IDC == CurContext) {
  943. if (!S->isDeclScope(*I))
  944. continue;
  945. } else if (IDC->Encloses(CurContext))
  946. break;
  947. }
  948. IdResolver.InsertDeclAfter(I, D);
  949. } else {
  950. IdResolver.AddDecl(D);
  951. }
  952. }
  953. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  954. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  955. TUScope->AddDecl(D);
  956. }
  957. bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
  958. bool ExplicitInstantiationOrSpecialization) {
  959. return IdResolver.isDeclInScope(D, Ctx, Context, S,
  960. ExplicitInstantiationOrSpecialization);
  961. }
  962. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  963. DeclContext *TargetDC = DC->getPrimaryContext();
  964. do {
  965. if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
  966. if (ScopeDC->getPrimaryContext() == TargetDC)
  967. return S;
  968. } while ((S = S->getParent()));
  969. return 0;
  970. }
  971. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  972. DeclContext*,
  973. ASTContext&);
  974. /// Filters out lookup results that don't fall within the given scope
  975. /// as determined by isDeclInScope.
  976. void Sema::FilterLookupForScope(LookupResult &R,
  977. DeclContext *Ctx, Scope *S,
  978. bool ConsiderLinkage,
  979. bool ExplicitInstantiationOrSpecialization) {
  980. LookupResult::Filter F = R.makeFilter();
  981. while (F.hasNext()) {
  982. NamedDecl *D = F.next();
  983. if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
  984. continue;
  985. if (ConsiderLinkage &&
  986. isOutOfScopePreviousDeclaration(D, Ctx, Context))
  987. continue;
  988. F.erase();
  989. }
  990. F.done();
  991. }
  992. static bool isUsingDecl(NamedDecl *D) {
  993. return isa<UsingShadowDecl>(D) ||
  994. isa<UnresolvedUsingTypenameDecl>(D) ||
  995. isa<UnresolvedUsingValueDecl>(D);
  996. }
  997. /// Removes using shadow declarations from the lookup results.
  998. static void RemoveUsingDecls(LookupResult &R) {
  999. LookupResult::Filter F = R.makeFilter();
  1000. while (F.hasNext())
  1001. if (isUsingDecl(F.next()))
  1002. F.erase();
  1003. F.done();
  1004. }
  1005. /// \brief Check for this common pattern:
  1006. /// @code
  1007. /// class S {
  1008. /// S(const S&); // DO NOT IMPLEMENT
  1009. /// void operator=(const S&); // DO NOT IMPLEMENT
  1010. /// };
  1011. /// @endcode
  1012. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1013. // FIXME: Should check for private access too but access is set after we get
  1014. // the decl here.
  1015. if (D->doesThisDeclarationHaveABody())
  1016. return false;
  1017. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1018. return CD->isCopyConstructor();
  1019. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  1020. return Method->isCopyAssignmentOperator();
  1021. return false;
  1022. }
  1023. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1024. assert(D);
  1025. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1026. return false;
  1027. // Ignore class templates.
  1028. if (D->getDeclContext()->isDependentContext() ||
  1029. D->getLexicalDeclContext()->isDependentContext())
  1030. return false;
  1031. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1032. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1033. return false;
  1034. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1035. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1036. return false;
  1037. } else {
  1038. // 'static inline' functions are used in headers; don't warn.
  1039. if (FD->getStorageClass() == SC_Static &&
  1040. FD->isInlineSpecified())
  1041. return false;
  1042. }
  1043. if (FD->doesThisDeclarationHaveABody() &&
  1044. Context.DeclMustBeEmitted(FD))
  1045. return false;
  1046. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1047. if (!VD->isFileVarDecl() ||
  1048. VD->getType().isConstant(Context) ||
  1049. Context.DeclMustBeEmitted(VD))
  1050. return false;
  1051. if (VD->isStaticDataMember() &&
  1052. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1053. return false;
  1054. } else {
  1055. return false;
  1056. }
  1057. // Only warn for unused decls internal to the translation unit.
  1058. if (D->getLinkage() == ExternalLinkage)
  1059. return false;
  1060. return true;
  1061. }
  1062. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1063. if (!D)
  1064. return;
  1065. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1066. const FunctionDecl *First = FD->getFirstDeclaration();
  1067. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1068. return; // First should already be in the vector.
  1069. }
  1070. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1071. const VarDecl *First = VD->getFirstDeclaration();
  1072. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1073. return; // First should already be in the vector.
  1074. }
  1075. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1076. UnusedFileScopedDecls.push_back(D);
  1077. }
  1078. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1079. if (D->isInvalidDecl())
  1080. return false;
  1081. if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1082. return false;
  1083. if (isa<LabelDecl>(D))
  1084. return true;
  1085. // White-list anything that isn't a local variable.
  1086. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
  1087. !D->getDeclContext()->isFunctionOrMethod())
  1088. return false;
  1089. // Types of valid local variables should be complete, so this should succeed.
  1090. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1091. // White-list anything with an __attribute__((unused)) type.
  1092. QualType Ty = VD->getType();
  1093. // Only look at the outermost level of typedef.
  1094. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1095. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1096. return false;
  1097. }
  1098. // If we failed to complete the type for some reason, or if the type is
  1099. // dependent, don't diagnose the variable.
  1100. if (Ty->isIncompleteType() || Ty->isDependentType())
  1101. return false;
  1102. if (const TagType *TT = Ty->getAs<TagType>()) {
  1103. const TagDecl *Tag = TT->getDecl();
  1104. if (Tag->hasAttr<UnusedAttr>())
  1105. return false;
  1106. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1107. if (!RD->hasTrivialDestructor())
  1108. return false;
  1109. if (const Expr *Init = VD->getInit()) {
  1110. const CXXConstructExpr *Construct =
  1111. dyn_cast<CXXConstructExpr>(Init);
  1112. if (Construct && !Construct->isElidable()) {
  1113. CXXConstructorDecl *CD = Construct->getConstructor();
  1114. if (!CD->isTrivial())
  1115. return false;
  1116. }
  1117. }
  1118. }
  1119. }
  1120. // TODO: __attribute__((unused)) templates?
  1121. }
  1122. return true;
  1123. }
  1124. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1125. FixItHint &Hint) {
  1126. if (isa<LabelDecl>(D)) {
  1127. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1128. tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
  1129. if (AfterColon.isInvalid())
  1130. return;
  1131. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1132. getCharRange(D->getLocStart(), AfterColon));
  1133. }
  1134. return;
  1135. }
  1136. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1137. /// unless they are marked attr(unused).
  1138. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1139. FixItHint Hint;
  1140. if (!ShouldDiagnoseUnusedDecl(D))
  1141. return;
  1142. GenerateFixForUnusedDecl(D, Context, Hint);
  1143. unsigned DiagID;
  1144. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1145. DiagID = diag::warn_unused_exception_param;
  1146. else if (isa<LabelDecl>(D))
  1147. DiagID = diag::warn_unused_label;
  1148. else
  1149. DiagID = diag::warn_unused_variable;
  1150. Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
  1151. }
  1152. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1153. // Verify that we have no forward references left. If so, there was a goto
  1154. // or address of a label taken, but no definition of it. Label fwd
  1155. // definitions are indicated with a null substmt.
  1156. if (L->getStmt() == 0)
  1157. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1158. }
  1159. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1160. if (S->decl_empty()) return;
  1161. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1162. "Scope shouldn't contain decls!");
  1163. for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
  1164. I != E; ++I) {
  1165. Decl *TmpD = (*I);
  1166. assert(TmpD && "This decl didn't get pushed??");
  1167. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1168. NamedDecl *D = cast<NamedDecl>(TmpD);
  1169. if (!D->getDeclName()) continue;
  1170. // Diagnose unused variables in this scope.
  1171. if (!S->hasErrorOccurred())
  1172. DiagnoseUnusedDecl(D);
  1173. // If this was a forward reference to a label, verify it was defined.
  1174. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1175. CheckPoppedLabel(LD, *this);
  1176. // Remove this name from our lexical scope.
  1177. IdResolver.RemoveDecl(D);
  1178. }
  1179. }
  1180. void Sema::ActOnStartFunctionDeclarator() {
  1181. ++InFunctionDeclarator;
  1182. }
  1183. void Sema::ActOnEndFunctionDeclarator() {
  1184. assert(InFunctionDeclarator);
  1185. --InFunctionDeclarator;
  1186. }
  1187. /// \brief Look for an Objective-C class in the translation unit.
  1188. ///
  1189. /// \param Id The name of the Objective-C class we're looking for. If
  1190. /// typo-correction fixes this name, the Id will be updated
  1191. /// to the fixed name.
  1192. ///
  1193. /// \param IdLoc The location of the name in the translation unit.
  1194. ///
  1195. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1196. /// if there is no class with the given name.
  1197. ///
  1198. /// \returns The declaration of the named Objective-C class, or NULL if the
  1199. /// class could not be found.
  1200. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1201. SourceLocation IdLoc,
  1202. bool DoTypoCorrection) {
  1203. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1204. // creation from this context.
  1205. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1206. if (!IDecl && DoTypoCorrection) {
  1207. // Perform typo correction at the given location, but only if we
  1208. // find an Objective-C class name.
  1209. DeclFilterCCC<ObjCInterfaceDecl> Validator;
  1210. if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
  1211. LookupOrdinaryName, TUScope, NULL,
  1212. Validator)) {
  1213. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1214. Diag(IdLoc, diag::err_undef_interface_suggest)
  1215. << Id << IDecl->getDeclName()
  1216. << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
  1217. Diag(IDecl->getLocation(), diag::note_previous_decl)
  1218. << IDecl->getDeclName();
  1219. Id = IDecl->getIdentifier();
  1220. }
  1221. }
  1222. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1223. // This routine must always return a class definition, if any.
  1224. if (Def && Def->getDefinition())
  1225. Def = Def->getDefinition();
  1226. return Def;
  1227. }
  1228. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1229. /// from S, where a non-field would be declared. This routine copes
  1230. /// with the difference between C and C++ scoping rules in structs and
  1231. /// unions. For example, the following code is well-formed in C but
  1232. /// ill-formed in C++:
  1233. /// @code
  1234. /// struct S6 {
  1235. /// enum { BAR } e;
  1236. /// };
  1237. ///
  1238. /// void test_S6() {
  1239. /// struct S6 a;
  1240. /// a.e = BAR;
  1241. /// }
  1242. /// @endcode
  1243. /// For the declaration of BAR, this routine will return a different
  1244. /// scope. The scope S will be the scope of the unnamed enumeration
  1245. /// within S6. In C++, this routine will return the scope associated
  1246. /// with S6, because the enumeration's scope is a transparent
  1247. /// context but structures can contain non-field names. In C, this
  1248. /// routine will return the translation unit scope, since the
  1249. /// enumeration's scope is a transparent context and structures cannot
  1250. /// contain non-field names.
  1251. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1252. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1253. (S->getEntity() &&
  1254. ((DeclContext *)S->getEntity())->isTransparentContext()) ||
  1255. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1256. S = S->getParent();
  1257. return S;
  1258. }
  1259. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1260. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1261. /// if we're creating this built-in in anticipation of redeclaring the
  1262. /// built-in.
  1263. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
  1264. Scope *S, bool ForRedeclaration,
  1265. SourceLocation Loc) {
  1266. Builtin::ID BID = (Builtin::ID)bid;
  1267. ASTContext::GetBuiltinTypeError Error;
  1268. QualType R = Context.GetBuiltinType(BID, Error);
  1269. switch (Error) {
  1270. case ASTContext::GE_None:
  1271. // Okay
  1272. break;
  1273. case ASTContext::GE_Missing_stdio:
  1274. if (ForRedeclaration)
  1275. Diag(Loc, diag::warn_implicit_decl_requires_stdio)
  1276. << Context.BuiltinInfo.GetName(BID);
  1277. return 0;
  1278. case ASTContext::GE_Missing_setjmp:
  1279. if (ForRedeclaration)
  1280. Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
  1281. << Context.BuiltinInfo.GetName(BID);
  1282. return 0;
  1283. case ASTContext::GE_Missing_ucontext:
  1284. if (ForRedeclaration)
  1285. Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
  1286. << Context.BuiltinInfo.GetName(BID);
  1287. return 0;
  1288. }
  1289. if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  1290. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1291. << Context.BuiltinInfo.GetName(BID)
  1292. << R;
  1293. if (Context.BuiltinInfo.getHeaderName(BID) &&
  1294. Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
  1295. != DiagnosticsEngine::Ignored)
  1296. Diag(Loc, diag::note_please_include_header)
  1297. << Context.BuiltinInfo.getHeaderName(BID)
  1298. << Context.BuiltinInfo.GetName(BID);
  1299. }
  1300. FunctionDecl *New = FunctionDecl::Create(Context,
  1301. Context.getTranslationUnitDecl(),
  1302. Loc, Loc, II, R, /*TInfo=*/0,
  1303. SC_Extern,
  1304. SC_None, false,
  1305. /*hasPrototype=*/true);
  1306. New->setImplicit();
  1307. // Create Decl objects for each parameter, adding them to the
  1308. // FunctionDecl.
  1309. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1310. SmallVector<ParmVarDecl*, 16> Params;
  1311. for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
  1312. ParmVarDecl *parm =
  1313. ParmVarDecl::Create(Context, New, SourceLocation(),
  1314. SourceLocation(), 0,
  1315. FT->getArgType(i), /*TInfo=*/0,
  1316. SC_None, SC_None, 0);
  1317. parm->setScopeInfo(0, i);
  1318. Params.push_back(parm);
  1319. }
  1320. New->setParams(Params);
  1321. }
  1322. AddKnownFunctionAttributes(New);
  1323. // TUScope is the translation-unit scope to insert this function into.
  1324. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1325. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1326. // entirely, but we're not there yet.
  1327. DeclContext *SavedContext = CurContext;
  1328. CurContext = Context.getTranslationUnitDecl();
  1329. PushOnScopeChains(New, TUScope);
  1330. CurContext = SavedContext;
  1331. return New;
  1332. }
  1333. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1334. QualType OldType;
  1335. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1336. OldType = OldTypedef->getUnderlyingType();
  1337. else
  1338. OldType = Context.getTypeDeclType(Old);
  1339. QualType NewType = New->getUnderlyingType();
  1340. if (NewType->isVariablyModifiedType()) {
  1341. // Must not redefine a typedef with a variably-modified type.
  1342. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1343. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1344. << Kind << NewType;
  1345. if (Old->getLocation().isValid())
  1346. Diag(Old->getLocation(), diag::note_previous_definition);
  1347. New->setInvalidDecl();
  1348. return true;
  1349. }
  1350. if (OldType != NewType &&
  1351. !OldType->isDependentType() &&
  1352. !NewType->isDependentType() &&
  1353. !Context.hasSameType(OldType, NewType)) {
  1354. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1355. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1356. << Kind << NewType << OldType;
  1357. if (Old->getLocation().isValid())
  1358. Diag(Old->getLocation(), diag::note_previous_definition);
  1359. New->setInvalidDecl();
  1360. return true;
  1361. }
  1362. return false;
  1363. }
  1364. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1365. /// same name and scope as a previous declaration 'Old'. Figure out
  1366. /// how to resolve this situation, merging decls or emitting
  1367. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1368. ///
  1369. void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
  1370. // If the new decl is known invalid already, don't bother doing any
  1371. // merging checks.
  1372. if (New->isInvalidDecl()) return;
  1373. // Allow multiple definitions for ObjC built-in typedefs.
  1374. // FIXME: Verify the underlying types are equivalent!
  1375. if (getLangOpts().ObjC1) {
  1376. const IdentifierInfo *TypeID = New->getIdentifier();
  1377. switch (TypeID->getLength()) {
  1378. default: break;
  1379. case 2:
  1380. {
  1381. if (!TypeID->isStr("id"))
  1382. break;
  1383. QualType T = New->getUnderlyingType();
  1384. if (!T->isPointerType())
  1385. break;
  1386. if (!T->isVoidPointerType()) {
  1387. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1388. if (!PT->isStructureType())
  1389. break;
  1390. }
  1391. Context.setObjCIdRedefinitionType(T);
  1392. // Install the built-in type for 'id', ignoring the current definition.
  1393. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1394. return;
  1395. }
  1396. case 5:
  1397. if (!TypeID->isStr("Class"))
  1398. break;
  1399. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1400. // Install the built-in type for 'Class', ignoring the current definition.
  1401. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1402. return;
  1403. case 3:
  1404. if (!TypeID->isStr("SEL"))
  1405. break;
  1406. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1407. // Install the built-in type for 'SEL', ignoring the current definition.
  1408. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1409. return;
  1410. }
  1411. // Fall through - the typedef name was not a builtin type.
  1412. }
  1413. // Verify the old decl was also a type.
  1414. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1415. if (!Old) {
  1416. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1417. << New->getDeclName();
  1418. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1419. if (OldD->getLocation().isValid())
  1420. Diag(OldD->getLocation(), diag::note_previous_definition);
  1421. return New->setInvalidDecl();
  1422. }
  1423. // If the old declaration is invalid, just give up here.
  1424. if (Old->isInvalidDecl())
  1425. return New->setInvalidDecl();
  1426. // If the typedef types are not identical, reject them in all languages and
  1427. // with any extensions enabled.
  1428. if (isIncompatibleTypedef(Old, New))
  1429. return;
  1430. // The types match. Link up the redeclaration chain if the old
  1431. // declaration was a typedef.
  1432. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
  1433. New->setPreviousDeclaration(Typedef);
  1434. if (getLangOpts().MicrosoftExt)
  1435. return;
  1436. if (getLangOpts().CPlusPlus) {
  1437. // C++ [dcl.typedef]p2:
  1438. // In a given non-class scope, a typedef specifier can be used to
  1439. // redefine the name of any type declared in that scope to refer
  1440. // to the type to which it already refers.
  1441. if (!isa<CXXRecordDecl>(CurContext))
  1442. return;
  1443. // C++0x [dcl.typedef]p4:
  1444. // In a given class scope, a typedef specifier can be used to redefine
  1445. // any class-name declared in that scope that is not also a typedef-name
  1446. // to refer to the type to which it already refers.
  1447. //
  1448. // This wording came in via DR424, which was a correction to the
  1449. // wording in DR56, which accidentally banned code like:
  1450. //
  1451. // struct S {
  1452. // typedef struct A { } A;
  1453. // };
  1454. //
  1455. // in the C++03 standard. We implement the C++0x semantics, which
  1456. // allow the above but disallow
  1457. //
  1458. // struct S {
  1459. // typedef int I;
  1460. // typedef int I;
  1461. // };
  1462. //
  1463. // since that was the intent of DR56.
  1464. if (!isa<TypedefNameDecl>(Old))
  1465. return;
  1466. Diag(New->getLocation(), diag::err_redefinition)
  1467. << New->getDeclName();
  1468. Diag(Old->getLocation(), diag::note_previous_definition);
  1469. return New->setInvalidDecl();
  1470. }
  1471. // Modules always permit redefinition of typedefs, as does C11.
  1472. if (getLangOpts().Modules || getLangOpts().C11)
  1473. return;
  1474. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1475. // is normally mapped to an error, but can be controlled with
  1476. // -Wtypedef-redefinition. If either the original or the redefinition is
  1477. // in a system header, don't emit this for compatibility with GCC.
  1478. if (getDiagnostics().getSuppressSystemWarnings() &&
  1479. (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1480. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1481. return;
  1482. Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
  1483. << New->getDeclName();
  1484. Diag(Old->getLocation(), diag::note_previous_definition);
  1485. return;
  1486. }
  1487. /// DeclhasAttr - returns true if decl Declaration already has the target
  1488. /// attribute.
  1489. static bool
  1490. DeclHasAttr(const Decl *D, const Attr *A) {
  1491. // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
  1492. // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
  1493. // responsible for making sure they are consistent.
  1494. const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
  1495. if (AA)
  1496. return false;
  1497. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  1498. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  1499. for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
  1500. if ((*i)->getKind() == A->getKind()) {
  1501. if (Ann) {
  1502. if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
  1503. return true;
  1504. continue;
  1505. }
  1506. // FIXME: Don't hardcode this check
  1507. if (OA && isa<OwnershipAttr>(*i))
  1508. return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
  1509. return true;
  1510. }
  1511. return false;
  1512. }
  1513. bool Sema::mergeDeclAttribute(Decl *D, InheritableAttr *Attr) {
  1514. InheritableAttr *NewAttr = NULL;
  1515. if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
  1516. NewAttr = mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
  1517. AA->getIntroduced(), AA->getDeprecated(),
  1518. AA->getObsoleted(), AA->getUnavailable(),
  1519. AA->getMessage());
  1520. else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
  1521. NewAttr = mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility());
  1522. else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
  1523. NewAttr = mergeDLLImportAttr(D, ImportA->getRange());
  1524. else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
  1525. NewAttr = mergeDLLExportAttr(D, ExportA->getRange());
  1526. else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
  1527. NewAttr = mergeFormatAttr(D, FA->getRange(), FA->getType(),
  1528. FA->getFormatIdx(), FA->getFirstArg());
  1529. else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
  1530. NewAttr = mergeSectionAttr(D, SA->getRange(), SA->getName());
  1531. else if (!DeclHasAttr(D, Attr))
  1532. NewAttr = cast<InheritableAttr>(Attr->clone(Context));
  1533. if (NewAttr) {
  1534. NewAttr->setInherited(true);
  1535. D->addAttr(NewAttr);
  1536. return true;
  1537. }
  1538. return false;
  1539. }
  1540. static const Decl *getDefinition(const Decl *D) {
  1541. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  1542. return TD->getDefinition();
  1543. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1544. return VD->getDefinition();
  1545. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1546. const FunctionDecl* Def;
  1547. if (FD->hasBody(Def))
  1548. return Def;
  1549. }
  1550. return NULL;
  1551. }
  1552. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  1553. for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
  1554. I != E; ++I) {
  1555. Attr *Attribute = *I;
  1556. if (Attribute->getKind() == Kind)
  1557. return true;
  1558. }
  1559. return false;
  1560. }
  1561. /// checkNewAttributesAfterDef - If we already have a definition, check that
  1562. /// there are no new attributes in this declaration.
  1563. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  1564. if (!New->hasAttrs())
  1565. return;
  1566. const Decl *Def = getDefinition(Old);
  1567. if (!Def || Def == New)
  1568. return;
  1569. AttrVec &NewAttributes = New->getAttrs();
  1570. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  1571. const Attr *NewAttribute = NewAttributes[I];
  1572. if (hasAttribute(Def, NewAttribute->getKind())) {
  1573. ++I;
  1574. continue; // regular attr merging will take care of validating this.
  1575. }
  1576. S.Diag(NewAttribute->getLocation(),
  1577. diag::warn_attribute_precede_definition);
  1578. S.Diag(Def->getLocation(), diag::note_previous_definition);
  1579. NewAttributes.erase(NewAttributes.begin() + I);
  1580. --E;
  1581. }
  1582. }
  1583. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  1584. void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
  1585. bool MergeDeprecation) {
  1586. // attributes declared post-definition are currently ignored
  1587. checkNewAttributesAfterDef(*this, New, Old);
  1588. if (!Old->hasAttrs())
  1589. return;
  1590. bool foundAny = New->hasAttrs();
  1591. // Ensure that any moving of objects within the allocated map is done before
  1592. // we process them.
  1593. if (!foundAny) New->setAttrs(AttrVec());
  1594. for (specific_attr_iterator<InheritableAttr>
  1595. i = Old->specific_attr_begin<InheritableAttr>(),
  1596. e = Old->specific_attr_end<InheritableAttr>();
  1597. i != e; ++i) {
  1598. // Ignore deprecated/unavailable/availability attributes if requested.
  1599. if (!MergeDeprecation &&
  1600. (isa<DeprecatedAttr>(*i) ||
  1601. isa<UnavailableAttr>(*i) ||
  1602. isa<AvailabilityAttr>(*i)))
  1603. continue;
  1604. if (mergeDeclAttribute(New, *i))
  1605. foundAny = true;
  1606. }
  1607. if (!foundAny) New->dropAttrs();
  1608. }
  1609. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  1610. /// to the new one.
  1611. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  1612. const ParmVarDecl *oldDecl,
  1613. ASTContext &C) {
  1614. if (!oldDecl->hasAttrs())
  1615. return;
  1616. bool foundAny = newDecl->hasAttrs();
  1617. // Ensure that any moving of objects within the allocated map is
  1618. // done before we process them.
  1619. if (!foundAny) newDecl->setAttrs(AttrVec());
  1620. for (specific_attr_iterator<InheritableParamAttr>
  1621. i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
  1622. e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
  1623. if (!DeclHasAttr(newDecl, *i)) {
  1624. InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
  1625. newAttr->setInherited(true);
  1626. newDecl->addAttr(newAttr);
  1627. foundAny = true;
  1628. }
  1629. }
  1630. if (!foundAny) newDecl->dropAttrs();
  1631. }
  1632. namespace {
  1633. /// Used in MergeFunctionDecl to keep track of function parameters in
  1634. /// C.
  1635. struct GNUCompatibleParamWarning {
  1636. ParmVarDecl *OldParm;
  1637. ParmVarDecl *NewParm;
  1638. QualType PromotedType;
  1639. };
  1640. }
  1641. /// getSpecialMember - get the special member enum for a method.
  1642. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  1643. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  1644. if (Ctor->isDefaultConstructor())
  1645. return Sema::CXXDefaultConstructor;
  1646. if (Ctor->isCopyConstructor())
  1647. return Sema::CXXCopyConstructor;
  1648. if (Ctor->isMoveConstructor())
  1649. return Sema::CXXMoveConstructor;
  1650. } else if (isa<CXXDestructorDecl>(MD)) {
  1651. return Sema::CXXDestructor;
  1652. } else if (MD->isCopyAssignmentOperator()) {
  1653. return Sema::CXXCopyAssignment;
  1654. } else if (MD->isMoveAssignmentOperator()) {
  1655. return Sema::CXXMoveAssignment;
  1656. }
  1657. return Sema::CXXInvalid;
  1658. }
  1659. /// canRedefineFunction - checks if a function can be redefined. Currently,
  1660. /// only extern inline functions can be redefined, and even then only in
  1661. /// GNU89 mode.
  1662. static bool canRedefineFunction(const FunctionDecl *FD,
  1663. const LangOptions& LangOpts) {
  1664. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  1665. !LangOpts.CPlusPlus &&
  1666. FD->isInlineSpecified() &&
  1667. FD->getStorageClass() == SC_Extern);
  1668. }
  1669. /// Is the given calling convention the ABI default for the given
  1670. /// declaration?
  1671. static bool isABIDefaultCC(Sema &S, CallingConv CC, FunctionDecl *D) {
  1672. CallingConv ABIDefaultCC;
  1673. if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  1674. ABIDefaultCC = S.Context.getDefaultCXXMethodCallConv(D->isVariadic());
  1675. } else {
  1676. // Free C function or a static method.
  1677. ABIDefaultCC = (S.Context.getLangOpts().MRTD ? CC_X86StdCall : CC_C);
  1678. }
  1679. return ABIDefaultCC == CC;
  1680. }
  1681. /// MergeFunctionDecl - We just parsed a function 'New' from
  1682. /// declarator D which has the same name and scope as a previous
  1683. /// declaration 'Old'. Figure out how to resolve this situation,
  1684. /// merging decls or emitting diagnostics as appropriate.
  1685. ///
  1686. /// In C++, New and Old must be declarations that are not
  1687. /// overloaded. Use IsOverload to determine whether New and Old are
  1688. /// overloaded, and to select the Old declaration that New should be
  1689. /// merged with.
  1690. ///
  1691. /// Returns true if there was an error, false otherwise.
  1692. bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
  1693. // Verify the old decl was also a function.
  1694. FunctionDecl *Old = 0;
  1695. if (FunctionTemplateDecl *OldFunctionTemplate
  1696. = dyn_cast<FunctionTemplateDecl>(OldD))
  1697. Old = OldFunctionTemplate->getTemplatedDecl();
  1698. else
  1699. Old = dyn_cast<FunctionDecl>(OldD);
  1700. if (!Old) {
  1701. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  1702. Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  1703. Diag(Shadow->getTargetDecl()->getLocation(),
  1704. diag::note_using_decl_target);
  1705. Diag(Shadow->getUsingDecl()->getLocation(),
  1706. diag::note_using_decl) << 0;
  1707. return true;
  1708. }
  1709. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1710. << New->getDeclName();
  1711. Diag(OldD->getLocation(), diag::note_previous_definition);
  1712. return true;
  1713. }
  1714. // Determine whether the previous declaration was a definition,
  1715. // implicit declaration, or a declaration.
  1716. diag::kind PrevDiag;
  1717. if (Old->isThisDeclarationADefinition())
  1718. PrevDiag = diag::note_previous_definition;
  1719. else if (Old->isImplicit())
  1720. PrevDiag = diag::note_previous_implicit_declaration;
  1721. else
  1722. PrevDiag = diag::note_previous_declaration;
  1723. QualType OldQType = Context.getCanonicalType(Old->getType());
  1724. QualType NewQType = Context.getCanonicalType(New->getType());
  1725. // Don't complain about this if we're in GNU89 mode and the old function
  1726. // is an extern inline function.
  1727. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  1728. New->getStorageClass() == SC_Static &&
  1729. Old->getStorageClass() != SC_Static &&
  1730. !canRedefineFunction(Old, getLangOpts())) {
  1731. if (getLangOpts().MicrosoftExt) {
  1732. Diag(New->getLocation(), diag::warn_static_non_static) << New;
  1733. Diag(Old->getLocation(), PrevDiag);
  1734. } else {
  1735. Diag(New->getLocation(), diag::err_static_non_static) << New;
  1736. Diag(Old->getLocation(), PrevDiag);
  1737. return true;
  1738. }
  1739. }
  1740. // If a function is first declared with a calling convention, but is
  1741. // later declared or defined without one, the second decl assumes the
  1742. // calling convention of the first.
  1743. //
  1744. // It's OK if a function is first declared without a calling convention,
  1745. // but is later declared or defined with the default calling convention.
  1746. //
  1747. // For the new decl, we have to look at the NON-canonical type to tell the
  1748. // difference between a function that really doesn't have a calling
  1749. // convention and one that is declared cdecl. That's because in
  1750. // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
  1751. // because it is the default calling convention.
  1752. //
  1753. // Note also that we DO NOT return at this point, because we still have
  1754. // other tests to run.
  1755. const FunctionType *OldType = cast<FunctionType>(OldQType);
  1756. const FunctionType *NewType = New->getType()->getAs<FunctionType>();
  1757. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  1758. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  1759. bool RequiresAdjustment = false;
  1760. if (OldTypeInfo.getCC() == NewTypeInfo.getCC()) {
  1761. // Fast path: nothing to do.
  1762. // Inherit the CC from the previous declaration if it was specified
  1763. // there but not here.
  1764. } else if (NewTypeInfo.getCC() == CC_Default) {
  1765. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  1766. RequiresAdjustment = true;
  1767. // Don't complain about mismatches when the default CC is
  1768. // effectively the same as the explict one.
  1769. } else if (OldTypeInfo.getCC() == CC_Default &&
  1770. isABIDefaultCC(*this, NewTypeInfo.getCC(), New)) {
  1771. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  1772. RequiresAdjustment = true;
  1773. } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
  1774. NewTypeInfo.getCC())) {
  1775. // Calling conventions really aren't compatible, so complain.
  1776. Diag(New->getLocation(), diag::err_cconv_change)
  1777. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  1778. << (OldTypeInfo.getCC() == CC_Default)
  1779. << (OldTypeInfo.getCC() == CC_Default ? "" :
  1780. FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
  1781. Diag(Old->getLocation(), diag::note_previous_declaration);
  1782. return true;
  1783. }
  1784. // FIXME: diagnose the other way around?
  1785. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  1786. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  1787. RequiresAdjustment = true;
  1788. }
  1789. // Merge regparm attribute.
  1790. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  1791. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  1792. if (NewTypeInfo.getHasRegParm()) {
  1793. Diag(New->getLocation(), diag::err_regparm_mismatch)
  1794. << NewType->getRegParmType()
  1795. << OldType->getRegParmType();
  1796. Diag(Old->getLocation(), diag::note_previous_declaration);
  1797. return true;
  1798. }
  1799. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  1800. RequiresAdjustment = true;
  1801. }
  1802. // Merge ns_returns_retained attribute.
  1803. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  1804. if (NewTypeInfo.getProducesResult()) {
  1805. Diag(New->getLocation(), diag::err_returns_retained_mismatch);
  1806. Diag(Old->getLocation(), diag::note_previous_declaration);
  1807. return true;
  1808. }
  1809. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  1810. RequiresAdjustment = true;
  1811. }
  1812. if (RequiresAdjustment) {
  1813. NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
  1814. New->setType(QualType(NewType, 0));
  1815. NewQType = Context.getCanonicalType(New->getType());
  1816. }
  1817. if (getLangOpts().CPlusPlus) {
  1818. // (C++98 13.1p2):
  1819. // Certain function declarations cannot be overloaded:
  1820. // -- Function declarations that differ only in the return type
  1821. // cannot be overloaded.
  1822. QualType OldReturnType = OldType->getResultType();
  1823. QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
  1824. QualType ResQT;
  1825. if (OldReturnType != NewReturnType) {
  1826. if (NewReturnType->isObjCObjectPointerType()
  1827. && OldReturnType->isObjCObjectPointerType())
  1828. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  1829. if (ResQT.isNull()) {
  1830. if (New->isCXXClassMember() && New->isOutOfLine())
  1831. Diag(New->getLocation(),
  1832. diag::err_member_def_does_not_match_ret_type) << New;
  1833. else
  1834. Diag(New->getLocation(), diag::err_ovl_diff_return_type);
  1835. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1836. return true;
  1837. }
  1838. else
  1839. NewQType = ResQT;
  1840. }
  1841. const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
  1842. CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
  1843. if (OldMethod && NewMethod) {
  1844. // Preserve triviality.
  1845. NewMethod->setTrivial(OldMethod->isTrivial());
  1846. // MSVC allows explicit template specialization at class scope:
  1847. // 2 CXMethodDecls referring to the same function will be injected.
  1848. // We don't want a redeclartion error.
  1849. bool IsClassScopeExplicitSpecialization =
  1850. OldMethod->isFunctionTemplateSpecialization() &&
  1851. NewMethod->isFunctionTemplateSpecialization();
  1852. bool isFriend = NewMethod->getFriendObjectKind();
  1853. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  1854. !IsClassScopeExplicitSpecialization) {
  1855. // -- Member function declarations with the same name and the
  1856. // same parameter types cannot be overloaded if any of them
  1857. // is a static member function declaration.
  1858. if (OldMethod->isStatic() || NewMethod->isStatic()) {
  1859. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  1860. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1861. return true;
  1862. }
  1863. // C++ [class.mem]p1:
  1864. // [...] A member shall not be declared twice in the
  1865. // member-specification, except that a nested class or member
  1866. // class template can be declared and then later defined.
  1867. if (ActiveTemplateInstantiations.empty()) {
  1868. unsigned NewDiag;
  1869. if (isa<CXXConstructorDecl>(OldMethod))
  1870. NewDiag = diag::err_constructor_redeclared;
  1871. else if (isa<CXXDestructorDecl>(NewMethod))
  1872. NewDiag = diag::err_destructor_redeclared;
  1873. else if (isa<CXXConversionDecl>(NewMethod))
  1874. NewDiag = diag::err_conv_function_redeclared;
  1875. else
  1876. NewDiag = diag::err_member_redeclared;
  1877. Diag(New->getLocation(), NewDiag);
  1878. } else {
  1879. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  1880. << New << New->getType();
  1881. }
  1882. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1883. // Complain if this is an explicit declaration of a special
  1884. // member that was initially declared implicitly.
  1885. //
  1886. // As an exception, it's okay to befriend such methods in order
  1887. // to permit the implicit constructor/destructor/operator calls.
  1888. } else if (OldMethod->isImplicit()) {
  1889. if (isFriend) {
  1890. NewMethod->setImplicit();
  1891. } else {
  1892. Diag(NewMethod->getLocation(),
  1893. diag::err_definition_of_implicitly_declared_member)
  1894. << New << getSpecialMember(OldMethod);
  1895. return true;
  1896. }
  1897. } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
  1898. Diag(NewMethod->getLocation(),
  1899. diag::err_definition_of_explicitly_defaulted_member)
  1900. << getSpecialMember(OldMethod);
  1901. return true;
  1902. }
  1903. }
  1904. // (C++98 8.3.5p3):
  1905. // All declarations for a function shall agree exactly in both the
  1906. // return type and the parameter-type-list.
  1907. // We also want to respect all the extended bits except noreturn.
  1908. // noreturn should now match unless the old type info didn't have it.
  1909. QualType OldQTypeForComparison = OldQType;
  1910. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  1911. assert(OldQType == QualType(OldType, 0));
  1912. const FunctionType *OldTypeForComparison
  1913. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  1914. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  1915. assert(OldQTypeForComparison.isCanonical());
  1916. }
  1917. if (OldQTypeForComparison == NewQType)
  1918. return MergeCompatibleFunctionDecls(New, Old, S);
  1919. // Fall through for conflicting redeclarations and redefinitions.
  1920. }
  1921. // C: Function types need to be compatible, not identical. This handles
  1922. // duplicate function decls like "void f(int); void f(enum X);" properly.
  1923. if (!getLangOpts().CPlusPlus &&
  1924. Context.typesAreCompatible(OldQType, NewQType)) {
  1925. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  1926. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  1927. const FunctionProtoType *OldProto = 0;
  1928. if (isa<FunctionNoProtoType>(NewFuncType) &&
  1929. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  1930. // The old declaration provided a function prototype, but the
  1931. // new declaration does not. Merge in the prototype.
  1932. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  1933. SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
  1934. OldProto->arg_type_end());
  1935. NewQType = Context.getFunctionType(NewFuncType->getResultType(),
  1936. ParamTypes.data(), ParamTypes.size(),
  1937. OldProto->getExtProtoInfo());
  1938. New->setType(NewQType);
  1939. New->setHasInheritedPrototype();
  1940. // Synthesize a parameter for each argument type.
  1941. SmallVector<ParmVarDecl*, 16> Params;
  1942. for (FunctionProtoType::arg_type_iterator
  1943. ParamType = OldProto->arg_type_begin(),
  1944. ParamEnd = OldProto->arg_type_end();
  1945. ParamType != ParamEnd; ++ParamType) {
  1946. ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
  1947. SourceLocation(),
  1948. SourceLocation(), 0,
  1949. *ParamType, /*TInfo=*/0,
  1950. SC_None, SC_None,
  1951. 0);
  1952. Param->setScopeInfo(0, Params.size());
  1953. Param->setImplicit();
  1954. Params.push_back(Param);
  1955. }
  1956. New->setParams(Params);
  1957. }
  1958. return MergeCompatibleFunctionDecls(New, Old, S);
  1959. }
  1960. // GNU C permits a K&R definition to follow a prototype declaration
  1961. // if the declared types of the parameters in the K&R definition
  1962. // match the types in the prototype declaration, even when the
  1963. // promoted types of the parameters from the K&R definition differ
  1964. // from the types in the prototype. GCC then keeps the types from
  1965. // the prototype.
  1966. //
  1967. // If a variadic prototype is followed by a non-variadic K&R definition,
  1968. // the K&R definition becomes variadic. This is sort of an edge case, but
  1969. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  1970. // C99 6.9.1p8.
  1971. if (!getLangOpts().CPlusPlus &&
  1972. Old->hasPrototype() && !New->hasPrototype() &&
  1973. New->getType()->getAs<FunctionProtoType>() &&
  1974. Old->getNumParams() == New->getNumParams()) {
  1975. SmallVector<QualType, 16> ArgTypes;
  1976. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  1977. const FunctionProtoType *OldProto
  1978. = Old->getType()->getAs<FunctionProtoType>();
  1979. const FunctionProtoType *NewProto
  1980. = New->getType()->getAs<FunctionProtoType>();
  1981. // Determine whether this is the GNU C extension.
  1982. QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
  1983. NewProto->getResultType());
  1984. bool LooseCompatible = !MergedReturn.isNull();
  1985. for (unsigned Idx = 0, End = Old->getNumParams();
  1986. LooseCompatible && Idx != End; ++Idx) {
  1987. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  1988. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  1989. if (Context.typesAreCompatible(OldParm->getType(),
  1990. NewProto->getArgType(Idx))) {
  1991. ArgTypes.push_back(NewParm->getType());
  1992. } else if (Context.typesAreCompatible(OldParm->getType(),
  1993. NewParm->getType(),
  1994. /*CompareUnqualified=*/true)) {
  1995. GNUCompatibleParamWarning Warn
  1996. = { OldParm, NewParm, NewProto->getArgType(Idx) };
  1997. Warnings.push_back(Warn);
  1998. ArgTypes.push_back(NewParm->getType());
  1999. } else
  2000. LooseCompatible = false;
  2001. }
  2002. if (LooseCompatible) {
  2003. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  2004. Diag(Warnings[Warn].NewParm->getLocation(),
  2005. diag::ext_param_promoted_not_compatible_with_prototype)
  2006. << Warnings[Warn].PromotedType
  2007. << Warnings[Warn].OldParm->getType();
  2008. if (Warnings[Warn].OldParm->getLocation().isValid())
  2009. Diag(Warnings[Warn].OldParm->getLocation(),
  2010. diag::note_previous_declaration);
  2011. }
  2012. New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
  2013. ArgTypes.size(),
  2014. OldProto->getExtProtoInfo()));
  2015. return MergeCompatibleFunctionDecls(New, Old, S);
  2016. }
  2017. // Fall through to diagnose conflicting types.
  2018. }
  2019. // A function that has already been declared has been redeclared or defined
  2020. // with a different type- show appropriate diagnostic
  2021. if (unsigned BuiltinID = Old->getBuiltinID()) {
  2022. // The user has declared a builtin function with an incompatible
  2023. // signature.
  2024. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  2025. // The function the user is redeclaring is a library-defined
  2026. // function like 'malloc' or 'printf'. Warn about the
  2027. // redeclaration, then pretend that we don't know about this
  2028. // library built-in.
  2029. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  2030. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  2031. << Old << Old->getType();
  2032. New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
  2033. Old->setInvalidDecl();
  2034. return false;
  2035. }
  2036. PrevDiag = diag::note_previous_builtin_declaration;
  2037. }
  2038. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  2039. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  2040. return true;
  2041. }
  2042. /// \brief Completes the merge of two function declarations that are
  2043. /// known to be compatible.
  2044. ///
  2045. /// This routine handles the merging of attributes and other
  2046. /// properties of function declarations form the old declaration to
  2047. /// the new declaration, once we know that New is in fact a
  2048. /// redeclaration of Old.
  2049. ///
  2050. /// \returns false
  2051. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  2052. Scope *S) {
  2053. // Merge the attributes
  2054. mergeDeclAttributes(New, Old);
  2055. // Merge the storage class.
  2056. if (Old->getStorageClass() != SC_Extern &&
  2057. Old->getStorageClass() != SC_None)
  2058. New->setStorageClass(Old->getStorageClass());
  2059. // Merge "pure" flag.
  2060. if (Old->isPure())
  2061. New->setPure();
  2062. // Merge attributes from the parameters. These can mismatch with K&R
  2063. // declarations.
  2064. if (New->getNumParams() == Old->getNumParams())
  2065. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
  2066. mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
  2067. Context);
  2068. if (getLangOpts().CPlusPlus)
  2069. return MergeCXXFunctionDecl(New, Old, S);
  2070. return false;
  2071. }
  2072. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  2073. ObjCMethodDecl *oldMethod) {
  2074. // Merge the attributes, including deprecated/unavailable
  2075. mergeDeclAttributes(newMethod, oldMethod, /* mergeDeprecation */true);
  2076. // Merge attributes from the parameters.
  2077. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  2078. oe = oldMethod->param_end();
  2079. for (ObjCMethodDecl::param_iterator
  2080. ni = newMethod->param_begin(), ne = newMethod->param_end();
  2081. ni != ne && oi != oe; ++ni, ++oi)
  2082. mergeParamDeclAttributes(*ni, *oi, Context);
  2083. CheckObjCMethodOverride(newMethod, oldMethod, true);
  2084. }
  2085. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  2086. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  2087. /// emitting diagnostics as appropriate.
  2088. ///
  2089. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  2090. /// to here in AddInitializerToDecl. We can't check them before the initializer
  2091. /// is attached.
  2092. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
  2093. if (New->isInvalidDecl() || Old->isInvalidDecl())
  2094. return;
  2095. QualType MergedT;
  2096. if (getLangOpts().CPlusPlus) {
  2097. AutoType *AT = New->getType()->getContainedAutoType();
  2098. if (AT && !AT->isDeduced()) {
  2099. // We don't know what the new type is until the initializer is attached.
  2100. return;
  2101. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  2102. // These could still be something that needs exception specs checked.
  2103. return MergeVarDeclExceptionSpecs(New, Old);
  2104. }
  2105. // C++ [basic.link]p10:
  2106. // [...] the types specified by all declarations referring to a given
  2107. // object or function shall be identical, except that declarations for an
  2108. // array object can specify array types that differ by the presence or
  2109. // absence of a major array bound (8.3.4).
  2110. else if (Old->getType()->isIncompleteArrayType() &&
  2111. New->getType()->isArrayType()) {
  2112. CanQual<ArrayType> OldArray
  2113. = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
  2114. CanQual<ArrayType> NewArray
  2115. = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
  2116. if (OldArray->getElementType() == NewArray->getElementType())
  2117. MergedT = New->getType();
  2118. } else if (Old->getType()->isArrayType() &&
  2119. New->getType()->isIncompleteArrayType()) {
  2120. CanQual<ArrayType> OldArray
  2121. = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
  2122. CanQual<ArrayType> NewArray
  2123. = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
  2124. if (OldArray->getElementType() == NewArray->getElementType())
  2125. MergedT = Old->getType();
  2126. } else if (New->getType()->isObjCObjectPointerType()
  2127. && Old->getType()->isObjCObjectPointerType()) {
  2128. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  2129. Old->getType());
  2130. }
  2131. } else {
  2132. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  2133. }
  2134. if (MergedT.isNull()) {
  2135. Diag(New->getLocation(), diag::err_redefinition_different_type)
  2136. << New->getDeclName() << New->getType() << Old->getType();
  2137. Diag(Old->getLocation(), diag::note_previous_definition);
  2138. return New->setInvalidDecl();
  2139. }
  2140. New->setType(MergedT);
  2141. }
  2142. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  2143. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  2144. /// situation, merging decls or emitting diagnostics as appropriate.
  2145. ///
  2146. /// Tentative definition rules (C99 6.9.2p2) are checked by
  2147. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  2148. /// definitions here, since the initializer hasn't been attached.
  2149. ///
  2150. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  2151. // If the new decl is already invalid, don't do any other checking.
  2152. if (New->isInvalidDecl())
  2153. return;
  2154. // Verify the old decl was also a variable.
  2155. VarDecl *Old = 0;
  2156. if (!Previous.isSingleResult() ||
  2157. !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
  2158. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2159. << New->getDeclName();
  2160. Diag(Previous.getRepresentativeDecl()->getLocation(),
  2161. diag::note_previous_definition);
  2162. return New->setInvalidDecl();
  2163. }
  2164. // C++ [class.mem]p1:
  2165. // A member shall not be declared twice in the member-specification [...]
  2166. //
  2167. // Here, we need only consider static data members.
  2168. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  2169. Diag(New->getLocation(), diag::err_duplicate_member)
  2170. << New->getIdentifier();
  2171. Diag(Old->getLocation(), diag::note_previous_declaration);
  2172. New->setInvalidDecl();
  2173. }
  2174. mergeDeclAttributes(New, Old);
  2175. // Warn if an already-declared variable is made a weak_import in a subsequent
  2176. // declaration
  2177. if (New->getAttr<WeakImportAttr>() &&
  2178. Old->getStorageClass() == SC_None &&
  2179. !Old->getAttr<WeakImportAttr>()) {
  2180. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  2181. Diag(Old->getLocation(), diag::note_previous_definition);
  2182. // Remove weak_import attribute on new declaration.
  2183. New->dropAttr<WeakImportAttr>();
  2184. }
  2185. // Merge the types.
  2186. MergeVarDeclTypes(New, Old);
  2187. if (New->isInvalidDecl())
  2188. return;
  2189. // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
  2190. if (New->getStorageClass() == SC_Static &&
  2191. (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
  2192. Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
  2193. Diag(Old->getLocation(), diag::note_previous_definition);
  2194. return New->setInvalidDecl();
  2195. }
  2196. // C99 6.2.2p4:
  2197. // For an identifier declared with the storage-class specifier
  2198. // extern in a scope in which a prior declaration of that
  2199. // identifier is visible,23) if the prior declaration specifies
  2200. // internal or external linkage, the linkage of the identifier at
  2201. // the later declaration is the same as the linkage specified at
  2202. // the prior declaration. If no prior declaration is visible, or
  2203. // if the prior declaration specifies no linkage, then the
  2204. // identifier has external linkage.
  2205. if (New->hasExternalStorage() && Old->hasLinkage())
  2206. /* Okay */;
  2207. else if (New->getStorageClass() != SC_Static &&
  2208. Old->getStorageClass() == SC_Static) {
  2209. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  2210. Diag(Old->getLocation(), diag::note_previous_definition);
  2211. return New->setInvalidDecl();
  2212. }
  2213. // Check if extern is followed by non-extern and vice-versa.
  2214. if (New->hasExternalStorage() &&
  2215. !Old->hasLinkage() && Old->isLocalVarDecl()) {
  2216. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  2217. Diag(Old->getLocation(), diag::note_previous_definition);
  2218. return New->setInvalidDecl();
  2219. }
  2220. if (Old->hasExternalStorage() &&
  2221. !New->hasLinkage() && New->isLocalVarDecl()) {
  2222. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  2223. Diag(Old->getLocation(), diag::note_previous_definition);
  2224. return New->setInvalidDecl();
  2225. }
  2226. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  2227. // FIXME: The test for external storage here seems wrong? We still
  2228. // need to check for mismatches.
  2229. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  2230. // Don't complain about out-of-line definitions of static members.
  2231. !(Old->getLexicalDeclContext()->isRecord() &&
  2232. !New->getLexicalDeclContext()->isRecord())) {
  2233. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  2234. Diag(Old->getLocation(), diag::note_previous_definition);
  2235. return New->setInvalidDecl();
  2236. }
  2237. if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
  2238. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  2239. Diag(Old->getLocation(), diag::note_previous_definition);
  2240. } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
  2241. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  2242. Diag(Old->getLocation(), diag::note_previous_definition);
  2243. }
  2244. // C++ doesn't have tentative definitions, so go right ahead and check here.
  2245. const VarDecl *Def;
  2246. if (getLangOpts().CPlusPlus &&
  2247. New->isThisDeclarationADefinition() == VarDecl::Definition &&
  2248. (Def = Old->getDefinition())) {
  2249. Diag(New->getLocation(), diag::err_redefinition)
  2250. << New->getDeclName();
  2251. Diag(Def->getLocation(), diag::note_previous_definition);
  2252. New->setInvalidDecl();
  2253. return;
  2254. }
  2255. // c99 6.2.2 P4.
  2256. // For an identifier declared with the storage-class specifier extern in a
  2257. // scope in which a prior declaration of that identifier is visible, if
  2258. // the prior declaration specifies internal or external linkage, the linkage
  2259. // of the identifier at the later declaration is the same as the linkage
  2260. // specified at the prior declaration.
  2261. // FIXME. revisit this code.
  2262. if (New->hasExternalStorage() &&
  2263. Old->getLinkage() == InternalLinkage &&
  2264. New->getDeclContext() == Old->getDeclContext())
  2265. New->setStorageClass(Old->getStorageClass());
  2266. // Keep a chain of previous declarations.
  2267. New->setPreviousDeclaration(Old);
  2268. // Inherit access appropriately.
  2269. New->setAccess(Old->getAccess());
  2270. }
  2271. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  2272. /// no declarator (e.g. "struct foo;") is parsed.
  2273. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  2274. DeclSpec &DS) {
  2275. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
  2276. }
  2277. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  2278. /// no declarator (e.g. "struct foo;") is parsed. It also accopts template
  2279. /// parameters to cope with template friend declarations.
  2280. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  2281. DeclSpec &DS,
  2282. MultiTemplateParamsArg TemplateParams) {
  2283. Decl *TagD = 0;
  2284. TagDecl *Tag = 0;
  2285. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  2286. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  2287. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  2288. DS.getTypeSpecType() == DeclSpec::TST_union ||
  2289. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  2290. TagD = DS.getRepAsDecl();
  2291. if (!TagD) // We probably had an error
  2292. return 0;
  2293. // Note that the above type specs guarantee that the
  2294. // type rep is a Decl, whereas in many of the others
  2295. // it's a Type.
  2296. if (isa<TagDecl>(TagD))
  2297. Tag = cast<TagDecl>(TagD);
  2298. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  2299. Tag = CTD->getTemplatedDecl();
  2300. }
  2301. if (Tag) {
  2302. Tag->setFreeStanding();
  2303. if (Tag->isInvalidDecl())
  2304. return Tag;
  2305. }
  2306. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  2307. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  2308. // or incomplete types shall not be restrict-qualified."
  2309. if (TypeQuals & DeclSpec::TQ_restrict)
  2310. Diag(DS.getRestrictSpecLoc(),
  2311. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  2312. << DS.getSourceRange();
  2313. }
  2314. if (DS.isConstexprSpecified()) {
  2315. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  2316. // and definitions of functions and variables.
  2317. if (Tag)
  2318. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  2319. << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
  2320. DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
  2321. DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
  2322. DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
  2323. else
  2324. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  2325. // Don't emit warnings after this error.
  2326. return TagD;
  2327. }
  2328. if (DS.isFriendSpecified()) {
  2329. // If we're dealing with a decl but not a TagDecl, assume that
  2330. // whatever routines created it handled the friendship aspect.
  2331. if (TagD && !Tag)
  2332. return 0;
  2333. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  2334. }
  2335. // Track whether we warned about the fact that there aren't any
  2336. // declarators.
  2337. bool emittedWarning = false;
  2338. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  2339. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  2340. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  2341. if (getLangOpts().CPlusPlus ||
  2342. Record->getDeclContext()->isRecord())
  2343. return BuildAnonymousStructOrUnion(S, DS, AS, Record);
  2344. Diag(DS.getLocStart(), diag::ext_no_declarators)
  2345. << DS.getSourceRange();
  2346. emittedWarning = true;
  2347. }
  2348. }
  2349. // Check for Microsoft C extension: anonymous struct.
  2350. if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
  2351. CurContext->isRecord() &&
  2352. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  2353. // Handle 2 kinds of anonymous struct:
  2354. // struct STRUCT;
  2355. // and
  2356. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  2357. RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
  2358. if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
  2359. (DS.getTypeSpecType() == DeclSpec::TST_typename &&
  2360. DS.getRepAsType().get()->isStructureType())) {
  2361. Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
  2362. << DS.getSourceRange();
  2363. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  2364. }
  2365. }
  2366. if (getLangOpts().CPlusPlus &&
  2367. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  2368. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  2369. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  2370. !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
  2371. Diag(Enum->getLocation(), diag::ext_no_declarators)
  2372. << DS.getSourceRange();
  2373. emittedWarning = true;
  2374. }
  2375. // Skip all the checks below if we have a type error.
  2376. if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
  2377. if (!DS.isMissingDeclaratorOk()) {
  2378. // Warn about typedefs of enums without names, since this is an
  2379. // extension in both Microsoft and GNU.
  2380. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
  2381. Tag && isa<EnumDecl>(Tag)) {
  2382. Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
  2383. << DS.getSourceRange();
  2384. return Tag;
  2385. }
  2386. Diag(DS.getLocStart(), diag::ext_no_declarators)
  2387. << DS.getSourceRange();
  2388. emittedWarning = true;
  2389. }
  2390. // We're going to complain about a bunch of spurious specifiers;
  2391. // only do this if we're declaring a tag, because otherwise we
  2392. // should be getting diag::ext_no_declarators.
  2393. if (emittedWarning || (TagD && TagD->isInvalidDecl()))
  2394. return TagD;
  2395. // Note that a linkage-specification sets a storage class, but
  2396. // 'extern "C" struct foo;' is actually valid and not theoretically
  2397. // useless.
  2398. if (DeclSpec::SCS scs = DS.getStorageClassSpec())
  2399. if (!DS.isExternInLinkageSpec())
  2400. Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
  2401. << DeclSpec::getSpecifierName(scs);
  2402. if (DS.isThreadSpecified())
  2403. Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
  2404. if (DS.getTypeQualifiers()) {
  2405. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  2406. Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
  2407. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  2408. Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
  2409. // Restrict is covered above.
  2410. }
  2411. if (DS.isInlineSpecified())
  2412. Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
  2413. if (DS.isVirtualSpecified())
  2414. Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
  2415. if (DS.isExplicitSpecified())
  2416. Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
  2417. if (DS.isModulePrivateSpecified() &&
  2418. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  2419. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  2420. << Tag->getTagKind()
  2421. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  2422. // Warn about ignored type attributes, for example:
  2423. // __attribute__((aligned)) struct A;
  2424. // Attributes should be placed after tag to apply to type declaration.
  2425. if (!DS.getAttributes().empty()) {
  2426. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  2427. if (TypeSpecType == DeclSpec::TST_class ||
  2428. TypeSpecType == DeclSpec::TST_struct ||
  2429. TypeSpecType == DeclSpec::TST_interface ||
  2430. TypeSpecType == DeclSpec::TST_union ||
  2431. TypeSpecType == DeclSpec::TST_enum) {
  2432. AttributeList* attrs = DS.getAttributes().getList();
  2433. while (attrs) {
  2434. Diag(attrs->getScopeLoc(),
  2435. diag::warn_declspec_attribute_ignored)
  2436. << attrs->getName()
  2437. << (TypeSpecType == DeclSpec::TST_class ? 0 :
  2438. TypeSpecType == DeclSpec::TST_struct ? 1 :
  2439. TypeSpecType == DeclSpec::TST_union ? 2 :
  2440. TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
  2441. attrs = attrs->getNext();
  2442. }
  2443. }
  2444. }
  2445. ActOnDocumentableDecl(TagD);
  2446. return TagD;
  2447. }
  2448. /// We are trying to inject an anonymous member into the given scope;
  2449. /// check if there's an existing declaration that can't be overloaded.
  2450. ///
  2451. /// \return true if this is a forbidden redeclaration
  2452. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  2453. Scope *S,
  2454. DeclContext *Owner,
  2455. DeclarationName Name,
  2456. SourceLocation NameLoc,
  2457. unsigned diagnostic) {
  2458. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  2459. Sema::ForRedeclaration);
  2460. if (!SemaRef.LookupName(R, S)) return false;
  2461. if (R.getAsSingle<TagDecl>())
  2462. return false;
  2463. // Pick a representative declaration.
  2464. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  2465. assert(PrevDecl && "Expected a non-null Decl");
  2466. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  2467. return false;
  2468. SemaRef.Diag(NameLoc, diagnostic) << Name;
  2469. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  2470. return true;
  2471. }
  2472. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  2473. /// anonymous struct or union AnonRecord into the owning context Owner
  2474. /// and scope S. This routine will be invoked just after we realize
  2475. /// that an unnamed union or struct is actually an anonymous union or
  2476. /// struct, e.g.,
  2477. ///
  2478. /// @code
  2479. /// union {
  2480. /// int i;
  2481. /// float f;
  2482. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  2483. /// // f into the surrounding scope.x
  2484. /// @endcode
  2485. ///
  2486. /// This routine is recursive, injecting the names of nested anonymous
  2487. /// structs/unions into the owning context and scope as well.
  2488. static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
  2489. DeclContext *Owner,
  2490. RecordDecl *AnonRecord,
  2491. AccessSpecifier AS,
  2492. SmallVector<NamedDecl*, 2> &Chaining,
  2493. bool MSAnonStruct) {
  2494. unsigned diagKind
  2495. = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
  2496. : diag::err_anonymous_struct_member_redecl;
  2497. bool Invalid = false;
  2498. // Look every FieldDecl and IndirectFieldDecl with a name.
  2499. for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
  2500. DEnd = AnonRecord->decls_end();
  2501. D != DEnd; ++D) {
  2502. if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
  2503. cast<NamedDecl>(*D)->getDeclName()) {
  2504. ValueDecl *VD = cast<ValueDecl>(*D);
  2505. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  2506. VD->getLocation(), diagKind)) {
  2507. // C++ [class.union]p2:
  2508. // The names of the members of an anonymous union shall be
  2509. // distinct from the names of any other entity in the
  2510. // scope in which the anonymous union is declared.
  2511. Invalid = true;
  2512. } else {
  2513. // C++ [class.union]p2:
  2514. // For the purpose of name lookup, after the anonymous union
  2515. // definition, the members of the anonymous union are
  2516. // considered to have been defined in the scope in which the
  2517. // anonymous union is declared.
  2518. unsigned OldChainingSize = Chaining.size();
  2519. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  2520. for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
  2521. PE = IF->chain_end(); PI != PE; ++PI)
  2522. Chaining.push_back(*PI);
  2523. else
  2524. Chaining.push_back(VD);
  2525. assert(Chaining.size() >= 2);
  2526. NamedDecl **NamedChain =
  2527. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  2528. for (unsigned i = 0; i < Chaining.size(); i++)
  2529. NamedChain[i] = Chaining[i];
  2530. IndirectFieldDecl* IndirectField =
  2531. IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
  2532. VD->getIdentifier(), VD->getType(),
  2533. NamedChain, Chaining.size());
  2534. IndirectField->setAccess(AS);
  2535. IndirectField->setImplicit();
  2536. SemaRef.PushOnScopeChains(IndirectField, S);
  2537. // That includes picking up the appropriate access specifier.
  2538. if (AS != AS_none) IndirectField->setAccess(AS);
  2539. Chaining.resize(OldChainingSize);
  2540. }
  2541. }
  2542. }
  2543. return Invalid;
  2544. }
  2545. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  2546. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  2547. /// illegal input values are mapped to SC_None.
  2548. static StorageClass
  2549. StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
  2550. switch (StorageClassSpec) {
  2551. case DeclSpec::SCS_unspecified: return SC_None;
  2552. case DeclSpec::SCS_extern: return SC_Extern;
  2553. case DeclSpec::SCS_static: return SC_Static;
  2554. case DeclSpec::SCS_auto: return SC_Auto;
  2555. case DeclSpec::SCS_register: return SC_Register;
  2556. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  2557. // Illegal SCSs map to None: error reporting is up to the caller.
  2558. case DeclSpec::SCS_mutable: // Fall through.
  2559. case DeclSpec::SCS_typedef: return SC_None;
  2560. }
  2561. llvm_unreachable("unknown storage class specifier");
  2562. }
  2563. /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
  2564. /// a StorageClass. Any error reporting is up to the caller:
  2565. /// illegal input values are mapped to SC_None.
  2566. static StorageClass
  2567. StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
  2568. switch (StorageClassSpec) {
  2569. case DeclSpec::SCS_unspecified: return SC_None;
  2570. case DeclSpec::SCS_extern: return SC_Extern;
  2571. case DeclSpec::SCS_static: return SC_Static;
  2572. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  2573. // Illegal SCSs map to None: error reporting is up to the caller.
  2574. case DeclSpec::SCS_auto: // Fall through.
  2575. case DeclSpec::SCS_mutable: // Fall through.
  2576. case DeclSpec::SCS_register: // Fall through.
  2577. case DeclSpec::SCS_typedef: return SC_None;
  2578. }
  2579. llvm_unreachable("unknown storage class specifier");
  2580. }
  2581. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  2582. /// anonymous structure or union. Anonymous unions are a C++ feature
  2583. /// (C++ [class.union]) and a C11 feature; anonymous structures
  2584. /// are a C11 feature and GNU C++ extension.
  2585. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  2586. AccessSpecifier AS,
  2587. RecordDecl *Record) {
  2588. DeclContext *Owner = Record->getDeclContext();
  2589. // Diagnose whether this anonymous struct/union is an extension.
  2590. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  2591. Diag(Record->getLocation(), diag::ext_anonymous_union);
  2592. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  2593. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  2594. else if (!Record->isUnion() && !getLangOpts().C11)
  2595. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  2596. // C and C++ require different kinds of checks for anonymous
  2597. // structs/unions.
  2598. bool Invalid = false;
  2599. if (getLangOpts().CPlusPlus) {
  2600. const char* PrevSpec = 0;
  2601. unsigned DiagID;
  2602. if (Record->isUnion()) {
  2603. // C++ [class.union]p6:
  2604. // Anonymous unions declared in a named namespace or in the
  2605. // global namespace shall be declared static.
  2606. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  2607. (isa<TranslationUnitDecl>(Owner) ||
  2608. (isa<NamespaceDecl>(Owner) &&
  2609. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  2610. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  2611. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  2612. // Recover by adding 'static'.
  2613. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  2614. PrevSpec, DiagID);
  2615. }
  2616. // C++ [class.union]p6:
  2617. // A storage class is not allowed in a declaration of an
  2618. // anonymous union in a class scope.
  2619. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  2620. isa<RecordDecl>(Owner)) {
  2621. Diag(DS.getStorageClassSpecLoc(),
  2622. diag::err_anonymous_union_with_storage_spec)
  2623. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  2624. // Recover by removing the storage specifier.
  2625. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  2626. SourceLocation(),
  2627. PrevSpec, DiagID);
  2628. }
  2629. }
  2630. // Ignore const/volatile/restrict qualifiers.
  2631. if (DS.getTypeQualifiers()) {
  2632. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  2633. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  2634. << Record->isUnion() << 0
  2635. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  2636. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  2637. Diag(DS.getVolatileSpecLoc(),
  2638. diag::ext_anonymous_struct_union_qualified)
  2639. << Record->isUnion() << 1
  2640. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  2641. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  2642. Diag(DS.getRestrictSpecLoc(),
  2643. diag::ext_anonymous_struct_union_qualified)
  2644. << Record->isUnion() << 2
  2645. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  2646. DS.ClearTypeQualifiers();
  2647. }
  2648. // C++ [class.union]p2:
  2649. // The member-specification of an anonymous union shall only
  2650. // define non-static data members. [Note: nested types and
  2651. // functions cannot be declared within an anonymous union. ]
  2652. for (DeclContext::decl_iterator Mem = Record->decls_begin(),
  2653. MemEnd = Record->decls_end();
  2654. Mem != MemEnd; ++Mem) {
  2655. if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
  2656. // C++ [class.union]p3:
  2657. // An anonymous union shall not have private or protected
  2658. // members (clause 11).
  2659. assert(FD->getAccess() != AS_none);
  2660. if (FD->getAccess() != AS_public) {
  2661. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  2662. << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
  2663. Invalid = true;
  2664. }
  2665. // C++ [class.union]p1
  2666. // An object of a class with a non-trivial constructor, a non-trivial
  2667. // copy constructor, a non-trivial destructor, or a non-trivial copy
  2668. // assignment operator cannot be a member of a union, nor can an
  2669. // array of such objects.
  2670. if (CheckNontrivialField(FD))
  2671. Invalid = true;
  2672. } else if ((*Mem)->isImplicit()) {
  2673. // Any implicit members are fine.
  2674. } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
  2675. // This is a type that showed up in an
  2676. // elaborated-type-specifier inside the anonymous struct or
  2677. // union, but which actually declares a type outside of the
  2678. // anonymous struct or union. It's okay.
  2679. } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
  2680. if (!MemRecord->isAnonymousStructOrUnion() &&
  2681. MemRecord->getDeclName()) {
  2682. // Visual C++ allows type definition in anonymous struct or union.
  2683. if (getLangOpts().MicrosoftExt)
  2684. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  2685. << (int)Record->isUnion();
  2686. else {
  2687. // This is a nested type declaration.
  2688. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  2689. << (int)Record->isUnion();
  2690. Invalid = true;
  2691. }
  2692. }
  2693. } else if (isa<AccessSpecDecl>(*Mem)) {
  2694. // Any access specifier is fine.
  2695. } else {
  2696. // We have something that isn't a non-static data
  2697. // member. Complain about it.
  2698. unsigned DK = diag::err_anonymous_record_bad_member;
  2699. if (isa<TypeDecl>(*Mem))
  2700. DK = diag::err_anonymous_record_with_type;
  2701. else if (isa<FunctionDecl>(*Mem))
  2702. DK = diag::err_anonymous_record_with_function;
  2703. else if (isa<VarDecl>(*Mem))
  2704. DK = diag::err_anonymous_record_with_static;
  2705. // Visual C++ allows type definition in anonymous struct or union.
  2706. if (getLangOpts().MicrosoftExt &&
  2707. DK == diag::err_anonymous_record_with_type)
  2708. Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
  2709. << (int)Record->isUnion();
  2710. else {
  2711. Diag((*Mem)->getLocation(), DK)
  2712. << (int)Record->isUnion();
  2713. Invalid = true;
  2714. }
  2715. }
  2716. }
  2717. }
  2718. if (!Record->isUnion() && !Owner->isRecord()) {
  2719. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  2720. << (int)getLangOpts().CPlusPlus;
  2721. Invalid = true;
  2722. }
  2723. // Mock up a declarator.
  2724. Declarator Dc(DS, Declarator::MemberContext);
  2725. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  2726. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  2727. // Create a declaration for this anonymous struct/union.
  2728. NamedDecl *Anon = 0;
  2729. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  2730. Anon = FieldDecl::Create(Context, OwningClass,
  2731. DS.getLocStart(),
  2732. Record->getLocation(),
  2733. /*IdentifierInfo=*/0,
  2734. Context.getTypeDeclType(Record),
  2735. TInfo,
  2736. /*BitWidth=*/0, /*Mutable=*/false,
  2737. /*InitStyle=*/ICIS_NoInit);
  2738. Anon->setAccess(AS);
  2739. if (getLangOpts().CPlusPlus)
  2740. FieldCollector->Add(cast<FieldDecl>(Anon));
  2741. } else {
  2742. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  2743. assert(SCSpec != DeclSpec::SCS_typedef &&
  2744. "Parser allowed 'typedef' as storage class VarDecl.");
  2745. VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
  2746. if (SCSpec == DeclSpec::SCS_mutable) {
  2747. // mutable can only appear on non-static class members, so it's always
  2748. // an error here
  2749. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  2750. Invalid = true;
  2751. SC = SC_None;
  2752. }
  2753. SCSpec = DS.getStorageClassSpecAsWritten();
  2754. VarDecl::StorageClass SCAsWritten
  2755. = StorageClassSpecToVarDeclStorageClass(SCSpec);
  2756. Anon = VarDecl::Create(Context, Owner,
  2757. DS.getLocStart(),
  2758. Record->getLocation(), /*IdentifierInfo=*/0,
  2759. Context.getTypeDeclType(Record),
  2760. TInfo, SC, SCAsWritten);
  2761. // Default-initialize the implicit variable. This initialization will be
  2762. // trivial in almost all cases, except if a union member has an in-class
  2763. // initializer:
  2764. // union { int n = 0; };
  2765. ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
  2766. }
  2767. Anon->setImplicit();
  2768. // Add the anonymous struct/union object to the current
  2769. // context. We'll be referencing this object when we refer to one of
  2770. // its members.
  2771. Owner->addDecl(Anon);
  2772. // Inject the members of the anonymous struct/union into the owning
  2773. // context and into the identifier resolver chain for name lookup
  2774. // purposes.
  2775. SmallVector<NamedDecl*, 2> Chain;
  2776. Chain.push_back(Anon);
  2777. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
  2778. Chain, false))
  2779. Invalid = true;
  2780. // Mark this as an anonymous struct/union type. Note that we do not
  2781. // do this until after we have already checked and injected the
  2782. // members of this anonymous struct/union type, because otherwise
  2783. // the members could be injected twice: once by DeclContext when it
  2784. // builds its lookup table, and once by
  2785. // InjectAnonymousStructOrUnionMembers.
  2786. Record->setAnonymousStructOrUnion(true);
  2787. if (Invalid)
  2788. Anon->setInvalidDecl();
  2789. return Anon;
  2790. }
  2791. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  2792. /// Microsoft C anonymous structure.
  2793. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  2794. /// Example:
  2795. ///
  2796. /// struct A { int a; };
  2797. /// struct B { struct A; int b; };
  2798. ///
  2799. /// void foo() {
  2800. /// B var;
  2801. /// var.a = 3;
  2802. /// }
  2803. ///
  2804. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  2805. RecordDecl *Record) {
  2806. // If there is no Record, get the record via the typedef.
  2807. if (!Record)
  2808. Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
  2809. // Mock up a declarator.
  2810. Declarator Dc(DS, Declarator::TypeNameContext);
  2811. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  2812. assert(TInfo && "couldn't build declarator info for anonymous struct");
  2813. // Create a declaration for this anonymous struct.
  2814. NamedDecl* Anon = FieldDecl::Create(Context,
  2815. cast<RecordDecl>(CurContext),
  2816. DS.getLocStart(),
  2817. DS.getLocStart(),
  2818. /*IdentifierInfo=*/0,
  2819. Context.getTypeDeclType(Record),
  2820. TInfo,
  2821. /*BitWidth=*/0, /*Mutable=*/false,
  2822. /*InitStyle=*/ICIS_NoInit);
  2823. Anon->setImplicit();
  2824. // Add the anonymous struct object to the current context.
  2825. CurContext->addDecl(Anon);
  2826. // Inject the members of the anonymous struct into the current
  2827. // context and into the identifier resolver chain for name lookup
  2828. // purposes.
  2829. SmallVector<NamedDecl*, 2> Chain;
  2830. Chain.push_back(Anon);
  2831. RecordDecl *RecordDef = Record->getDefinition();
  2832. if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
  2833. RecordDef, AS_none,
  2834. Chain, true))
  2835. Anon->setInvalidDecl();
  2836. return Anon;
  2837. }
  2838. /// GetNameForDeclarator - Determine the full declaration name for the
  2839. /// given Declarator.
  2840. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  2841. return GetNameFromUnqualifiedId(D.getName());
  2842. }
  2843. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  2844. DeclarationNameInfo
  2845. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  2846. DeclarationNameInfo NameInfo;
  2847. NameInfo.setLoc(Name.StartLocation);
  2848. switch (Name.getKind()) {
  2849. case UnqualifiedId::IK_ImplicitSelfParam:
  2850. case UnqualifiedId::IK_Identifier:
  2851. NameInfo.setName(Name.Identifier);
  2852. NameInfo.setLoc(Name.StartLocation);
  2853. return NameInfo;
  2854. case UnqualifiedId::IK_OperatorFunctionId:
  2855. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  2856. Name.OperatorFunctionId.Operator));
  2857. NameInfo.setLoc(Name.StartLocation);
  2858. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  2859. = Name.OperatorFunctionId.SymbolLocations[0];
  2860. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  2861. = Name.EndLocation.getRawEncoding();
  2862. return NameInfo;
  2863. case UnqualifiedId::IK_LiteralOperatorId:
  2864. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  2865. Name.Identifier));
  2866. NameInfo.setLoc(Name.StartLocation);
  2867. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  2868. return NameInfo;
  2869. case UnqualifiedId::IK_ConversionFunctionId: {
  2870. TypeSourceInfo *TInfo;
  2871. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  2872. if (Ty.isNull())
  2873. return DeclarationNameInfo();
  2874. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  2875. Context.getCanonicalType(Ty)));
  2876. NameInfo.setLoc(Name.StartLocation);
  2877. NameInfo.setNamedTypeInfo(TInfo);
  2878. return NameInfo;
  2879. }
  2880. case UnqualifiedId::IK_ConstructorName: {
  2881. TypeSourceInfo *TInfo;
  2882. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  2883. if (Ty.isNull())
  2884. return DeclarationNameInfo();
  2885. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  2886. Context.getCanonicalType(Ty)));
  2887. NameInfo.setLoc(Name.StartLocation);
  2888. NameInfo.setNamedTypeInfo(TInfo);
  2889. return NameInfo;
  2890. }
  2891. case UnqualifiedId::IK_ConstructorTemplateId: {
  2892. // In well-formed code, we can only have a constructor
  2893. // template-id that refers to the current context, so go there
  2894. // to find the actual type being constructed.
  2895. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  2896. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  2897. return DeclarationNameInfo();
  2898. // Determine the type of the class being constructed.
  2899. QualType CurClassType = Context.getTypeDeclType(CurClass);
  2900. // FIXME: Check two things: that the template-id names the same type as
  2901. // CurClassType, and that the template-id does not occur when the name
  2902. // was qualified.
  2903. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  2904. Context.getCanonicalType(CurClassType)));
  2905. NameInfo.setLoc(Name.StartLocation);
  2906. // FIXME: should we retrieve TypeSourceInfo?
  2907. NameInfo.setNamedTypeInfo(0);
  2908. return NameInfo;
  2909. }
  2910. case UnqualifiedId::IK_DestructorName: {
  2911. TypeSourceInfo *TInfo;
  2912. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  2913. if (Ty.isNull())
  2914. return DeclarationNameInfo();
  2915. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  2916. Context.getCanonicalType(Ty)));
  2917. NameInfo.setLoc(Name.StartLocation);
  2918. NameInfo.setNamedTypeInfo(TInfo);
  2919. return NameInfo;
  2920. }
  2921. case UnqualifiedId::IK_TemplateId: {
  2922. TemplateName TName = Name.TemplateId->Template.get();
  2923. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  2924. return Context.getNameForTemplate(TName, TNameLoc);
  2925. }
  2926. } // switch (Name.getKind())
  2927. llvm_unreachable("Unknown name kind");
  2928. }
  2929. static QualType getCoreType(QualType Ty) {
  2930. do {
  2931. if (Ty->isPointerType() || Ty->isReferenceType())
  2932. Ty = Ty->getPointeeType();
  2933. else if (Ty->isArrayType())
  2934. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  2935. else
  2936. return Ty.withoutLocalFastQualifiers();
  2937. } while (true);
  2938. }
  2939. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  2940. /// and Definition have "nearly" matching parameters. This heuristic is
  2941. /// used to improve diagnostics in the case where an out-of-line function
  2942. /// definition doesn't match any declaration within the class or namespace.
  2943. /// Also sets Params to the list of indices to the parameters that differ
  2944. /// between the declaration and the definition. If hasSimilarParameters
  2945. /// returns true and Params is empty, then all of the parameters match.
  2946. static bool hasSimilarParameters(ASTContext &Context,
  2947. FunctionDecl *Declaration,
  2948. FunctionDecl *Definition,
  2949. llvm::SmallVectorImpl<unsigned> &Params) {
  2950. Params.clear();
  2951. if (Declaration->param_size() != Definition->param_size())
  2952. return false;
  2953. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  2954. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  2955. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  2956. // The parameter types are identical
  2957. if (Context.hasSameType(DefParamTy, DeclParamTy))
  2958. continue;
  2959. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  2960. QualType DefParamBaseTy = getCoreType(DefParamTy);
  2961. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  2962. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  2963. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  2964. (DeclTyName && DeclTyName == DefTyName))
  2965. Params.push_back(Idx);
  2966. else // The two parameters aren't even close
  2967. return false;
  2968. }
  2969. return true;
  2970. }
  2971. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  2972. /// declarator needs to be rebuilt in the current instantiation.
  2973. /// Any bits of declarator which appear before the name are valid for
  2974. /// consideration here. That's specifically the type in the decl spec
  2975. /// and the base type in any member-pointer chunks.
  2976. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  2977. DeclarationName Name) {
  2978. // The types we specifically need to rebuild are:
  2979. // - typenames, typeofs, and decltypes
  2980. // - types which will become injected class names
  2981. // Of course, we also need to rebuild any type referencing such a
  2982. // type. It's safest to just say "dependent", but we call out a
  2983. // few cases here.
  2984. DeclSpec &DS = D.getMutableDeclSpec();
  2985. switch (DS.getTypeSpecType()) {
  2986. case DeclSpec::TST_typename:
  2987. case DeclSpec::TST_typeofType:
  2988. case DeclSpec::TST_decltype:
  2989. case DeclSpec::TST_underlyingType:
  2990. case DeclSpec::TST_atomic: {
  2991. // Grab the type from the parser.
  2992. TypeSourceInfo *TSI = 0;
  2993. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  2994. if (T.isNull() || !T->isDependentType()) break;
  2995. // Make sure there's a type source info. This isn't really much
  2996. // of a waste; most dependent types should have type source info
  2997. // attached already.
  2998. if (!TSI)
  2999. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  3000. // Rebuild the type in the current instantiation.
  3001. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  3002. if (!TSI) return true;
  3003. // Store the new type back in the decl spec.
  3004. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  3005. DS.UpdateTypeRep(LocType);
  3006. break;
  3007. }
  3008. case DeclSpec::TST_typeofExpr: {
  3009. Expr *E = DS.getRepAsExpr();
  3010. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  3011. if (Result.isInvalid()) return true;
  3012. DS.UpdateExprRep(Result.get());
  3013. break;
  3014. }
  3015. default:
  3016. // Nothing to do for these decl specs.
  3017. break;
  3018. }
  3019. // It doesn't matter what order we do this in.
  3020. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  3021. DeclaratorChunk &Chunk = D.getTypeObject(I);
  3022. // The only type information in the declarator which can come
  3023. // before the declaration name is the base type of a member
  3024. // pointer.
  3025. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  3026. continue;
  3027. // Rebuild the scope specifier in-place.
  3028. CXXScopeSpec &SS = Chunk.Mem.Scope();
  3029. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  3030. return true;
  3031. }
  3032. return false;
  3033. }
  3034. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  3035. D.setFunctionDefinitionKind(FDK_Declaration);
  3036. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  3037. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  3038. Dcl && Dcl->getDeclContext()->isFileContext())
  3039. Dcl->setTopLevelDeclInObjCContainer();
  3040. return Dcl;
  3041. }
  3042. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  3043. /// If T is the name of a class, then each of the following shall have a
  3044. /// name different from T:
  3045. /// - every static data member of class T;
  3046. /// - every member function of class T
  3047. /// - every member of class T that is itself a type;
  3048. /// \returns true if the declaration name violates these rules.
  3049. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  3050. DeclarationNameInfo NameInfo) {
  3051. DeclarationName Name = NameInfo.getName();
  3052. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  3053. if (Record->getIdentifier() && Record->getDeclName() == Name) {
  3054. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  3055. return true;
  3056. }
  3057. return false;
  3058. }
  3059. /// \brief Diagnose a declaration whose declarator-id has the given
  3060. /// nested-name-specifier.
  3061. ///
  3062. /// \param SS The nested-name-specifier of the declarator-id.
  3063. ///
  3064. /// \param DC The declaration context to which the nested-name-specifier
  3065. /// resolves.
  3066. ///
  3067. /// \param Name The name of the entity being declared.
  3068. ///
  3069. /// \param Loc The location of the name of the entity being declared.
  3070. ///
  3071. /// \returns true if we cannot safely recover from this error, false otherwise.
  3072. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  3073. DeclarationName Name,
  3074. SourceLocation Loc) {
  3075. DeclContext *Cur = CurContext;
  3076. while (isa<LinkageSpecDecl>(Cur))
  3077. Cur = Cur->getParent();
  3078. // C++ [dcl.meaning]p1:
  3079. // A declarator-id shall not be qualified except for the definition
  3080. // of a member function (9.3) or static data member (9.4) outside of
  3081. // its class, the definition or explicit instantiation of a function
  3082. // or variable member of a namespace outside of its namespace, or the
  3083. // definition of an explicit specialization outside of its namespace,
  3084. // or the declaration of a friend function that is a member of
  3085. // another class or namespace (11.3). [...]
  3086. // The user provided a superfluous scope specifier that refers back to the
  3087. // class or namespaces in which the entity is already declared.
  3088. //
  3089. // class X {
  3090. // void X::f();
  3091. // };
  3092. if (Cur->Equals(DC)) {
  3093. Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
  3094. : diag::err_member_extra_qualification)
  3095. << Name << FixItHint::CreateRemoval(SS.getRange());
  3096. SS.clear();
  3097. return false;
  3098. }
  3099. // Check whether the qualifying scope encloses the scope of the original
  3100. // declaration.
  3101. if (!Cur->Encloses(DC)) {
  3102. if (Cur->isRecord())
  3103. Diag(Loc, diag::err_member_qualification)
  3104. << Name << SS.getRange();
  3105. else if (isa<TranslationUnitDecl>(DC))
  3106. Diag(Loc, diag::err_invalid_declarator_global_scope)
  3107. << Name << SS.getRange();
  3108. else if (isa<FunctionDecl>(Cur))
  3109. Diag(Loc, diag::err_invalid_declarator_in_function)
  3110. << Name << SS.getRange();
  3111. else
  3112. Diag(Loc, diag::err_invalid_declarator_scope)
  3113. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  3114. return true;
  3115. }
  3116. if (Cur->isRecord()) {
  3117. // Cannot qualify members within a class.
  3118. Diag(Loc, diag::err_member_qualification)
  3119. << Name << SS.getRange();
  3120. SS.clear();
  3121. // C++ constructors and destructors with incorrect scopes can break
  3122. // our AST invariants by having the wrong underlying types. If
  3123. // that's the case, then drop this declaration entirely.
  3124. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  3125. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  3126. !Context.hasSameType(Name.getCXXNameType(),
  3127. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  3128. return true;
  3129. return false;
  3130. }
  3131. // C++11 [dcl.meaning]p1:
  3132. // [...] "The nested-name-specifier of the qualified declarator-id shall
  3133. // not begin with a decltype-specifer"
  3134. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  3135. while (SpecLoc.getPrefix())
  3136. SpecLoc = SpecLoc.getPrefix();
  3137. if (dyn_cast_or_null<DecltypeType>(
  3138. SpecLoc.getNestedNameSpecifier()->getAsType()))
  3139. Diag(Loc, diag::err_decltype_in_declarator)
  3140. << SpecLoc.getTypeLoc().getSourceRange();
  3141. return false;
  3142. }
  3143. Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  3144. MultiTemplateParamsArg TemplateParamLists) {
  3145. // TODO: consider using NameInfo for diagnostic.
  3146. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  3147. DeclarationName Name = NameInfo.getName();
  3148. // All of these full declarators require an identifier. If it doesn't have
  3149. // one, the ParsedFreeStandingDeclSpec action should be used.
  3150. if (!Name) {
  3151. if (!D.isInvalidType()) // Reject this if we think it is valid.
  3152. Diag(D.getDeclSpec().getLocStart(),
  3153. diag::err_declarator_need_ident)
  3154. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  3155. return 0;
  3156. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  3157. return 0;
  3158. // The scope passed in may not be a decl scope. Zip up the scope tree until
  3159. // we find one that is.
  3160. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  3161. (S->getFlags() & Scope::TemplateParamScope) != 0)
  3162. S = S->getParent();
  3163. DeclContext *DC = CurContext;
  3164. if (D.getCXXScopeSpec().isInvalid())
  3165. D.setInvalidType();
  3166. else if (D.getCXXScopeSpec().isSet()) {
  3167. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  3168. UPPC_DeclarationQualifier))
  3169. return 0;
  3170. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  3171. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  3172. if (!DC) {
  3173. // If we could not compute the declaration context, it's because the
  3174. // declaration context is dependent but does not refer to a class,
  3175. // class template, or class template partial specialization. Complain
  3176. // and return early, to avoid the coming semantic disaster.
  3177. Diag(D.getIdentifierLoc(),
  3178. diag::err_template_qualified_declarator_no_match)
  3179. << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
  3180. << D.getCXXScopeSpec().getRange();
  3181. return 0;
  3182. }
  3183. bool IsDependentContext = DC->isDependentContext();
  3184. if (!IsDependentContext &&
  3185. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  3186. return 0;
  3187. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  3188. Diag(D.getIdentifierLoc(),
  3189. diag::err_member_def_undefined_record)
  3190. << Name << DC << D.getCXXScopeSpec().getRange();
  3191. D.setInvalidType();
  3192. } else if (!D.getDeclSpec().isFriendSpecified()) {
  3193. if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
  3194. Name, D.getIdentifierLoc())) {
  3195. if (DC->isRecord())
  3196. return 0;
  3197. D.setInvalidType();
  3198. }
  3199. }
  3200. // Check whether we need to rebuild the type of the given
  3201. // declaration in the current instantiation.
  3202. if (EnteringContext && IsDependentContext &&
  3203. TemplateParamLists.size() != 0) {
  3204. ContextRAII SavedContext(*this, DC);
  3205. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  3206. D.setInvalidType();
  3207. }
  3208. }
  3209. if (DiagnoseClassNameShadow(DC, NameInfo))
  3210. // If this is a typedef, we'll end up spewing multiple diagnostics.
  3211. // Just return early; it's safer.
  3212. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  3213. return 0;
  3214. NamedDecl *New;
  3215. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  3216. QualType R = TInfo->getType();
  3217. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  3218. UPPC_DeclarationType))
  3219. D.setInvalidType();
  3220. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  3221. ForRedeclaration);
  3222. // See if this is a redefinition of a variable in the same scope.
  3223. if (!D.getCXXScopeSpec().isSet()) {
  3224. bool IsLinkageLookup = false;
  3225. // If the declaration we're planning to build will be a function
  3226. // or object with linkage, then look for another declaration with
  3227. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  3228. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  3229. /* Do nothing*/;
  3230. else if (R->isFunctionType()) {
  3231. if (CurContext->isFunctionOrMethod() ||
  3232. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  3233. IsLinkageLookup = true;
  3234. } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
  3235. IsLinkageLookup = true;
  3236. else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  3237. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  3238. IsLinkageLookup = true;
  3239. if (IsLinkageLookup)
  3240. Previous.clear(LookupRedeclarationWithLinkage);
  3241. LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
  3242. } else { // Something like "int foo::x;"
  3243. LookupQualifiedName(Previous, DC);
  3244. // C++ [dcl.meaning]p1:
  3245. // When the declarator-id is qualified, the declaration shall refer to a
  3246. // previously declared member of the class or namespace to which the
  3247. // qualifier refers (or, in the case of a namespace, of an element of the
  3248. // inline namespace set of that namespace (7.3.1)) or to a specialization
  3249. // thereof; [...]
  3250. //
  3251. // Note that we already checked the context above, and that we do not have
  3252. // enough information to make sure that Previous contains the declaration
  3253. // we want to match. For example, given:
  3254. //
  3255. // class X {
  3256. // void f();
  3257. // void f(float);
  3258. // };
  3259. //
  3260. // void X::f(int) { } // ill-formed
  3261. //
  3262. // In this case, Previous will point to the overload set
  3263. // containing the two f's declared in X, but neither of them
  3264. // matches.
  3265. // C++ [dcl.meaning]p1:
  3266. // [...] the member shall not merely have been introduced by a
  3267. // using-declaration in the scope of the class or namespace nominated by
  3268. // the nested-name-specifier of the declarator-id.
  3269. RemoveUsingDecls(Previous);
  3270. }
  3271. if (Previous.isSingleResult() &&
  3272. Previous.getFoundDecl()->isTemplateParameter()) {
  3273. // Maybe we will complain about the shadowed template parameter.
  3274. if (!D.isInvalidType())
  3275. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  3276. Previous.getFoundDecl());
  3277. // Just pretend that we didn't see the previous declaration.
  3278. Previous.clear();
  3279. }
  3280. // In C++, the previous declaration we find might be a tag type
  3281. // (class or enum). In this case, the new declaration will hide the
  3282. // tag type. Note that this does does not apply if we're declaring a
  3283. // typedef (C++ [dcl.typedef]p4).
  3284. if (Previous.isSingleTagDecl() &&
  3285. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
  3286. Previous.clear();
  3287. bool AddToScope = true;
  3288. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  3289. if (TemplateParamLists.size()) {
  3290. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  3291. return 0;
  3292. }
  3293. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  3294. } else if (R->isFunctionType()) {
  3295. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  3296. TemplateParamLists,
  3297. AddToScope);
  3298. } else {
  3299. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
  3300. TemplateParamLists);
  3301. }
  3302. if (New == 0)
  3303. return 0;
  3304. // If this has an identifier and is not an invalid redeclaration or
  3305. // function template specialization, add it to the scope stack.
  3306. if (New->getDeclName() && AddToScope &&
  3307. !(D.isRedeclaration() && New->isInvalidDecl()))
  3308. PushOnScopeChains(New, S);
  3309. return New;
  3310. }
  3311. /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
  3312. /// types into constant array types in certain situations which would otherwise
  3313. /// be errors (for GCC compatibility).
  3314. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  3315. ASTContext &Context,
  3316. bool &SizeIsNegative,
  3317. llvm::APSInt &Oversized) {
  3318. // This method tries to turn a variable array into a constant
  3319. // array even when the size isn't an ICE. This is necessary
  3320. // for compatibility with code that depends on gcc's buggy
  3321. // constant expression folding, like struct {char x[(int)(char*)2];}
  3322. SizeIsNegative = false;
  3323. Oversized = 0;
  3324. if (T->isDependentType())
  3325. return QualType();
  3326. QualifierCollector Qs;
  3327. const Type *Ty = Qs.strip(T);
  3328. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  3329. QualType Pointee = PTy->getPointeeType();
  3330. QualType FixedType =
  3331. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  3332. Oversized);
  3333. if (FixedType.isNull()) return FixedType;
  3334. FixedType = Context.getPointerType(FixedType);
  3335. return Qs.apply(Context, FixedType);
  3336. }
  3337. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  3338. QualType Inner = PTy->getInnerType();
  3339. QualType FixedType =
  3340. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  3341. Oversized);
  3342. if (FixedType.isNull()) return FixedType;
  3343. FixedType = Context.getParenType(FixedType);
  3344. return Qs.apply(Context, FixedType);
  3345. }
  3346. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  3347. if (!VLATy)
  3348. return QualType();
  3349. // FIXME: We should probably handle this case
  3350. if (VLATy->getElementType()->isVariablyModifiedType())
  3351. return QualType();
  3352. llvm::APSInt Res;
  3353. if (!VLATy->getSizeExpr() ||
  3354. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  3355. return QualType();
  3356. // Check whether the array size is negative.
  3357. if (Res.isSigned() && Res.isNegative()) {
  3358. SizeIsNegative = true;
  3359. return QualType();
  3360. }
  3361. // Check whether the array is too large to be addressed.
  3362. unsigned ActiveSizeBits
  3363. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  3364. Res);
  3365. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  3366. Oversized = Res;
  3367. return QualType();
  3368. }
  3369. return Context.getConstantArrayType(VLATy->getElementType(),
  3370. Res, ArrayType::Normal, 0);
  3371. }
  3372. /// \brief Register the given locally-scoped external C declaration so
  3373. /// that it can be found later for redeclarations
  3374. void
  3375. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
  3376. const LookupResult &Previous,
  3377. Scope *S) {
  3378. assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
  3379. "Decl is not a locally-scoped decl!");
  3380. // Note that we have a locally-scoped external with this name.
  3381. LocallyScopedExternalDecls[ND->getDeclName()] = ND;
  3382. if (!Previous.isSingleResult())
  3383. return;
  3384. NamedDecl *PrevDecl = Previous.getFoundDecl();
  3385. // If there was a previous declaration of this variable, it may be
  3386. // in our identifier chain. Update the identifier chain with the new
  3387. // declaration.
  3388. if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
  3389. // The previous declaration was found on the identifer resolver
  3390. // chain, so remove it from its scope.
  3391. if (S->isDeclScope(PrevDecl)) {
  3392. // Special case for redeclarations in the SAME scope.
  3393. // Because this declaration is going to be added to the identifier chain
  3394. // later, we should temporarily take it OFF the chain.
  3395. IdResolver.RemoveDecl(ND);
  3396. } else {
  3397. // Find the scope for the original declaration.
  3398. while (S && !S->isDeclScope(PrevDecl))
  3399. S = S->getParent();
  3400. }
  3401. if (S)
  3402. S->RemoveDecl(PrevDecl);
  3403. }
  3404. }
  3405. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
  3406. Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
  3407. if (ExternalSource) {
  3408. // Load locally-scoped external decls from the external source.
  3409. SmallVector<NamedDecl *, 4> Decls;
  3410. ExternalSource->ReadLocallyScopedExternalDecls(Decls);
  3411. for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
  3412. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  3413. = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
  3414. if (Pos == LocallyScopedExternalDecls.end())
  3415. LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
  3416. }
  3417. }
  3418. return LocallyScopedExternalDecls.find(Name);
  3419. }
  3420. /// \brief Diagnose function specifiers on a declaration of an identifier that
  3421. /// does not identify a function.
  3422. void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
  3423. // FIXME: We should probably indicate the identifier in question to avoid
  3424. // confusion for constructs like "inline int a(), b;"
  3425. if (D.getDeclSpec().isInlineSpecified())
  3426. Diag(D.getDeclSpec().getInlineSpecLoc(),
  3427. diag::err_inline_non_function);
  3428. if (D.getDeclSpec().isVirtualSpecified())
  3429. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  3430. diag::err_virtual_non_function);
  3431. if (D.getDeclSpec().isExplicitSpecified())
  3432. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  3433. diag::err_explicit_non_function);
  3434. }
  3435. NamedDecl*
  3436. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  3437. TypeSourceInfo *TInfo, LookupResult &Previous) {
  3438. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  3439. if (D.getCXXScopeSpec().isSet()) {
  3440. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  3441. << D.getCXXScopeSpec().getRange();
  3442. D.setInvalidType();
  3443. // Pretend we didn't see the scope specifier.
  3444. DC = CurContext;
  3445. Previous.clear();
  3446. }
  3447. if (getLangOpts().CPlusPlus) {
  3448. // Check that there are no default arguments (C++ only).
  3449. CheckExtraCXXDefaultArguments(D);
  3450. }
  3451. DiagnoseFunctionSpecifiers(D);
  3452. if (D.getDeclSpec().isThreadSpecified())
  3453. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  3454. if (D.getDeclSpec().isConstexprSpecified())
  3455. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  3456. << 1;
  3457. if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
  3458. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  3459. << D.getName().getSourceRange();
  3460. return 0;
  3461. }
  3462. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  3463. if (!NewTD) return 0;
  3464. // Handle attributes prior to checking for duplicates in MergeVarDecl
  3465. ProcessDeclAttributes(S, NewTD, D);
  3466. CheckTypedefForVariablyModifiedType(S, NewTD);
  3467. bool Redeclaration = D.isRedeclaration();
  3468. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  3469. D.setRedeclaration(Redeclaration);
  3470. return ND;
  3471. }
  3472. void
  3473. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  3474. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  3475. // then it shall have block scope.
  3476. // Note that variably modified types must be fixed before merging the decl so
  3477. // that redeclarations will match.
  3478. QualType T = NewTD->getUnderlyingType();
  3479. if (T->isVariablyModifiedType()) {
  3480. getCurFunction()->setHasBranchProtectedScope();
  3481. if (S->getFnParent() == 0) {
  3482. bool SizeIsNegative;
  3483. llvm::APSInt Oversized;
  3484. QualType FixedTy =
  3485. TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  3486. Oversized);
  3487. if (!FixedTy.isNull()) {
  3488. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  3489. NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
  3490. } else {
  3491. if (SizeIsNegative)
  3492. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  3493. else if (T->isVariableArrayType())
  3494. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  3495. else if (Oversized.getBoolValue())
  3496. Diag(NewTD->getLocation(), diag::err_array_too_large)
  3497. << Oversized.toString(10);
  3498. else
  3499. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  3500. NewTD->setInvalidDecl();
  3501. }
  3502. }
  3503. }
  3504. }
  3505. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  3506. /// declares a typedef-name, either using the 'typedef' type specifier or via
  3507. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  3508. NamedDecl*
  3509. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  3510. LookupResult &Previous, bool &Redeclaration) {
  3511. // Merge the decl with the existing one if appropriate. If the decl is
  3512. // in an outer scope, it isn't the same thing.
  3513. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
  3514. /*ExplicitInstantiationOrSpecialization=*/false);
  3515. if (!Previous.empty()) {
  3516. Redeclaration = true;
  3517. MergeTypedefNameDecl(NewTD, Previous);
  3518. }
  3519. // If this is the C FILE type, notify the AST context.
  3520. if (IdentifierInfo *II = NewTD->getIdentifier())
  3521. if (!NewTD->isInvalidDecl() &&
  3522. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  3523. if (II->isStr("FILE"))
  3524. Context.setFILEDecl(NewTD);
  3525. else if (II->isStr("jmp_buf"))
  3526. Context.setjmp_bufDecl(NewTD);
  3527. else if (II->isStr("sigjmp_buf"))
  3528. Context.setsigjmp_bufDecl(NewTD);
  3529. else if (II->isStr("ucontext_t"))
  3530. Context.setucontext_tDecl(NewTD);
  3531. }
  3532. return NewTD;
  3533. }
  3534. /// \brief Determines whether the given declaration is an out-of-scope
  3535. /// previous declaration.
  3536. ///
  3537. /// This routine should be invoked when name lookup has found a
  3538. /// previous declaration (PrevDecl) that is not in the scope where a
  3539. /// new declaration by the same name is being introduced. If the new
  3540. /// declaration occurs in a local scope, previous declarations with
  3541. /// linkage may still be considered previous declarations (C99
  3542. /// 6.2.2p4-5, C++ [basic.link]p6).
  3543. ///
  3544. /// \param PrevDecl the previous declaration found by name
  3545. /// lookup
  3546. ///
  3547. /// \param DC the context in which the new declaration is being
  3548. /// declared.
  3549. ///
  3550. /// \returns true if PrevDecl is an out-of-scope previous declaration
  3551. /// for a new delcaration with the same name.
  3552. static bool
  3553. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  3554. ASTContext &Context) {
  3555. if (!PrevDecl)
  3556. return false;
  3557. if (!PrevDecl->hasLinkage())
  3558. return false;
  3559. if (Context.getLangOpts().CPlusPlus) {
  3560. // C++ [basic.link]p6:
  3561. // If there is a visible declaration of an entity with linkage
  3562. // having the same name and type, ignoring entities declared
  3563. // outside the innermost enclosing namespace scope, the block
  3564. // scope declaration declares that same entity and receives the
  3565. // linkage of the previous declaration.
  3566. DeclContext *OuterContext = DC->getRedeclContext();
  3567. if (!OuterContext->isFunctionOrMethod())
  3568. // This rule only applies to block-scope declarations.
  3569. return false;
  3570. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  3571. if (PrevOuterContext->isRecord())
  3572. // We found a member function: ignore it.
  3573. return false;
  3574. // Find the innermost enclosing namespace for the new and
  3575. // previous declarations.
  3576. OuterContext = OuterContext->getEnclosingNamespaceContext();
  3577. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  3578. // The previous declaration is in a different namespace, so it
  3579. // isn't the same function.
  3580. if (!OuterContext->Equals(PrevOuterContext))
  3581. return false;
  3582. }
  3583. return true;
  3584. }
  3585. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  3586. CXXScopeSpec &SS = D.getCXXScopeSpec();
  3587. if (!SS.isSet()) return;
  3588. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  3589. }
  3590. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  3591. QualType type = decl->getType();
  3592. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  3593. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  3594. // Various kinds of declaration aren't allowed to be __autoreleasing.
  3595. unsigned kind = -1U;
  3596. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  3597. if (var->hasAttr<BlocksAttr>())
  3598. kind = 0; // __block
  3599. else if (!var->hasLocalStorage())
  3600. kind = 1; // global
  3601. } else if (isa<ObjCIvarDecl>(decl)) {
  3602. kind = 3; // ivar
  3603. } else if (isa<FieldDecl>(decl)) {
  3604. kind = 2; // field
  3605. }
  3606. if (kind != -1U) {
  3607. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  3608. << kind;
  3609. }
  3610. } else if (lifetime == Qualifiers::OCL_None) {
  3611. // Try to infer lifetime.
  3612. if (!type->isObjCLifetimeType())
  3613. return false;
  3614. lifetime = type->getObjCARCImplicitLifetime();
  3615. type = Context.getLifetimeQualifiedType(type, lifetime);
  3616. decl->setType(type);
  3617. }
  3618. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  3619. // Thread-local variables cannot have lifetime.
  3620. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  3621. var->isThreadSpecified()) {
  3622. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  3623. << var->getType();
  3624. return true;
  3625. }
  3626. }
  3627. return false;
  3628. }
  3629. NamedDecl*
  3630. Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  3631. TypeSourceInfo *TInfo, LookupResult &Previous,
  3632. MultiTemplateParamsArg TemplateParamLists) {
  3633. QualType R = TInfo->getType();
  3634. DeclarationName Name = GetNameForDeclarator(D).getName();
  3635. // Check that there are no default arguments (C++ only).
  3636. if (getLangOpts().CPlusPlus)
  3637. CheckExtraCXXDefaultArguments(D);
  3638. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  3639. assert(SCSpec != DeclSpec::SCS_typedef &&
  3640. "Parser allowed 'typedef' as storage class VarDecl.");
  3641. VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
  3642. if (SCSpec == DeclSpec::SCS_mutable) {
  3643. // mutable can only appear on non-static class members, so it's always
  3644. // an error here
  3645. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  3646. D.setInvalidType();
  3647. SC = SC_None;
  3648. }
  3649. SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
  3650. VarDecl::StorageClass SCAsWritten
  3651. = StorageClassSpecToVarDeclStorageClass(SCSpec);
  3652. IdentifierInfo *II = Name.getAsIdentifierInfo();
  3653. if (!II) {
  3654. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
  3655. << Name;
  3656. return 0;
  3657. }
  3658. DiagnoseFunctionSpecifiers(D);
  3659. if (!DC->isRecord() && S->getFnParent() == 0) {
  3660. // C99 6.9p2: The storage-class specifiers auto and register shall not
  3661. // appear in the declaration specifiers in an external declaration.
  3662. if (SC == SC_Auto || SC == SC_Register) {
  3663. // If this is a register variable with an asm label specified, then this
  3664. // is a GNU extension.
  3665. if (SC == SC_Register && D.getAsmLabel())
  3666. Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
  3667. else
  3668. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  3669. D.setInvalidType();
  3670. }
  3671. }
  3672. if (getLangOpts().OpenCL) {
  3673. // Set up the special work-group-local storage class for variables in the
  3674. // OpenCL __local address space.
  3675. if (R.getAddressSpace() == LangAS::opencl_local)
  3676. SC = SC_OpenCLWorkGroupLocal;
  3677. }
  3678. bool isExplicitSpecialization = false;
  3679. VarDecl *NewVD;
  3680. if (!getLangOpts().CPlusPlus) {
  3681. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  3682. D.getIdentifierLoc(), II,
  3683. R, TInfo, SC, SCAsWritten);
  3684. if (D.isInvalidType())
  3685. NewVD->setInvalidDecl();
  3686. } else {
  3687. if (DC->isRecord() && !CurContext->isRecord()) {
  3688. // This is an out-of-line definition of a static data member.
  3689. if (SC == SC_Static) {
  3690. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  3691. diag::err_static_out_of_line)
  3692. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  3693. } else if (SC == SC_None)
  3694. SC = SC_Static;
  3695. }
  3696. if (SC == SC_Static && CurContext->isRecord()) {
  3697. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  3698. if (RD->isLocalClass())
  3699. Diag(D.getIdentifierLoc(),
  3700. diag::err_static_data_member_not_allowed_in_local_class)
  3701. << Name << RD->getDeclName();
  3702. // C++98 [class.union]p1: If a union contains a static data member,
  3703. // the program is ill-formed. C++11 drops this restriction.
  3704. if (RD->isUnion())
  3705. Diag(D.getIdentifierLoc(),
  3706. getLangOpts().CPlusPlus0x
  3707. ? diag::warn_cxx98_compat_static_data_member_in_union
  3708. : diag::ext_static_data_member_in_union) << Name;
  3709. // We conservatively disallow static data members in anonymous structs.
  3710. else if (!RD->getDeclName())
  3711. Diag(D.getIdentifierLoc(),
  3712. diag::err_static_data_member_not_allowed_in_anon_struct)
  3713. << Name << RD->isUnion();
  3714. }
  3715. }
  3716. // Match up the template parameter lists with the scope specifier, then
  3717. // determine whether we have a template or a template specialization.
  3718. isExplicitSpecialization = false;
  3719. bool Invalid = false;
  3720. if (TemplateParameterList *TemplateParams
  3721. = MatchTemplateParametersToScopeSpecifier(
  3722. D.getDeclSpec().getLocStart(),
  3723. D.getIdentifierLoc(),
  3724. D.getCXXScopeSpec(),
  3725. TemplateParamLists.data(),
  3726. TemplateParamLists.size(),
  3727. /*never a friend*/ false,
  3728. isExplicitSpecialization,
  3729. Invalid)) {
  3730. if (TemplateParams->size() > 0) {
  3731. // There is no such thing as a variable template.
  3732. Diag(D.getIdentifierLoc(), diag::err_template_variable)
  3733. << II
  3734. << SourceRange(TemplateParams->getTemplateLoc(),
  3735. TemplateParams->getRAngleLoc());
  3736. return 0;
  3737. } else {
  3738. // There is an extraneous 'template<>' for this variable. Complain
  3739. // about it, but allow the declaration of the variable.
  3740. Diag(TemplateParams->getTemplateLoc(),
  3741. diag::err_template_variable_noparams)
  3742. << II
  3743. << SourceRange(TemplateParams->getTemplateLoc(),
  3744. TemplateParams->getRAngleLoc());
  3745. }
  3746. }
  3747. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  3748. D.getIdentifierLoc(), II,
  3749. R, TInfo, SC, SCAsWritten);
  3750. // If this decl has an auto type in need of deduction, make a note of the
  3751. // Decl so we can diagnose uses of it in its own initializer.
  3752. if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
  3753. R->getContainedAutoType())
  3754. ParsingInitForAutoVars.insert(NewVD);
  3755. if (D.isInvalidType() || Invalid)
  3756. NewVD->setInvalidDecl();
  3757. SetNestedNameSpecifier(NewVD, D);
  3758. if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
  3759. NewVD->setTemplateParameterListsInfo(Context,
  3760. TemplateParamLists.size(),
  3761. TemplateParamLists.data());
  3762. }
  3763. if (D.getDeclSpec().isConstexprSpecified())
  3764. NewVD->setConstexpr(true);
  3765. }
  3766. // Set the lexical context. If the declarator has a C++ scope specifier, the
  3767. // lexical context will be different from the semantic context.
  3768. NewVD->setLexicalDeclContext(CurContext);
  3769. if (D.getDeclSpec().isThreadSpecified()) {
  3770. if (NewVD->hasLocalStorage())
  3771. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
  3772. else if (!Context.getTargetInfo().isTLSSupported())
  3773. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
  3774. else
  3775. NewVD->setThreadSpecified(true);
  3776. }
  3777. if (D.getDeclSpec().isModulePrivateSpecified()) {
  3778. if (isExplicitSpecialization)
  3779. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  3780. << 2
  3781. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  3782. else if (NewVD->hasLocalStorage())
  3783. Diag(NewVD->getLocation(), diag::err_module_private_local)
  3784. << 0 << NewVD->getDeclName()
  3785. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  3786. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  3787. else
  3788. NewVD->setModulePrivate();
  3789. }
  3790. // Handle attributes prior to checking for duplicates in MergeVarDecl
  3791. ProcessDeclAttributes(S, NewVD, D);
  3792. if (getLangOpts().CUDA) {
  3793. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  3794. // storage [duration]."
  3795. if (SC == SC_None && S->getFnParent() != 0 &&
  3796. (NewVD->hasAttr<CUDASharedAttr>() || NewVD->hasAttr<CUDAConstantAttr>()))
  3797. NewVD->setStorageClass(SC_Static);
  3798. }
  3799. // In auto-retain/release, infer strong retension for variables of
  3800. // retainable type.
  3801. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  3802. NewVD->setInvalidDecl();
  3803. // Handle GNU asm-label extension (encoded as an attribute).
  3804. if (Expr *E = (Expr*)D.getAsmLabel()) {
  3805. // The parser guarantees this is a string.
  3806. StringLiteral *SE = cast<StringLiteral>(E);
  3807. StringRef Label = SE->getString();
  3808. if (S->getFnParent() != 0) {
  3809. switch (SC) {
  3810. case SC_None:
  3811. case SC_Auto:
  3812. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  3813. break;
  3814. case SC_Register:
  3815. if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
  3816. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  3817. break;
  3818. case SC_Static:
  3819. case SC_Extern:
  3820. case SC_PrivateExtern:
  3821. case SC_OpenCLWorkGroupLocal:
  3822. break;
  3823. }
  3824. }
  3825. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  3826. Context, Label));
  3827. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  3828. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  3829. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  3830. if (I != ExtnameUndeclaredIdentifiers.end()) {
  3831. NewVD->addAttr(I->second);
  3832. ExtnameUndeclaredIdentifiers.erase(I);
  3833. }
  3834. }
  3835. // Diagnose shadowed variables before filtering for scope.
  3836. if (!D.getCXXScopeSpec().isSet())
  3837. CheckShadow(S, NewVD, Previous);
  3838. // Don't consider existing declarations that are in a different
  3839. // scope and are out-of-semantic-context declarations (if the new
  3840. // declaration has linkage).
  3841. FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
  3842. isExplicitSpecialization);
  3843. if (!getLangOpts().CPlusPlus) {
  3844. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  3845. } else {
  3846. // Merge the decl with the existing one if appropriate.
  3847. if (!Previous.empty()) {
  3848. if (Previous.isSingleResult() &&
  3849. isa<FieldDecl>(Previous.getFoundDecl()) &&
  3850. D.getCXXScopeSpec().isSet()) {
  3851. // The user tried to define a non-static data member
  3852. // out-of-line (C++ [dcl.meaning]p1).
  3853. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  3854. << D.getCXXScopeSpec().getRange();
  3855. Previous.clear();
  3856. NewVD->setInvalidDecl();
  3857. }
  3858. } else if (D.getCXXScopeSpec().isSet()) {
  3859. // No previous declaration in the qualifying scope.
  3860. Diag(D.getIdentifierLoc(), diag::err_no_member)
  3861. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  3862. << D.getCXXScopeSpec().getRange();
  3863. NewVD->setInvalidDecl();
  3864. }
  3865. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  3866. // This is an explicit specialization of a static data member. Check it.
  3867. if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
  3868. CheckMemberSpecialization(NewVD, Previous))
  3869. NewVD->setInvalidDecl();
  3870. }
  3871. // If this is a locally-scoped extern C variable, update the map of
  3872. // such variables.
  3873. if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
  3874. !NewVD->isInvalidDecl())
  3875. RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
  3876. // If there's a #pragma GCC visibility in scope, and this isn't a class
  3877. // member, set the visibility of this variable.
  3878. if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
  3879. AddPushedVisibilityAttribute(NewVD);
  3880. MarkUnusedFileScopedDecl(NewVD);
  3881. return NewVD;
  3882. }
  3883. /// \brief Diagnose variable or built-in function shadowing. Implements
  3884. /// -Wshadow.
  3885. ///
  3886. /// This method is called whenever a VarDecl is added to a "useful"
  3887. /// scope.
  3888. ///
  3889. /// \param S the scope in which the shadowing name is being declared
  3890. /// \param R the lookup of the name
  3891. ///
  3892. void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
  3893. // Return if warning is ignored.
  3894. if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
  3895. DiagnosticsEngine::Ignored)
  3896. return;
  3897. // Don't diagnose declarations at file scope.
  3898. if (D->hasGlobalStorage())
  3899. return;
  3900. DeclContext *NewDC = D->getDeclContext();
  3901. // Only diagnose if we're shadowing an unambiguous field or variable.
  3902. if (R.getResultKind() != LookupResult::Found)
  3903. return;
  3904. NamedDecl* ShadowedDecl = R.getFoundDecl();
  3905. if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
  3906. return;
  3907. // Fields are not shadowed by variables in C++ static methods.
  3908. if (isa<FieldDecl>(ShadowedDecl))
  3909. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  3910. if (MD->isStatic())
  3911. return;
  3912. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  3913. if (shadowedVar->isExternC()) {
  3914. // For shadowing external vars, make sure that we point to the global
  3915. // declaration, not a locally scoped extern declaration.
  3916. for (VarDecl::redecl_iterator
  3917. I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
  3918. I != E; ++I)
  3919. if (I->isFileVarDecl()) {
  3920. ShadowedDecl = *I;
  3921. break;
  3922. }
  3923. }
  3924. DeclContext *OldDC = ShadowedDecl->getDeclContext();
  3925. // Only warn about certain kinds of shadowing for class members.
  3926. if (NewDC && NewDC->isRecord()) {
  3927. // In particular, don't warn about shadowing non-class members.
  3928. if (!OldDC->isRecord())
  3929. return;
  3930. // TODO: should we warn about static data members shadowing
  3931. // static data members from base classes?
  3932. // TODO: don't diagnose for inaccessible shadowed members.
  3933. // This is hard to do perfectly because we might friend the
  3934. // shadowing context, but that's just a false negative.
  3935. }
  3936. // Determine what kind of declaration we're shadowing.
  3937. unsigned Kind;
  3938. if (isa<RecordDecl>(OldDC)) {
  3939. if (isa<FieldDecl>(ShadowedDecl))
  3940. Kind = 3; // field
  3941. else
  3942. Kind = 2; // static data member
  3943. } else if (OldDC->isFileContext())
  3944. Kind = 1; // global
  3945. else
  3946. Kind = 0; // local
  3947. DeclarationName Name = R.getLookupName();
  3948. // Emit warning and note.
  3949. Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
  3950. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  3951. }
  3952. /// \brief Check -Wshadow without the advantage of a previous lookup.
  3953. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  3954. if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
  3955. DiagnosticsEngine::Ignored)
  3956. return;
  3957. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  3958. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  3959. LookupName(R, S);
  3960. CheckShadow(S, D, R);
  3961. }
  3962. /// \brief Perform semantic checking on a newly-created variable
  3963. /// declaration.
  3964. ///
  3965. /// This routine performs all of the type-checking required for a
  3966. /// variable declaration once it has been built. It is used both to
  3967. /// check variables after they have been parsed and their declarators
  3968. /// have been translated into a declaration, and to check variables
  3969. /// that have been instantiated from a template.
  3970. ///
  3971. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  3972. ///
  3973. /// Returns true if the variable declaration is a redeclaration.
  3974. bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
  3975. LookupResult &Previous) {
  3976. // If the decl is already known invalid, don't check it.
  3977. if (NewVD->isInvalidDecl())
  3978. return false;
  3979. QualType T = NewVD->getType();
  3980. if (T->isObjCObjectType()) {
  3981. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  3982. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  3983. T = Context.getObjCObjectPointerType(T);
  3984. NewVD->setType(T);
  3985. }
  3986. // Emit an error if an address space was applied to decl with local storage.
  3987. // This includes arrays of objects with address space qualifiers, but not
  3988. // automatic variables that point to other address spaces.
  3989. // ISO/IEC TR 18037 S5.1.2
  3990. if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
  3991. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
  3992. NewVD->setInvalidDecl();
  3993. return false;
  3994. }
  3995. // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
  3996. // scope.
  3997. if ((getLangOpts().OpenCLVersion >= 120)
  3998. && NewVD->isStaticLocal()) {
  3999. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  4000. NewVD->setInvalidDecl();
  4001. return false;
  4002. }
  4003. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  4004. && !NewVD->hasAttr<BlocksAttr>()) {
  4005. if (getLangOpts().getGC() != LangOptions::NonGC)
  4006. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  4007. else
  4008. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  4009. }
  4010. bool isVM = T->isVariablyModifiedType();
  4011. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  4012. NewVD->hasAttr<BlocksAttr>())
  4013. getCurFunction()->setHasBranchProtectedScope();
  4014. if ((isVM && NewVD->hasLinkage()) ||
  4015. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  4016. bool SizeIsNegative;
  4017. llvm::APSInt Oversized;
  4018. QualType FixedTy =
  4019. TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  4020. Oversized);
  4021. if (FixedTy.isNull() && T->isVariableArrayType()) {
  4022. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  4023. // FIXME: This won't give the correct result for
  4024. // int a[10][n];
  4025. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  4026. if (NewVD->isFileVarDecl())
  4027. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  4028. << SizeRange;
  4029. else if (NewVD->getStorageClass() == SC_Static)
  4030. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  4031. << SizeRange;
  4032. else
  4033. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  4034. << SizeRange;
  4035. NewVD->setInvalidDecl();
  4036. return false;
  4037. }
  4038. if (FixedTy.isNull()) {
  4039. if (NewVD->isFileVarDecl())
  4040. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  4041. else
  4042. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  4043. NewVD->setInvalidDecl();
  4044. return false;
  4045. }
  4046. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  4047. NewVD->setType(FixedTy);
  4048. }
  4049. if (Previous.empty() && NewVD->isExternC()) {
  4050. // Since we did not find anything by this name and we're declaring
  4051. // an extern "C" variable, look for a non-visible extern "C"
  4052. // declaration with the same name.
  4053. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  4054. = findLocallyScopedExternalDecl(NewVD->getDeclName());
  4055. if (Pos != LocallyScopedExternalDecls.end())
  4056. Previous.addDecl(Pos->second);
  4057. }
  4058. if (T->isVoidType() && !NewVD->hasExternalStorage()) {
  4059. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  4060. << T;
  4061. NewVD->setInvalidDecl();
  4062. return false;
  4063. }
  4064. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  4065. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  4066. NewVD->setInvalidDecl();
  4067. return false;
  4068. }
  4069. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  4070. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  4071. NewVD->setInvalidDecl();
  4072. return false;
  4073. }
  4074. if (NewVD->isConstexpr() && !T->isDependentType() &&
  4075. RequireLiteralType(NewVD->getLocation(), T,
  4076. diag::err_constexpr_var_non_literal)) {
  4077. NewVD->setInvalidDecl();
  4078. return false;
  4079. }
  4080. if (!Previous.empty()) {
  4081. MergeVarDecl(NewVD, Previous);
  4082. return true;
  4083. }
  4084. return false;
  4085. }
  4086. /// \brief Data used with FindOverriddenMethod
  4087. struct FindOverriddenMethodData {
  4088. Sema *S;
  4089. CXXMethodDecl *Method;
  4090. };
  4091. /// \brief Member lookup function that determines whether a given C++
  4092. /// method overrides a method in a base class, to be used with
  4093. /// CXXRecordDecl::lookupInBases().
  4094. static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
  4095. CXXBasePath &Path,
  4096. void *UserData) {
  4097. RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
  4098. FindOverriddenMethodData *Data
  4099. = reinterpret_cast<FindOverriddenMethodData*>(UserData);
  4100. DeclarationName Name = Data->Method->getDeclName();
  4101. // FIXME: Do we care about other names here too?
  4102. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  4103. // We really want to find the base class destructor here.
  4104. QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
  4105. CanQualType CT = Data->S->Context.getCanonicalType(T);
  4106. Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
  4107. }
  4108. for (Path.Decls = BaseRecord->lookup(Name);
  4109. Path.Decls.first != Path.Decls.second;
  4110. ++Path.Decls.first) {
  4111. NamedDecl *D = *Path.Decls.first;
  4112. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  4113. if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
  4114. return true;
  4115. }
  4116. }
  4117. return false;
  4118. }
  4119. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  4120. /// and if so, check that it's a valid override and remember it.
  4121. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  4122. // Look for virtual methods in base classes that this method might override.
  4123. CXXBasePaths Paths;
  4124. FindOverriddenMethodData Data;
  4125. Data.Method = MD;
  4126. Data.S = this;
  4127. bool AddedAny = false;
  4128. if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
  4129. for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
  4130. E = Paths.found_decls_end(); I != E; ++I) {
  4131. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
  4132. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  4133. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  4134. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  4135. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  4136. AddedAny = true;
  4137. }
  4138. }
  4139. }
  4140. }
  4141. return AddedAny;
  4142. }
  4143. namespace {
  4144. // Struct for holding all of the extra arguments needed by
  4145. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  4146. struct ActOnFDArgs {
  4147. Scope *S;
  4148. Declarator &D;
  4149. MultiTemplateParamsArg TemplateParamLists;
  4150. bool AddToScope;
  4151. };
  4152. }
  4153. namespace {
  4154. // Callback to only accept typo corrections that have a non-zero edit distance.
  4155. // Also only accept corrections that have the same parent decl.
  4156. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  4157. public:
  4158. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  4159. CXXRecordDecl *Parent)
  4160. : Context(Context), OriginalFD(TypoFD),
  4161. ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
  4162. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  4163. if (candidate.getEditDistance() == 0)
  4164. return false;
  4165. llvm::SmallVector<unsigned, 1> MismatchedParams;
  4166. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  4167. CDeclEnd = candidate.end();
  4168. CDecl != CDeclEnd; ++CDecl) {
  4169. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  4170. if (FD && !FD->hasBody() &&
  4171. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  4172. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  4173. CXXRecordDecl *Parent = MD->getParent();
  4174. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  4175. return true;
  4176. } else if (!ExpectedParent) {
  4177. return true;
  4178. }
  4179. }
  4180. }
  4181. return false;
  4182. }
  4183. private:
  4184. ASTContext &Context;
  4185. FunctionDecl *OriginalFD;
  4186. CXXRecordDecl *ExpectedParent;
  4187. };
  4188. }
  4189. /// \brief Generate diagnostics for an invalid function redeclaration.
  4190. ///
  4191. /// This routine handles generating the diagnostic messages for an invalid
  4192. /// function redeclaration, including finding possible similar declarations
  4193. /// or performing typo correction if there are no previous declarations with
  4194. /// the same name.
  4195. ///
  4196. /// Returns a NamedDecl if typo correction was performed and substituting in
  4197. /// the new declaration name does not cause new errors.
  4198. static NamedDecl* DiagnoseInvalidRedeclaration(
  4199. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  4200. ActOnFDArgs &ExtraArgs) {
  4201. NamedDecl *Result = NULL;
  4202. DeclarationName Name = NewFD->getDeclName();
  4203. DeclContext *NewDC = NewFD->getDeclContext();
  4204. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  4205. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  4206. llvm::SmallVector<unsigned, 1> MismatchedParams;
  4207. llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
  4208. TypoCorrection Correction;
  4209. bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
  4210. ExtraArgs.D.getDeclSpec().isFriendSpecified());
  4211. unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
  4212. : diag::err_member_def_does_not_match;
  4213. NewFD->setInvalidDecl();
  4214. SemaRef.LookupQualifiedName(Prev, NewDC);
  4215. assert(!Prev.isAmbiguous() &&
  4216. "Cannot have an ambiguity in previous-declaration lookup");
  4217. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  4218. DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
  4219. MD ? MD->getParent() : 0);
  4220. if (!Prev.empty()) {
  4221. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  4222. Func != FuncEnd; ++Func) {
  4223. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  4224. if (FD &&
  4225. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  4226. // Add 1 to the index so that 0 can mean the mismatch didn't
  4227. // involve a parameter
  4228. unsigned ParamNum =
  4229. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  4230. NearMatches.push_back(std::make_pair(FD, ParamNum));
  4231. }
  4232. }
  4233. // If the qualified name lookup yielded nothing, try typo correction
  4234. } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
  4235. Prev.getLookupKind(), 0, 0,
  4236. Validator, NewDC))) {
  4237. // Trap errors.
  4238. Sema::SFINAETrap Trap(SemaRef);
  4239. // Set up everything for the call to ActOnFunctionDeclarator
  4240. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  4241. ExtraArgs.D.getIdentifierLoc());
  4242. Previous.clear();
  4243. Previous.setLookupName(Correction.getCorrection());
  4244. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  4245. CDeclEnd = Correction.end();
  4246. CDecl != CDeclEnd; ++CDecl) {
  4247. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  4248. if (FD && !FD->hasBody() &&
  4249. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  4250. Previous.addDecl(FD);
  4251. }
  4252. }
  4253. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  4254. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  4255. // pieces need to verify the typo-corrected C++ declaraction and hopefully
  4256. // eliminate the need for the parameter pack ExtraArgs.
  4257. Result = SemaRef.ActOnFunctionDeclarator(
  4258. ExtraArgs.S, ExtraArgs.D,
  4259. Correction.getCorrectionDecl()->getDeclContext(),
  4260. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  4261. ExtraArgs.AddToScope);
  4262. if (Trap.hasErrorOccurred()) {
  4263. // Pretend the typo correction never occurred
  4264. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  4265. ExtraArgs.D.getIdentifierLoc());
  4266. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  4267. Previous.clear();
  4268. Previous.setLookupName(Name);
  4269. Result = NULL;
  4270. } else {
  4271. for (LookupResult::iterator Func = Previous.begin(),
  4272. FuncEnd = Previous.end();
  4273. Func != FuncEnd; ++Func) {
  4274. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
  4275. NearMatches.push_back(std::make_pair(FD, 0));
  4276. }
  4277. }
  4278. if (NearMatches.empty()) {
  4279. // Ignore the correction if it didn't yield any close FunctionDecl matches
  4280. Correction = TypoCorrection();
  4281. } else {
  4282. DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
  4283. : diag::err_member_def_does_not_match_suggest;
  4284. }
  4285. }
  4286. if (Correction) {
  4287. SourceRange FixItLoc(NewFD->getLocation());
  4288. CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec();
  4289. if (Correction.getCorrectionSpecifier() && SS.isValid())
  4290. FixItLoc.setBegin(SS.getBeginLoc());
  4291. SemaRef.Diag(NewFD->getLocStart(), DiagMsg)
  4292. << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
  4293. << FixItHint::CreateReplacement(
  4294. FixItLoc, Correction.getAsString(SemaRef.getLangOpts()));
  4295. } else {
  4296. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  4297. << Name << NewDC << NewFD->getLocation();
  4298. }
  4299. bool NewFDisConst = false;
  4300. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  4301. NewFDisConst = NewMD->isConst();
  4302. for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
  4303. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  4304. NearMatch != NearMatchEnd; ++NearMatch) {
  4305. FunctionDecl *FD = NearMatch->first;
  4306. bool FDisConst = false;
  4307. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  4308. FDisConst = MD->isConst();
  4309. if (unsigned Idx = NearMatch->second) {
  4310. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  4311. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  4312. if (Loc.isInvalid()) Loc = FD->getLocation();
  4313. SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
  4314. << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
  4315. } else if (Correction) {
  4316. SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
  4317. << Correction.getQuoted(SemaRef.getLangOpts());
  4318. } else if (FDisConst != NewFDisConst) {
  4319. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  4320. << NewFDisConst << FD->getSourceRange().getEnd();
  4321. } else
  4322. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
  4323. }
  4324. return Result;
  4325. }
  4326. static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
  4327. Declarator &D) {
  4328. switch (D.getDeclSpec().getStorageClassSpec()) {
  4329. default: llvm_unreachable("Unknown storage class!");
  4330. case DeclSpec::SCS_auto:
  4331. case DeclSpec::SCS_register:
  4332. case DeclSpec::SCS_mutable:
  4333. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4334. diag::err_typecheck_sclass_func);
  4335. D.setInvalidType();
  4336. break;
  4337. case DeclSpec::SCS_unspecified: break;
  4338. case DeclSpec::SCS_extern: return SC_Extern;
  4339. case DeclSpec::SCS_static: {
  4340. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  4341. // C99 6.7.1p5:
  4342. // The declaration of an identifier for a function that has
  4343. // block scope shall have no explicit storage-class specifier
  4344. // other than extern
  4345. // See also (C++ [dcl.stc]p4).
  4346. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4347. diag::err_static_block_func);
  4348. break;
  4349. } else
  4350. return SC_Static;
  4351. }
  4352. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4353. }
  4354. // No explicit storage class has already been returned
  4355. return SC_None;
  4356. }
  4357. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  4358. DeclContext *DC, QualType &R,
  4359. TypeSourceInfo *TInfo,
  4360. FunctionDecl::StorageClass SC,
  4361. bool &IsVirtualOkay) {
  4362. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  4363. DeclarationName Name = NameInfo.getName();
  4364. FunctionDecl *NewFD = 0;
  4365. bool isInline = D.getDeclSpec().isInlineSpecified();
  4366. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
  4367. FunctionDecl::StorageClass SCAsWritten
  4368. = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
  4369. if (!SemaRef.getLangOpts().CPlusPlus) {
  4370. // Determine whether the function was written with a
  4371. // prototype. This true when:
  4372. // - there is a prototype in the declarator, or
  4373. // - the type R of the function is some kind of typedef or other reference
  4374. // to a type name (which eventually refers to a function type).
  4375. bool HasPrototype =
  4376. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  4377. (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
  4378. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  4379. D.getLocStart(), NameInfo, R,
  4380. TInfo, SC, SCAsWritten, isInline,
  4381. HasPrototype);
  4382. if (D.isInvalidType())
  4383. NewFD->setInvalidDecl();
  4384. // Set the lexical context.
  4385. NewFD->setLexicalDeclContext(SemaRef.CurContext);
  4386. return NewFD;
  4387. }
  4388. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  4389. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  4390. // Check that the return type is not an abstract class type.
  4391. // For record types, this is done by the AbstractClassUsageDiagnoser once
  4392. // the class has been completely parsed.
  4393. if (!DC->isRecord() &&
  4394. SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
  4395. R->getAs<FunctionType>()->getResultType(),
  4396. diag::err_abstract_type_in_decl,
  4397. SemaRef.AbstractReturnType))
  4398. D.setInvalidType();
  4399. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  4400. // This is a C++ constructor declaration.
  4401. assert(DC->isRecord() &&
  4402. "Constructors can only be declared in a member context");
  4403. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  4404. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4405. D.getLocStart(), NameInfo,
  4406. R, TInfo, isExplicit, isInline,
  4407. /*isImplicitlyDeclared=*/false,
  4408. isConstexpr);
  4409. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  4410. // This is a C++ destructor declaration.
  4411. if (DC->isRecord()) {
  4412. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  4413. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  4414. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  4415. SemaRef.Context, Record,
  4416. D.getLocStart(),
  4417. NameInfo, R, TInfo, isInline,
  4418. /*isImplicitlyDeclared=*/false);
  4419. // If the class is complete, then we now create the implicit exception
  4420. // specification. If the class is incomplete or dependent, we can't do
  4421. // it yet.
  4422. if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() &&
  4423. Record->getDefinition() && !Record->isBeingDefined() &&
  4424. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  4425. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  4426. }
  4427. IsVirtualOkay = true;
  4428. return NewDD;
  4429. } else {
  4430. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  4431. D.setInvalidType();
  4432. // Create a FunctionDecl to satisfy the function definition parsing
  4433. // code path.
  4434. return FunctionDecl::Create(SemaRef.Context, DC,
  4435. D.getLocStart(),
  4436. D.getIdentifierLoc(), Name, R, TInfo,
  4437. SC, SCAsWritten, isInline,
  4438. /*hasPrototype=*/true, isConstexpr);
  4439. }
  4440. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  4441. if (!DC->isRecord()) {
  4442. SemaRef.Diag(D.getIdentifierLoc(),
  4443. diag::err_conv_function_not_member);
  4444. return 0;
  4445. }
  4446. SemaRef.CheckConversionDeclarator(D, R, SC);
  4447. IsVirtualOkay = true;
  4448. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4449. D.getLocStart(), NameInfo,
  4450. R, TInfo, isInline, isExplicit,
  4451. isConstexpr, SourceLocation());
  4452. } else if (DC->isRecord()) {
  4453. // If the name of the function is the same as the name of the record,
  4454. // then this must be an invalid constructor that has a return type.
  4455. // (The parser checks for a return type and makes the declarator a
  4456. // constructor if it has no return type).
  4457. if (Name.getAsIdentifierInfo() &&
  4458. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  4459. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  4460. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  4461. << SourceRange(D.getIdentifierLoc());
  4462. return 0;
  4463. }
  4464. bool isStatic = SC == SC_Static;
  4465. // [class.free]p1:
  4466. // Any allocation function for a class T is a static member
  4467. // (even if not explicitly declared static).
  4468. if (Name.getCXXOverloadedOperator() == OO_New ||
  4469. Name.getCXXOverloadedOperator() == OO_Array_New)
  4470. isStatic = true;
  4471. // [class.free]p6 Any deallocation function for a class X is a static member
  4472. // (even if not explicitly declared static).
  4473. if (Name.getCXXOverloadedOperator() == OO_Delete ||
  4474. Name.getCXXOverloadedOperator() == OO_Array_Delete)
  4475. isStatic = true;
  4476. IsVirtualOkay = !isStatic;
  4477. // This is a C++ method declaration.
  4478. return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4479. D.getLocStart(), NameInfo, R,
  4480. TInfo, isStatic, SCAsWritten, isInline,
  4481. isConstexpr, SourceLocation());
  4482. } else {
  4483. // Determine whether the function was written with a
  4484. // prototype. This true when:
  4485. // - we're in C++ (where every function has a prototype),
  4486. return FunctionDecl::Create(SemaRef.Context, DC,
  4487. D.getLocStart(),
  4488. NameInfo, R, TInfo, SC, SCAsWritten, isInline,
  4489. true/*HasPrototype*/, isConstexpr);
  4490. }
  4491. }
  4492. void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
  4493. // In C++, the empty parameter-type-list must be spelled "void"; a
  4494. // typedef of void is not permitted.
  4495. if (getLangOpts().CPlusPlus &&
  4496. Param->getType().getUnqualifiedType() != Context.VoidTy) {
  4497. bool IsTypeAlias = false;
  4498. if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
  4499. IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
  4500. else if (const TemplateSpecializationType *TST =
  4501. Param->getType()->getAs<TemplateSpecializationType>())
  4502. IsTypeAlias = TST->isTypeAlias();
  4503. Diag(Param->getLocation(), diag::err_param_typedef_of_void)
  4504. << IsTypeAlias;
  4505. }
  4506. }
  4507. NamedDecl*
  4508. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  4509. TypeSourceInfo *TInfo, LookupResult &Previous,
  4510. MultiTemplateParamsArg TemplateParamLists,
  4511. bool &AddToScope) {
  4512. QualType R = TInfo->getType();
  4513. assert(R.getTypePtr()->isFunctionType());
  4514. // TODO: consider using NameInfo for diagnostic.
  4515. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4516. DeclarationName Name = NameInfo.getName();
  4517. FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
  4518. if (D.getDeclSpec().isThreadSpecified())
  4519. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  4520. // Do not allow returning a objc interface by-value.
  4521. if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
  4522. Diag(D.getIdentifierLoc(),
  4523. diag::err_object_cannot_be_passed_returned_by_value) << 0
  4524. << R->getAs<FunctionType>()->getResultType()
  4525. << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
  4526. QualType T = R->getAs<FunctionType>()->getResultType();
  4527. T = Context.getObjCObjectPointerType(T);
  4528. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
  4529. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  4530. R = Context.getFunctionType(T, FPT->arg_type_begin(),
  4531. FPT->getNumArgs(), EPI);
  4532. }
  4533. else if (isa<FunctionNoProtoType>(R))
  4534. R = Context.getFunctionNoProtoType(T);
  4535. }
  4536. bool isFriend = false;
  4537. FunctionTemplateDecl *FunctionTemplate = 0;
  4538. bool isExplicitSpecialization = false;
  4539. bool isFunctionTemplateSpecialization = false;
  4540. bool isDependentClassScopeExplicitSpecialization = false;
  4541. bool HasExplicitTemplateArgs = false;
  4542. TemplateArgumentListInfo TemplateArgs;
  4543. bool isVirtualOkay = false;
  4544. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  4545. isVirtualOkay);
  4546. if (!NewFD) return 0;
  4547. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  4548. NewFD->setTopLevelDeclInObjCContainer();
  4549. if (getLangOpts().CPlusPlus) {
  4550. bool isInline = D.getDeclSpec().isInlineSpecified();
  4551. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  4552. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  4553. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  4554. isFriend = D.getDeclSpec().isFriendSpecified();
  4555. if (isFriend && !isInline && D.isFunctionDefinition()) {
  4556. // C++ [class.friend]p5
  4557. // A function can be defined in a friend declaration of a
  4558. // class . . . . Such a function is implicitly inline.
  4559. NewFD->setImplicitlyInline();
  4560. }
  4561. // If this is a method defined in an __interface, and is not a constructor
  4562. // or an overloaded operator, then set the pure flag (isVirtual will already
  4563. // return true).
  4564. if (const CXXRecordDecl *Parent =
  4565. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  4566. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  4567. NewFD->setPure(true);
  4568. }
  4569. SetNestedNameSpecifier(NewFD, D);
  4570. isExplicitSpecialization = false;
  4571. isFunctionTemplateSpecialization = false;
  4572. if (D.isInvalidType())
  4573. NewFD->setInvalidDecl();
  4574. // Set the lexical context. If the declarator has a C++
  4575. // scope specifier, or is the object of a friend declaration, the
  4576. // lexical context will be different from the semantic context.
  4577. NewFD->setLexicalDeclContext(CurContext);
  4578. // Match up the template parameter lists with the scope specifier, then
  4579. // determine whether we have a template or a template specialization.
  4580. bool Invalid = false;
  4581. if (TemplateParameterList *TemplateParams
  4582. = MatchTemplateParametersToScopeSpecifier(
  4583. D.getDeclSpec().getLocStart(),
  4584. D.getIdentifierLoc(),
  4585. D.getCXXScopeSpec(),
  4586. TemplateParamLists.data(),
  4587. TemplateParamLists.size(),
  4588. isFriend,
  4589. isExplicitSpecialization,
  4590. Invalid)) {
  4591. if (TemplateParams->size() > 0) {
  4592. // This is a function template
  4593. // Check that we can declare a template here.
  4594. if (CheckTemplateDeclScope(S, TemplateParams))
  4595. return 0;
  4596. // A destructor cannot be a template.
  4597. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  4598. Diag(NewFD->getLocation(), diag::err_destructor_template);
  4599. return 0;
  4600. }
  4601. // If we're adding a template to a dependent context, we may need to
  4602. // rebuilding some of the types used within the template parameter list,
  4603. // now that we know what the current instantiation is.
  4604. if (DC->isDependentContext()) {
  4605. ContextRAII SavedContext(*this, DC);
  4606. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  4607. Invalid = true;
  4608. }
  4609. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  4610. NewFD->getLocation(),
  4611. Name, TemplateParams,
  4612. NewFD);
  4613. FunctionTemplate->setLexicalDeclContext(CurContext);
  4614. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  4615. // For source fidelity, store the other template param lists.
  4616. if (TemplateParamLists.size() > 1) {
  4617. NewFD->setTemplateParameterListsInfo(Context,
  4618. TemplateParamLists.size() - 1,
  4619. TemplateParamLists.data());
  4620. }
  4621. } else {
  4622. // This is a function template specialization.
  4623. isFunctionTemplateSpecialization = true;
  4624. // For source fidelity, store all the template param lists.
  4625. NewFD->setTemplateParameterListsInfo(Context,
  4626. TemplateParamLists.size(),
  4627. TemplateParamLists.data());
  4628. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  4629. if (isFriend) {
  4630. // We want to remove the "template<>", found here.
  4631. SourceRange RemoveRange = TemplateParams->getSourceRange();
  4632. // If we remove the template<> and the name is not a
  4633. // template-id, we're actually silently creating a problem:
  4634. // the friend declaration will refer to an untemplated decl,
  4635. // and clearly the user wants a template specialization. So
  4636. // we need to insert '<>' after the name.
  4637. SourceLocation InsertLoc;
  4638. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  4639. InsertLoc = D.getName().getSourceRange().getEnd();
  4640. InsertLoc = PP.getLocForEndOfToken(InsertLoc);
  4641. }
  4642. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  4643. << Name << RemoveRange
  4644. << FixItHint::CreateRemoval(RemoveRange)
  4645. << FixItHint::CreateInsertion(InsertLoc, "<>");
  4646. }
  4647. }
  4648. }
  4649. else {
  4650. // All template param lists were matched against the scope specifier:
  4651. // this is NOT (an explicit specialization of) a template.
  4652. if (TemplateParamLists.size() > 0)
  4653. // For source fidelity, store all the template param lists.
  4654. NewFD->setTemplateParameterListsInfo(Context,
  4655. TemplateParamLists.size(),
  4656. TemplateParamLists.data());
  4657. }
  4658. if (Invalid) {
  4659. NewFD->setInvalidDecl();
  4660. if (FunctionTemplate)
  4661. FunctionTemplate->setInvalidDecl();
  4662. }
  4663. // C++ [dcl.fct.spec]p5:
  4664. // The virtual specifier shall only be used in declarations of
  4665. // nonstatic class member functions that appear within a
  4666. // member-specification of a class declaration; see 10.3.
  4667. //
  4668. if (isVirtual && !NewFD->isInvalidDecl()) {
  4669. if (!isVirtualOkay) {
  4670. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  4671. diag::err_virtual_non_function);
  4672. } else if (!CurContext->isRecord()) {
  4673. // 'virtual' was specified outside of the class.
  4674. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  4675. diag::err_virtual_out_of_class)
  4676. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  4677. } else if (NewFD->getDescribedFunctionTemplate()) {
  4678. // C++ [temp.mem]p3:
  4679. // A member function template shall not be virtual.
  4680. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  4681. diag::err_virtual_member_function_template)
  4682. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  4683. } else {
  4684. // Okay: Add virtual to the method.
  4685. NewFD->setVirtualAsWritten(true);
  4686. }
  4687. }
  4688. // C++ [dcl.fct.spec]p3:
  4689. // The inline specifier shall not appear on a block scope function
  4690. // declaration.
  4691. if (isInline && !NewFD->isInvalidDecl()) {
  4692. if (CurContext->isFunctionOrMethod()) {
  4693. // 'inline' is not allowed on block scope function declaration.
  4694. Diag(D.getDeclSpec().getInlineSpecLoc(),
  4695. diag::err_inline_declaration_block_scope) << Name
  4696. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  4697. }
  4698. }
  4699. // C++ [dcl.fct.spec]p6:
  4700. // The explicit specifier shall be used only in the declaration of a
  4701. // constructor or conversion function within its class definition;
  4702. // see 12.3.1 and 12.3.2.
  4703. if (isExplicit && !NewFD->isInvalidDecl()) {
  4704. if (!CurContext->isRecord()) {
  4705. // 'explicit' was specified outside of the class.
  4706. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  4707. diag::err_explicit_out_of_class)
  4708. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  4709. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  4710. !isa<CXXConversionDecl>(NewFD)) {
  4711. // 'explicit' was specified on a function that wasn't a constructor
  4712. // or conversion function.
  4713. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  4714. diag::err_explicit_non_ctor_or_conv_function)
  4715. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  4716. }
  4717. }
  4718. if (isConstexpr) {
  4719. // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
  4720. // are implicitly inline.
  4721. NewFD->setImplicitlyInline();
  4722. // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
  4723. // be either constructors or to return a literal type. Therefore,
  4724. // destructors cannot be declared constexpr.
  4725. if (isa<CXXDestructorDecl>(NewFD))
  4726. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  4727. }
  4728. // If __module_private__ was specified, mark the function accordingly.
  4729. if (D.getDeclSpec().isModulePrivateSpecified()) {
  4730. if (isFunctionTemplateSpecialization) {
  4731. SourceLocation ModulePrivateLoc
  4732. = D.getDeclSpec().getModulePrivateSpecLoc();
  4733. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  4734. << 0
  4735. << FixItHint::CreateRemoval(ModulePrivateLoc);
  4736. } else {
  4737. NewFD->setModulePrivate();
  4738. if (FunctionTemplate)
  4739. FunctionTemplate->setModulePrivate();
  4740. }
  4741. }
  4742. if (isFriend) {
  4743. // For now, claim that the objects have no previous declaration.
  4744. if (FunctionTemplate) {
  4745. FunctionTemplate->setObjectOfFriendDecl(false);
  4746. FunctionTemplate->setAccess(AS_public);
  4747. }
  4748. NewFD->setObjectOfFriendDecl(false);
  4749. NewFD->setAccess(AS_public);
  4750. }
  4751. // If a function is defined as defaulted or deleted, mark it as such now.
  4752. switch (D.getFunctionDefinitionKind()) {
  4753. case FDK_Declaration:
  4754. case FDK_Definition:
  4755. break;
  4756. case FDK_Defaulted:
  4757. NewFD->setDefaulted();
  4758. break;
  4759. case FDK_Deleted:
  4760. NewFD->setDeletedAsWritten();
  4761. break;
  4762. }
  4763. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  4764. D.isFunctionDefinition()) {
  4765. // C++ [class.mfct]p2:
  4766. // A member function may be defined (8.4) in its class definition, in
  4767. // which case it is an inline member function (7.1.2)
  4768. NewFD->setImplicitlyInline();
  4769. }
  4770. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  4771. !CurContext->isRecord()) {
  4772. // C++ [class.static]p1:
  4773. // A data or function member of a class may be declared static
  4774. // in a class definition, in which case it is a static member of
  4775. // the class.
  4776. // Complain about the 'static' specifier if it's on an out-of-line
  4777. // member function definition.
  4778. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4779. diag::err_static_out_of_line)
  4780. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  4781. }
  4782. }
  4783. // Filter out previous declarations that don't match the scope.
  4784. FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
  4785. isExplicitSpecialization ||
  4786. isFunctionTemplateSpecialization);
  4787. // Handle GNU asm-label extension (encoded as an attribute).
  4788. if (Expr *E = (Expr*) D.getAsmLabel()) {
  4789. // The parser guarantees this is a string.
  4790. StringLiteral *SE = cast<StringLiteral>(E);
  4791. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  4792. SE->getString()));
  4793. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  4794. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  4795. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  4796. if (I != ExtnameUndeclaredIdentifiers.end()) {
  4797. NewFD->addAttr(I->second);
  4798. ExtnameUndeclaredIdentifiers.erase(I);
  4799. }
  4800. }
  4801. // Copy the parameter declarations from the declarator D to the function
  4802. // declaration NewFD, if they are available. First scavenge them into Params.
  4803. SmallVector<ParmVarDecl*, 16> Params;
  4804. if (D.isFunctionDeclarator()) {
  4805. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  4806. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  4807. // function that takes no arguments, not a function that takes a
  4808. // single void argument.
  4809. // We let through "const void" here because Sema::GetTypeForDeclarator
  4810. // already checks for that case.
  4811. if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
  4812. FTI.ArgInfo[0].Param &&
  4813. cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
  4814. // Empty arg list, don't push any params.
  4815. checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
  4816. } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
  4817. for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
  4818. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
  4819. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  4820. Param->setDeclContext(NewFD);
  4821. Params.push_back(Param);
  4822. if (Param->isInvalidDecl())
  4823. NewFD->setInvalidDecl();
  4824. }
  4825. }
  4826. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  4827. // When we're declaring a function with a typedef, typeof, etc as in the
  4828. // following example, we'll need to synthesize (unnamed)
  4829. // parameters for use in the declaration.
  4830. //
  4831. // @code
  4832. // typedef void fn(int);
  4833. // fn f;
  4834. // @endcode
  4835. // Synthesize a parameter for each argument type.
  4836. for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
  4837. AE = FT->arg_type_end(); AI != AE; ++AI) {
  4838. ParmVarDecl *Param =
  4839. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
  4840. Param->setScopeInfo(0, Params.size());
  4841. Params.push_back(Param);
  4842. }
  4843. } else {
  4844. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  4845. "Should not need args for typedef of non-prototype fn");
  4846. }
  4847. // Finally, we know we have the right number of parameters, install them.
  4848. NewFD->setParams(Params);
  4849. // Find all anonymous symbols defined during the declaration of this function
  4850. // and add to NewFD. This lets us track decls such 'enum Y' in:
  4851. //
  4852. // void f(enum Y {AA} x) {}
  4853. //
  4854. // which would otherwise incorrectly end up in the translation unit scope.
  4855. NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
  4856. DeclsInPrototypeScope.clear();
  4857. // Process the non-inheritable attributes on this declaration.
  4858. ProcessDeclAttributes(S, NewFD, D,
  4859. /*NonInheritable=*/true, /*Inheritable=*/false);
  4860. // Functions returning a variably modified type violate C99 6.7.5.2p2
  4861. // because all functions have linkage.
  4862. if (!NewFD->isInvalidDecl() &&
  4863. NewFD->getResultType()->isVariablyModifiedType()) {
  4864. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  4865. NewFD->setInvalidDecl();
  4866. }
  4867. // Handle attributes.
  4868. ProcessDeclAttributes(S, NewFD, D,
  4869. /*NonInheritable=*/false, /*Inheritable=*/true);
  4870. if (!getLangOpts().CPlusPlus) {
  4871. // Perform semantic checking on the function declaration.
  4872. bool isExplicitSpecialization=false;
  4873. if (!NewFD->isInvalidDecl()) {
  4874. if (NewFD->isMain())
  4875. CheckMain(NewFD, D.getDeclSpec());
  4876. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  4877. isExplicitSpecialization));
  4878. }
  4879. // Make graceful recovery from an invalid redeclaration.
  4880. else if (!Previous.empty())
  4881. D.setRedeclaration(true);
  4882. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  4883. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  4884. "previous declaration set still overloaded");
  4885. } else {
  4886. // If the declarator is a template-id, translate the parser's template
  4887. // argument list into our AST format.
  4888. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  4889. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  4890. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  4891. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  4892. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  4893. TemplateId->NumArgs);
  4894. translateTemplateArguments(TemplateArgsPtr,
  4895. TemplateArgs);
  4896. HasExplicitTemplateArgs = true;
  4897. if (NewFD->isInvalidDecl()) {
  4898. HasExplicitTemplateArgs = false;
  4899. } else if (FunctionTemplate) {
  4900. // Function template with explicit template arguments.
  4901. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  4902. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  4903. HasExplicitTemplateArgs = false;
  4904. } else if (!isFunctionTemplateSpecialization &&
  4905. !D.getDeclSpec().isFriendSpecified()) {
  4906. // We have encountered something that the user meant to be a
  4907. // specialization (because it has explicitly-specified template
  4908. // arguments) but that was not introduced with a "template<>" (or had
  4909. // too few of them).
  4910. Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
  4911. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
  4912. << FixItHint::CreateInsertion(
  4913. D.getDeclSpec().getLocStart(),
  4914. "template<> ");
  4915. isFunctionTemplateSpecialization = true;
  4916. } else {
  4917. // "friend void foo<>(int);" is an implicit specialization decl.
  4918. isFunctionTemplateSpecialization = true;
  4919. }
  4920. } else if (isFriend && isFunctionTemplateSpecialization) {
  4921. // This combination is only possible in a recovery case; the user
  4922. // wrote something like:
  4923. // template <> friend void foo(int);
  4924. // which we're recovering from as if the user had written:
  4925. // friend void foo<>(int);
  4926. // Go ahead and fake up a template id.
  4927. HasExplicitTemplateArgs = true;
  4928. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  4929. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  4930. }
  4931. // If it's a friend (and only if it's a friend), it's possible
  4932. // that either the specialized function type or the specialized
  4933. // template is dependent, and therefore matching will fail. In
  4934. // this case, don't check the specialization yet.
  4935. bool InstantiationDependent = false;
  4936. if (isFunctionTemplateSpecialization && isFriend &&
  4937. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  4938. TemplateSpecializationType::anyDependentTemplateArguments(
  4939. TemplateArgs.getArgumentArray(), TemplateArgs.size(),
  4940. InstantiationDependent))) {
  4941. assert(HasExplicitTemplateArgs &&
  4942. "friend function specialization without template args");
  4943. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  4944. Previous))
  4945. NewFD->setInvalidDecl();
  4946. } else if (isFunctionTemplateSpecialization) {
  4947. if (CurContext->isDependentContext() && CurContext->isRecord()
  4948. && !isFriend) {
  4949. isDependentClassScopeExplicitSpecialization = true;
  4950. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  4951. diag::ext_function_specialization_in_class :
  4952. diag::err_function_specialization_in_class)
  4953. << NewFD->getDeclName();
  4954. } else if (CheckFunctionTemplateSpecialization(NewFD,
  4955. (HasExplicitTemplateArgs ? &TemplateArgs : 0),
  4956. Previous))
  4957. NewFD->setInvalidDecl();
  4958. // C++ [dcl.stc]p1:
  4959. // A storage-class-specifier shall not be specified in an explicit
  4960. // specialization (14.7.3)
  4961. if (SC != SC_None) {
  4962. if (SC != NewFD->getStorageClass())
  4963. Diag(NewFD->getLocation(),
  4964. diag::err_explicit_specialization_inconsistent_storage_class)
  4965. << SC
  4966. << FixItHint::CreateRemoval(
  4967. D.getDeclSpec().getStorageClassSpecLoc());
  4968. else
  4969. Diag(NewFD->getLocation(),
  4970. diag::ext_explicit_specialization_storage_class)
  4971. << FixItHint::CreateRemoval(
  4972. D.getDeclSpec().getStorageClassSpecLoc());
  4973. }
  4974. } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
  4975. if (CheckMemberSpecialization(NewFD, Previous))
  4976. NewFD->setInvalidDecl();
  4977. }
  4978. // Perform semantic checking on the function declaration.
  4979. if (!isDependentClassScopeExplicitSpecialization) {
  4980. if (NewFD->isInvalidDecl()) {
  4981. // If this is a class member, mark the class invalid immediately.
  4982. // This avoids some consistency errors later.
  4983. if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
  4984. methodDecl->getParent()->setInvalidDecl();
  4985. } else {
  4986. if (NewFD->isMain())
  4987. CheckMain(NewFD, D.getDeclSpec());
  4988. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  4989. isExplicitSpecialization));
  4990. }
  4991. }
  4992. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  4993. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  4994. "previous declaration set still overloaded");
  4995. NamedDecl *PrincipalDecl = (FunctionTemplate
  4996. ? cast<NamedDecl>(FunctionTemplate)
  4997. : NewFD);
  4998. if (isFriend && D.isRedeclaration()) {
  4999. AccessSpecifier Access = AS_public;
  5000. if (!NewFD->isInvalidDecl())
  5001. Access = NewFD->getPreviousDecl()->getAccess();
  5002. NewFD->setAccess(Access);
  5003. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  5004. PrincipalDecl->setObjectOfFriendDecl(true);
  5005. }
  5006. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  5007. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  5008. PrincipalDecl->setNonMemberOperator();
  5009. // If we have a function template, check the template parameter
  5010. // list. This will check and merge default template arguments.
  5011. if (FunctionTemplate) {
  5012. FunctionTemplateDecl *PrevTemplate =
  5013. FunctionTemplate->getPreviousDecl();
  5014. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  5015. PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
  5016. D.getDeclSpec().isFriendSpecified()
  5017. ? (D.isFunctionDefinition()
  5018. ? TPC_FriendFunctionTemplateDefinition
  5019. : TPC_FriendFunctionTemplate)
  5020. : (D.getCXXScopeSpec().isSet() &&
  5021. DC && DC->isRecord() &&
  5022. DC->isDependentContext())
  5023. ? TPC_ClassTemplateMember
  5024. : TPC_FunctionTemplate);
  5025. }
  5026. if (NewFD->isInvalidDecl()) {
  5027. // Ignore all the rest of this.
  5028. } else if (!D.isRedeclaration()) {
  5029. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  5030. AddToScope };
  5031. // Fake up an access specifier if it's supposed to be a class member.
  5032. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  5033. NewFD->setAccess(AS_public);
  5034. // Qualified decls generally require a previous declaration.
  5035. if (D.getCXXScopeSpec().isSet()) {
  5036. // ...with the major exception of templated-scope or
  5037. // dependent-scope friend declarations.
  5038. // TODO: we currently also suppress this check in dependent
  5039. // contexts because (1) the parameter depth will be off when
  5040. // matching friend templates and (2) we might actually be
  5041. // selecting a friend based on a dependent factor. But there
  5042. // are situations where these conditions don't apply and we
  5043. // can actually do this check immediately.
  5044. if (isFriend &&
  5045. (TemplateParamLists.size() ||
  5046. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  5047. CurContext->isDependentContext())) {
  5048. // ignore these
  5049. } else {
  5050. // The user tried to provide an out-of-line definition for a
  5051. // function that is a member of a class or namespace, but there
  5052. // was no such member function declared (C++ [class.mfct]p2,
  5053. // C++ [namespace.memdef]p2). For example:
  5054. //
  5055. // class X {
  5056. // void f() const;
  5057. // };
  5058. //
  5059. // void X::f() { } // ill-formed
  5060. //
  5061. // Complain about this problem, and attempt to suggest close
  5062. // matches (e.g., those that differ only in cv-qualifiers and
  5063. // whether the parameter types are references).
  5064. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
  5065. NewFD,
  5066. ExtraArgs)) {
  5067. AddToScope = ExtraArgs.AddToScope;
  5068. return Result;
  5069. }
  5070. }
  5071. // Unqualified local friend declarations are required to resolve
  5072. // to something.
  5073. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  5074. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
  5075. NewFD,
  5076. ExtraArgs)) {
  5077. AddToScope = ExtraArgs.AddToScope;
  5078. return Result;
  5079. }
  5080. }
  5081. } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
  5082. !isFriend && !isFunctionTemplateSpecialization &&
  5083. !isExplicitSpecialization) {
  5084. // An out-of-line member function declaration must also be a
  5085. // definition (C++ [dcl.meaning]p1).
  5086. // Note that this is not the case for explicit specializations of
  5087. // function templates or member functions of class templates, per
  5088. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  5089. // extension for compatibility with old SWIG code which likes to
  5090. // generate them.
  5091. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  5092. << D.getCXXScopeSpec().getRange();
  5093. }
  5094. }
  5095. AddKnownFunctionAttributes(NewFD);
  5096. if (NewFD->hasAttr<OverloadableAttr>() &&
  5097. !NewFD->getType()->getAs<FunctionProtoType>()) {
  5098. Diag(NewFD->getLocation(),
  5099. diag::err_attribute_overloadable_no_prototype)
  5100. << NewFD;
  5101. // Turn this into a variadic function with no parameters.
  5102. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  5103. FunctionProtoType::ExtProtoInfo EPI;
  5104. EPI.Variadic = true;
  5105. EPI.ExtInfo = FT->getExtInfo();
  5106. QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
  5107. NewFD->setType(R);
  5108. }
  5109. // If there's a #pragma GCC visibility in scope, and this isn't a class
  5110. // member, set the visibility of this function.
  5111. if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
  5112. AddPushedVisibilityAttribute(NewFD);
  5113. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  5114. // marking the function.
  5115. AddCFAuditedAttribute(NewFD);
  5116. // If this is a locally-scoped extern C function, update the
  5117. // map of such names.
  5118. if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
  5119. && !NewFD->isInvalidDecl())
  5120. RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
  5121. // Set this FunctionDecl's range up to the right paren.
  5122. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  5123. if (getLangOpts().CPlusPlus) {
  5124. if (FunctionTemplate) {
  5125. if (NewFD->isInvalidDecl())
  5126. FunctionTemplate->setInvalidDecl();
  5127. return FunctionTemplate;
  5128. }
  5129. }
  5130. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  5131. if ((getLangOpts().OpenCLVersion >= 120)
  5132. && NewFD->hasAttr<OpenCLKernelAttr>()
  5133. && (SC == SC_Static)) {
  5134. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  5135. D.setInvalidType();
  5136. }
  5137. MarkUnusedFileScopedDecl(NewFD);
  5138. if (getLangOpts().CUDA)
  5139. if (IdentifierInfo *II = NewFD->getIdentifier())
  5140. if (!NewFD->isInvalidDecl() &&
  5141. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5142. if (II->isStr("cudaConfigureCall")) {
  5143. if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
  5144. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  5145. Context.setcudaConfigureCallDecl(NewFD);
  5146. }
  5147. }
  5148. // Here we have an function template explicit specialization at class scope.
  5149. // The actually specialization will be postponed to template instatiation
  5150. // time via the ClassScopeFunctionSpecializationDecl node.
  5151. if (isDependentClassScopeExplicitSpecialization) {
  5152. ClassScopeFunctionSpecializationDecl *NewSpec =
  5153. ClassScopeFunctionSpecializationDecl::Create(
  5154. Context, CurContext, SourceLocation(),
  5155. cast<CXXMethodDecl>(NewFD),
  5156. HasExplicitTemplateArgs, TemplateArgs);
  5157. CurContext->addDecl(NewSpec);
  5158. AddToScope = false;
  5159. }
  5160. return NewFD;
  5161. }
  5162. /// \brief Perform semantic checking of a new function declaration.
  5163. ///
  5164. /// Performs semantic analysis of the new function declaration
  5165. /// NewFD. This routine performs all semantic checking that does not
  5166. /// require the actual declarator involved in the declaration, and is
  5167. /// used both for the declaration of functions as they are parsed
  5168. /// (called via ActOnDeclarator) and for the declaration of functions
  5169. /// that have been instantiated via C++ template instantiation (called
  5170. /// via InstantiateDecl).
  5171. ///
  5172. /// \param IsExplicitSpecialization whether this new function declaration is
  5173. /// an explicit specialization of the previous declaration.
  5174. ///
  5175. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  5176. ///
  5177. /// \returns true if the function declaration is a redeclaration.
  5178. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  5179. LookupResult &Previous,
  5180. bool IsExplicitSpecialization) {
  5181. assert(!NewFD->getResultType()->isVariablyModifiedType()
  5182. && "Variably modified return types are not handled here");
  5183. // Check for a previous declaration of this name.
  5184. if (Previous.empty() && NewFD->isExternC()) {
  5185. // Since we did not find anything by this name and we're declaring
  5186. // an extern "C" function, look for a non-visible extern "C"
  5187. // declaration with the same name.
  5188. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  5189. = findLocallyScopedExternalDecl(NewFD->getDeclName());
  5190. if (Pos != LocallyScopedExternalDecls.end())
  5191. Previous.addDecl(Pos->second);
  5192. }
  5193. bool Redeclaration = false;
  5194. // Merge or overload the declaration with an existing declaration of
  5195. // the same name, if appropriate.
  5196. if (!Previous.empty()) {
  5197. // Determine whether NewFD is an overload of PrevDecl or
  5198. // a declaration that requires merging. If it's an overload,
  5199. // there's no more work to do here; we'll just add the new
  5200. // function to the scope.
  5201. NamedDecl *OldDecl = 0;
  5202. if (!AllowOverloadingOfFunction(Previous, Context)) {
  5203. Redeclaration = true;
  5204. OldDecl = Previous.getFoundDecl();
  5205. } else {
  5206. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  5207. /*NewIsUsingDecl*/ false)) {
  5208. case Ovl_Match:
  5209. Redeclaration = true;
  5210. break;
  5211. case Ovl_NonFunction:
  5212. Redeclaration = true;
  5213. break;
  5214. case Ovl_Overload:
  5215. Redeclaration = false;
  5216. break;
  5217. }
  5218. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  5219. // If a function name is overloadable in C, then every function
  5220. // with that name must be marked "overloadable".
  5221. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  5222. << Redeclaration << NewFD;
  5223. NamedDecl *OverloadedDecl = 0;
  5224. if (Redeclaration)
  5225. OverloadedDecl = OldDecl;
  5226. else if (!Previous.empty())
  5227. OverloadedDecl = Previous.getRepresentativeDecl();
  5228. if (OverloadedDecl)
  5229. Diag(OverloadedDecl->getLocation(),
  5230. diag::note_attribute_overloadable_prev_overload);
  5231. NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
  5232. Context));
  5233. }
  5234. }
  5235. if (Redeclaration) {
  5236. // NewFD and OldDecl represent declarations that need to be
  5237. // merged.
  5238. if (MergeFunctionDecl(NewFD, OldDecl, S)) {
  5239. NewFD->setInvalidDecl();
  5240. return Redeclaration;
  5241. }
  5242. Previous.clear();
  5243. Previous.addDecl(OldDecl);
  5244. if (FunctionTemplateDecl *OldTemplateDecl
  5245. = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  5246. NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
  5247. FunctionTemplateDecl *NewTemplateDecl
  5248. = NewFD->getDescribedFunctionTemplate();
  5249. assert(NewTemplateDecl && "Template/non-template mismatch");
  5250. if (CXXMethodDecl *Method
  5251. = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
  5252. Method->setAccess(OldTemplateDecl->getAccess());
  5253. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  5254. }
  5255. // If this is an explicit specialization of a member that is a function
  5256. // template, mark it as a member specialization.
  5257. if (IsExplicitSpecialization &&
  5258. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  5259. NewTemplateDecl->setMemberSpecialization();
  5260. assert(OldTemplateDecl->isMemberSpecialization());
  5261. }
  5262. } else {
  5263. if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
  5264. NewFD->setAccess(OldDecl->getAccess());
  5265. NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
  5266. }
  5267. }
  5268. }
  5269. // Semantic checking for this function declaration (in isolation).
  5270. if (getLangOpts().CPlusPlus) {
  5271. // C++-specific checks.
  5272. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  5273. CheckConstructor(Constructor);
  5274. } else if (CXXDestructorDecl *Destructor =
  5275. dyn_cast<CXXDestructorDecl>(NewFD)) {
  5276. CXXRecordDecl *Record = Destructor->getParent();
  5277. QualType ClassType = Context.getTypeDeclType(Record);
  5278. // FIXME: Shouldn't we be able to perform this check even when the class
  5279. // type is dependent? Both gcc and edg can handle that.
  5280. if (!ClassType->isDependentType()) {
  5281. DeclarationName Name
  5282. = Context.DeclarationNames.getCXXDestructorName(
  5283. Context.getCanonicalType(ClassType));
  5284. if (NewFD->getDeclName() != Name) {
  5285. Diag(NewFD->getLocation(), diag::err_destructor_name);
  5286. NewFD->setInvalidDecl();
  5287. return Redeclaration;
  5288. }
  5289. }
  5290. } else if (CXXConversionDecl *Conversion
  5291. = dyn_cast<CXXConversionDecl>(NewFD)) {
  5292. ActOnConversionDeclarator(Conversion);
  5293. }
  5294. // Find any virtual functions that this function overrides.
  5295. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  5296. if (!Method->isFunctionTemplateSpecialization() &&
  5297. !Method->getDescribedFunctionTemplate()) {
  5298. if (AddOverriddenMethods(Method->getParent(), Method)) {
  5299. // If the function was marked as "static", we have a problem.
  5300. if (NewFD->getStorageClass() == SC_Static) {
  5301. Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
  5302. << NewFD->getDeclName();
  5303. for (CXXMethodDecl::method_iterator
  5304. Overridden = Method->begin_overridden_methods(),
  5305. OverriddenEnd = Method->end_overridden_methods();
  5306. Overridden != OverriddenEnd;
  5307. ++Overridden) {
  5308. Diag((*Overridden)->getLocation(),
  5309. diag::note_overridden_virtual_function);
  5310. }
  5311. }
  5312. }
  5313. }
  5314. if (Method->isStatic())
  5315. checkThisInStaticMemberFunctionType(Method);
  5316. }
  5317. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  5318. if (NewFD->isOverloadedOperator() &&
  5319. CheckOverloadedOperatorDeclaration(NewFD)) {
  5320. NewFD->setInvalidDecl();
  5321. return Redeclaration;
  5322. }
  5323. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  5324. if (NewFD->getLiteralIdentifier() &&
  5325. CheckLiteralOperatorDeclaration(NewFD)) {
  5326. NewFD->setInvalidDecl();
  5327. return Redeclaration;
  5328. }
  5329. // In C++, check default arguments now that we have merged decls. Unless
  5330. // the lexical context is the class, because in this case this is done
  5331. // during delayed parsing anyway.
  5332. if (!CurContext->isRecord())
  5333. CheckCXXDefaultArguments(NewFD);
  5334. // If this function declares a builtin function, check the type of this
  5335. // declaration against the expected type for the builtin.
  5336. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  5337. ASTContext::GetBuiltinTypeError Error;
  5338. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  5339. if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
  5340. // The type of this function differs from the type of the builtin,
  5341. // so forget about the builtin entirely.
  5342. Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
  5343. }
  5344. }
  5345. // If this function is declared as being extern "C", then check to see if
  5346. // the function returns a UDT (class, struct, or union type) that is not C
  5347. // compatible, and if it does, warn the user.
  5348. if (NewFD->isExternC()) {
  5349. QualType R = NewFD->getResultType();
  5350. if (R->isIncompleteType() && !R->isVoidType())
  5351. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  5352. << NewFD << R;
  5353. else if (!R.isPODType(Context) && !R->isVoidType() &&
  5354. !R->isObjCObjectPointerType())
  5355. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  5356. }
  5357. }
  5358. return Redeclaration;
  5359. }
  5360. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  5361. // C++11 [basic.start.main]p3: A program that declares main to be inline,
  5362. // static or constexpr is ill-formed.
  5363. // C99 6.7.4p4: In a hosted environment, the inline function specifier
  5364. // shall not appear in a declaration of main.
  5365. // static main is not an error under C99, but we should warn about it.
  5366. if (FD->getStorageClass() == SC_Static)
  5367. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  5368. ? diag::err_static_main : diag::warn_static_main)
  5369. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  5370. if (FD->isInlineSpecified())
  5371. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  5372. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  5373. if (FD->isConstexpr()) {
  5374. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  5375. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  5376. FD->setConstexpr(false);
  5377. }
  5378. QualType T = FD->getType();
  5379. assert(T->isFunctionType() && "function decl is not of function type");
  5380. const FunctionType* FT = T->castAs<FunctionType>();
  5381. // All the standards say that main() should should return 'int'.
  5382. if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
  5383. // In C and C++, main magically returns 0 if you fall off the end;
  5384. // set the flag which tells us that.
  5385. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  5386. FD->setHasImplicitReturnZero(true);
  5387. // In C with GNU extensions we allow main() to have non-integer return
  5388. // type, but we should warn about the extension, and we disable the
  5389. // implicit-return-zero rule.
  5390. } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  5391. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  5392. // Otherwise, this is just a flat-out error.
  5393. } else {
  5394. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
  5395. FD->setInvalidDecl(true);
  5396. }
  5397. // Treat protoless main() as nullary.
  5398. if (isa<FunctionNoProtoType>(FT)) return;
  5399. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  5400. unsigned nparams = FTP->getNumArgs();
  5401. assert(FD->getNumParams() == nparams);
  5402. bool HasExtraParameters = (nparams > 3);
  5403. // Darwin passes an undocumented fourth argument of type char**. If
  5404. // other platforms start sprouting these, the logic below will start
  5405. // getting shifty.
  5406. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  5407. HasExtraParameters = false;
  5408. if (HasExtraParameters) {
  5409. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  5410. FD->setInvalidDecl(true);
  5411. nparams = 3;
  5412. }
  5413. // FIXME: a lot of the following diagnostics would be improved
  5414. // if we had some location information about types.
  5415. QualType CharPP =
  5416. Context.getPointerType(Context.getPointerType(Context.CharTy));
  5417. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  5418. for (unsigned i = 0; i < nparams; ++i) {
  5419. QualType AT = FTP->getArgType(i);
  5420. bool mismatch = true;
  5421. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  5422. mismatch = false;
  5423. else if (Expected[i] == CharPP) {
  5424. // As an extension, the following forms are okay:
  5425. // char const **
  5426. // char const * const *
  5427. // char * const *
  5428. QualifierCollector qs;
  5429. const PointerType* PT;
  5430. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  5431. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  5432. (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
  5433. qs.removeConst();
  5434. mismatch = !qs.empty();
  5435. }
  5436. }
  5437. if (mismatch) {
  5438. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  5439. // TODO: suggest replacing given type with expected type
  5440. FD->setInvalidDecl(true);
  5441. }
  5442. }
  5443. if (nparams == 1 && !FD->isInvalidDecl()) {
  5444. Diag(FD->getLocation(), diag::warn_main_one_arg);
  5445. }
  5446. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  5447. Diag(FD->getLocation(), diag::err_main_template_decl);
  5448. FD->setInvalidDecl();
  5449. }
  5450. }
  5451. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  5452. // FIXME: Need strict checking. In C89, we need to check for
  5453. // any assignment, increment, decrement, function-calls, or
  5454. // commas outside of a sizeof. In C99, it's the same list,
  5455. // except that the aforementioned are allowed in unevaluated
  5456. // expressions. Everything else falls under the
  5457. // "may accept other forms of constant expressions" exception.
  5458. // (We never end up here for C++, so the constant expression
  5459. // rules there don't matter.)
  5460. if (Init->isConstantInitializer(Context, false))
  5461. return false;
  5462. Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
  5463. << Init->getSourceRange();
  5464. return true;
  5465. }
  5466. namespace {
  5467. // Visits an initialization expression to see if OrigDecl is evaluated in
  5468. // its own initialization and throws a warning if it does.
  5469. class SelfReferenceChecker
  5470. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  5471. Sema &S;
  5472. Decl *OrigDecl;
  5473. bool isRecordType;
  5474. bool isPODType;
  5475. bool isReferenceType;
  5476. public:
  5477. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  5478. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  5479. S(S), OrigDecl(OrigDecl) {
  5480. isPODType = false;
  5481. isRecordType = false;
  5482. isReferenceType = false;
  5483. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  5484. isPODType = VD->getType().isPODType(S.Context);
  5485. isRecordType = VD->getType()->isRecordType();
  5486. isReferenceType = VD->getType()->isReferenceType();
  5487. }
  5488. }
  5489. // Sometimes, the expression passed in lacks the casts that are used
  5490. // to determine which DeclRefExpr's to check. Assume that the casts
  5491. // are present and continue visiting the expression.
  5492. void HandleExpr(Expr *E) {
  5493. // Skip checking T a = a where T is not a record or reference type.
  5494. // Doing so is a way to silence uninitialized warnings.
  5495. if (isRecordType || isReferenceType)
  5496. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  5497. HandleDeclRefExpr(DRE);
  5498. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  5499. HandleValue(CO->getTrueExpr());
  5500. HandleValue(CO->getFalseExpr());
  5501. }
  5502. Visit(E);
  5503. }
  5504. // For most expressions, the cast is directly above the DeclRefExpr.
  5505. // For conditional operators, the cast can be outside the conditional
  5506. // operator if both expressions are DeclRefExpr's.
  5507. void HandleValue(Expr *E) {
  5508. E = E->IgnoreParenImpCasts();
  5509. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  5510. HandleDeclRefExpr(DRE);
  5511. return;
  5512. }
  5513. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  5514. HandleValue(CO->getTrueExpr());
  5515. HandleValue(CO->getFalseExpr());
  5516. }
  5517. }
  5518. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  5519. if ((!isRecordType && E->getCastKind() == CK_LValueToRValue) ||
  5520. (isRecordType && E->getCastKind() == CK_NoOp))
  5521. HandleValue(E->getSubExpr());
  5522. Inherited::VisitImplicitCastExpr(E);
  5523. }
  5524. void VisitMemberExpr(MemberExpr *E) {
  5525. // Don't warn on arrays since they can be treated as pointers.
  5526. if (E->getType()->canDecayToPointerType()) return;
  5527. ValueDecl *VD = E->getMemberDecl();
  5528. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(VD);
  5529. if (isa<FieldDecl>(VD) || (MD && !MD->isStatic()))
  5530. if (DeclRefExpr *DRE
  5531. = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) {
  5532. HandleDeclRefExpr(DRE);
  5533. return;
  5534. }
  5535. Inherited::VisitMemberExpr(E);
  5536. }
  5537. void VisitUnaryOperator(UnaryOperator *E) {
  5538. // For POD record types, addresses of its own members are well-defined.
  5539. if (E->getOpcode() == UO_AddrOf && isRecordType && isPODType &&
  5540. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) return;
  5541. Inherited::VisitUnaryOperator(E);
  5542. }
  5543. void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
  5544. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  5545. Decl* ReferenceDecl = DRE->getDecl();
  5546. if (OrigDecl != ReferenceDecl) return;
  5547. unsigned diag = isReferenceType
  5548. ? diag::warn_uninit_self_reference_in_reference_init
  5549. : diag::warn_uninit_self_reference_in_init;
  5550. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  5551. S.PDiag(diag)
  5552. << DRE->getNameInfo().getName()
  5553. << OrigDecl->getLocation()
  5554. << DRE->getSourceRange());
  5555. }
  5556. };
  5557. }
  5558. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  5559. void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) {
  5560. SelfReferenceChecker(*this, OrigDecl).HandleExpr(E);
  5561. }
  5562. /// AddInitializerToDecl - Adds the initializer Init to the
  5563. /// declaration dcl. If DirectInit is true, this is C++ direct
  5564. /// initialization rather than copy initialization.
  5565. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
  5566. bool DirectInit, bool TypeMayContainAuto) {
  5567. // If there is no declaration, there was an error parsing it. Just ignore
  5568. // the initializer.
  5569. if (RealDecl == 0 || RealDecl->isInvalidDecl())
  5570. return;
  5571. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  5572. // With declarators parsed the way they are, the parser cannot
  5573. // distinguish between a normal initializer and a pure-specifier.
  5574. // Thus this grotesque test.
  5575. IntegerLiteral *IL;
  5576. if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
  5577. Context.getCanonicalType(IL->getType()) == Context.IntTy)
  5578. CheckPureMethod(Method, Init->getSourceRange());
  5579. else {
  5580. Diag(Method->getLocation(), diag::err_member_function_initialization)
  5581. << Method->getDeclName() << Init->getSourceRange();
  5582. Method->setInvalidDecl();
  5583. }
  5584. return;
  5585. }
  5586. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  5587. if (!VDecl) {
  5588. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  5589. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  5590. RealDecl->setInvalidDecl();
  5591. return;
  5592. }
  5593. // Check for self-references within variable initializers.
  5594. // Variables declared within a function/method body (except for references)
  5595. // are handled by a dataflow analysis.
  5596. // Record types initialized by initializer list are handled here.
  5597. // Initialization by constructors are handled in TryConstructorInitialization.
  5598. if ((!VDecl->hasLocalStorage() || VDecl->getType()->isReferenceType()) &&
  5599. (isa<InitListExpr>(Init) || !VDecl->getType()->isRecordType()))
  5600. CheckSelfReference(RealDecl, Init);
  5601. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  5602. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  5603. AutoType *Auto = 0;
  5604. if (TypeMayContainAuto &&
  5605. (Auto = VDecl->getType()->getContainedAutoType()) &&
  5606. !Auto->isDeduced()) {
  5607. Expr *DeduceInit = Init;
  5608. // Initializer could be a C++ direct-initializer. Deduction only works if it
  5609. // contains exactly one expression.
  5610. if (CXXDirectInit) {
  5611. if (CXXDirectInit->getNumExprs() == 0) {
  5612. // It isn't possible to write this directly, but it is possible to
  5613. // end up in this situation with "auto x(some_pack...);"
  5614. Diag(CXXDirectInit->getLocStart(),
  5615. diag::err_auto_var_init_no_expression)
  5616. << VDecl->getDeclName() << VDecl->getType()
  5617. << VDecl->getSourceRange();
  5618. RealDecl->setInvalidDecl();
  5619. return;
  5620. } else if (CXXDirectInit->getNumExprs() > 1) {
  5621. Diag(CXXDirectInit->getExpr(1)->getLocStart(),
  5622. diag::err_auto_var_init_multiple_expressions)
  5623. << VDecl->getDeclName() << VDecl->getType()
  5624. << VDecl->getSourceRange();
  5625. RealDecl->setInvalidDecl();
  5626. return;
  5627. } else {
  5628. DeduceInit = CXXDirectInit->getExpr(0);
  5629. }
  5630. }
  5631. TypeSourceInfo *DeducedType = 0;
  5632. if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
  5633. DAR_Failed)
  5634. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  5635. if (!DeducedType) {
  5636. RealDecl->setInvalidDecl();
  5637. return;
  5638. }
  5639. VDecl->setTypeSourceInfo(DeducedType);
  5640. VDecl->setType(DeducedType->getType());
  5641. VDecl->ClearLinkageCache();
  5642. // In ARC, infer lifetime.
  5643. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  5644. VDecl->setInvalidDecl();
  5645. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  5646. // 'id' instead of a specific object type prevents most of our usual checks.
  5647. // We only want to warn outside of template instantiations, though:
  5648. // inside a template, the 'id' could have come from a parameter.
  5649. if (ActiveTemplateInstantiations.empty() &&
  5650. DeducedType->getType()->isObjCIdType()) {
  5651. SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc();
  5652. Diag(Loc, diag::warn_auto_var_is_id)
  5653. << VDecl->getDeclName() << DeduceInit->getSourceRange();
  5654. }
  5655. // If this is a redeclaration, check that the type we just deduced matches
  5656. // the previously declared type.
  5657. if (VarDecl *Old = VDecl->getPreviousDecl())
  5658. MergeVarDeclTypes(VDecl, Old);
  5659. }
  5660. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  5661. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  5662. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  5663. VDecl->setInvalidDecl();
  5664. return;
  5665. }
  5666. if (!VDecl->getType()->isDependentType()) {
  5667. // A definition must end up with a complete type, which means it must be
  5668. // complete with the restriction that an array type might be completed by
  5669. // the initializer; note that later code assumes this restriction.
  5670. QualType BaseDeclType = VDecl->getType();
  5671. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  5672. BaseDeclType = Array->getElementType();
  5673. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  5674. diag::err_typecheck_decl_incomplete_type)) {
  5675. RealDecl->setInvalidDecl();
  5676. return;
  5677. }
  5678. // The variable can not have an abstract class type.
  5679. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  5680. diag::err_abstract_type_in_decl,
  5681. AbstractVariableType))
  5682. VDecl->setInvalidDecl();
  5683. }
  5684. const VarDecl *Def;
  5685. if ((Def = VDecl->getDefinition()) && Def != VDecl) {
  5686. Diag(VDecl->getLocation(), diag::err_redefinition)
  5687. << VDecl->getDeclName();
  5688. Diag(Def->getLocation(), diag::note_previous_definition);
  5689. VDecl->setInvalidDecl();
  5690. return;
  5691. }
  5692. const VarDecl* PrevInit = 0;
  5693. if (getLangOpts().CPlusPlus) {
  5694. // C++ [class.static.data]p4
  5695. // If a static data member is of const integral or const
  5696. // enumeration type, its declaration in the class definition can
  5697. // specify a constant-initializer which shall be an integral
  5698. // constant expression (5.19). In that case, the member can appear
  5699. // in integral constant expressions. The member shall still be
  5700. // defined in a namespace scope if it is used in the program and the
  5701. // namespace scope definition shall not contain an initializer.
  5702. //
  5703. // We already performed a redefinition check above, but for static
  5704. // data members we also need to check whether there was an in-class
  5705. // declaration with an initializer.
  5706. if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
  5707. Diag(VDecl->getLocation(), diag::err_redefinition)
  5708. << VDecl->getDeclName();
  5709. Diag(PrevInit->getLocation(), diag::note_previous_definition);
  5710. return;
  5711. }
  5712. if (VDecl->hasLocalStorage())
  5713. getCurFunction()->setHasBranchProtectedScope();
  5714. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  5715. VDecl->setInvalidDecl();
  5716. return;
  5717. }
  5718. }
  5719. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  5720. // a kernel function cannot be initialized."
  5721. if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
  5722. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  5723. VDecl->setInvalidDecl();
  5724. return;
  5725. }
  5726. // Get the decls type and save a reference for later, since
  5727. // CheckInitializerTypes may change it.
  5728. QualType DclT = VDecl->getType(), SavT = DclT;
  5729. // Top-level message sends default to 'id' when we're in a debugger
  5730. // and we are assigning it to a variable of 'id' type.
  5731. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
  5732. if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
  5733. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  5734. if (Result.isInvalid()) {
  5735. VDecl->setInvalidDecl();
  5736. return;
  5737. }
  5738. Init = Result.take();
  5739. }
  5740. // Perform the initialization.
  5741. if (!VDecl->isInvalidDecl()) {
  5742. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  5743. InitializationKind Kind
  5744. = DirectInit ?
  5745. CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
  5746. Init->getLocStart(),
  5747. Init->getLocEnd())
  5748. : InitializationKind::CreateDirectList(
  5749. VDecl->getLocation())
  5750. : InitializationKind::CreateCopy(VDecl->getLocation(),
  5751. Init->getLocStart());
  5752. Expr **Args = &Init;
  5753. unsigned NumArgs = 1;
  5754. if (CXXDirectInit) {
  5755. Args = CXXDirectInit->getExprs();
  5756. NumArgs = CXXDirectInit->getNumExprs();
  5757. }
  5758. InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
  5759. ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
  5760. MultiExprArg(Args, NumArgs), &DclT);
  5761. if (Result.isInvalid()) {
  5762. VDecl->setInvalidDecl();
  5763. return;
  5764. }
  5765. Init = Result.takeAs<Expr>();
  5766. }
  5767. // If the type changed, it means we had an incomplete type that was
  5768. // completed by the initializer. For example:
  5769. // int ary[] = { 1, 3, 5 };
  5770. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  5771. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  5772. VDecl->setType(DclT);
  5773. // Check any implicit conversions within the expression.
  5774. CheckImplicitConversions(Init, VDecl->getLocation());
  5775. if (!VDecl->isInvalidDecl()) {
  5776. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  5777. if (VDecl->hasAttr<BlocksAttr>())
  5778. checkRetainCycles(VDecl, Init);
  5779. }
  5780. Init = MaybeCreateExprWithCleanups(Init);
  5781. // Attach the initializer to the decl.
  5782. VDecl->setInit(Init);
  5783. if (VDecl->isLocalVarDecl()) {
  5784. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  5785. // static storage duration shall be constant expressions or string literals.
  5786. // C++ does not have this restriction.
  5787. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
  5788. VDecl->getStorageClass() == SC_Static)
  5789. CheckForConstantInitializer(Init, DclT);
  5790. } else if (VDecl->isStaticDataMember() &&
  5791. VDecl->getLexicalDeclContext()->isRecord()) {
  5792. // This is an in-class initialization for a static data member, e.g.,
  5793. //
  5794. // struct S {
  5795. // static const int value = 17;
  5796. // };
  5797. // C++ [class.mem]p4:
  5798. // A member-declarator can contain a constant-initializer only
  5799. // if it declares a static member (9.4) of const integral or
  5800. // const enumeration type, see 9.4.2.
  5801. //
  5802. // C++11 [class.static.data]p3:
  5803. // If a non-volatile const static data member is of integral or
  5804. // enumeration type, its declaration in the class definition can
  5805. // specify a brace-or-equal-initializer in which every initalizer-clause
  5806. // that is an assignment-expression is a constant expression. A static
  5807. // data member of literal type can be declared in the class definition
  5808. // with the constexpr specifier; if so, its declaration shall specify a
  5809. // brace-or-equal-initializer in which every initializer-clause that is
  5810. // an assignment-expression is a constant expression.
  5811. // Do nothing on dependent types.
  5812. if (DclT->isDependentType()) {
  5813. // Allow any 'static constexpr' members, whether or not they are of literal
  5814. // type. We separately check that every constexpr variable is of literal
  5815. // type.
  5816. } else if (VDecl->isConstexpr()) {
  5817. // Require constness.
  5818. } else if (!DclT.isConstQualified()) {
  5819. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  5820. << Init->getSourceRange();
  5821. VDecl->setInvalidDecl();
  5822. // We allow integer constant expressions in all cases.
  5823. } else if (DclT->isIntegralOrEnumerationType()) {
  5824. // Check whether the expression is a constant expression.
  5825. SourceLocation Loc;
  5826. if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified())
  5827. // In C++11, a non-constexpr const static data member with an
  5828. // in-class initializer cannot be volatile.
  5829. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  5830. else if (Init->isValueDependent())
  5831. ; // Nothing to check.
  5832. else if (Init->isIntegerConstantExpr(Context, &Loc))
  5833. ; // Ok, it's an ICE!
  5834. else if (Init->isEvaluatable(Context)) {
  5835. // If we can constant fold the initializer through heroics, accept it,
  5836. // but report this as a use of an extension for -pedantic.
  5837. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  5838. << Init->getSourceRange();
  5839. } else {
  5840. // Otherwise, this is some crazy unknown case. Report the issue at the
  5841. // location provided by the isIntegerConstantExpr failed check.
  5842. Diag(Loc, diag::err_in_class_initializer_non_constant)
  5843. << Init->getSourceRange();
  5844. VDecl->setInvalidDecl();
  5845. }
  5846. // We allow foldable floating-point constants as an extension.
  5847. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  5848. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  5849. << DclT << Init->getSourceRange();
  5850. if (getLangOpts().CPlusPlus0x)
  5851. Diag(VDecl->getLocation(),
  5852. diag::note_in_class_initializer_float_type_constexpr)
  5853. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  5854. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  5855. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  5856. << Init->getSourceRange();
  5857. VDecl->setInvalidDecl();
  5858. }
  5859. // Suggest adding 'constexpr' in C++11 for literal types.
  5860. } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) {
  5861. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  5862. << DclT << Init->getSourceRange()
  5863. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  5864. VDecl->setConstexpr(true);
  5865. } else {
  5866. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  5867. << DclT << Init->getSourceRange();
  5868. VDecl->setInvalidDecl();
  5869. }
  5870. } else if (VDecl->isFileVarDecl()) {
  5871. if (VDecl->getStorageClassAsWritten() == SC_Extern &&
  5872. (!getLangOpts().CPlusPlus ||
  5873. !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
  5874. Diag(VDecl->getLocation(), diag::warn_extern_init);
  5875. // C99 6.7.8p4. All file scoped initializers need to be constant.
  5876. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  5877. CheckForConstantInitializer(Init, DclT);
  5878. }
  5879. // We will represent direct-initialization similarly to copy-initialization:
  5880. // int x(1); -as-> int x = 1;
  5881. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  5882. //
  5883. // Clients that want to distinguish between the two forms, can check for
  5884. // direct initializer using VarDecl::getInitStyle().
  5885. // A major benefit is that clients that don't particularly care about which
  5886. // exactly form was it (like the CodeGen) can handle both cases without
  5887. // special case code.
  5888. // C++ 8.5p11:
  5889. // The form of initialization (using parentheses or '=') is generally
  5890. // insignificant, but does matter when the entity being initialized has a
  5891. // class type.
  5892. if (CXXDirectInit) {
  5893. assert(DirectInit && "Call-style initializer must be direct init.");
  5894. VDecl->setInitStyle(VarDecl::CallInit);
  5895. } else if (DirectInit) {
  5896. // This must be list-initialization. No other way is direct-initialization.
  5897. VDecl->setInitStyle(VarDecl::ListInit);
  5898. }
  5899. CheckCompleteVariableDeclaration(VDecl);
  5900. }
  5901. /// ActOnInitializerError - Given that there was an error parsing an
  5902. /// initializer for the given declaration, try to return to some form
  5903. /// of sanity.
  5904. void Sema::ActOnInitializerError(Decl *D) {
  5905. // Our main concern here is re-establishing invariants like "a
  5906. // variable's type is either dependent or complete".
  5907. if (!D || D->isInvalidDecl()) return;
  5908. VarDecl *VD = dyn_cast<VarDecl>(D);
  5909. if (!VD) return;
  5910. // Auto types are meaningless if we can't make sense of the initializer.
  5911. if (ParsingInitForAutoVars.count(D)) {
  5912. D->setInvalidDecl();
  5913. return;
  5914. }
  5915. QualType Ty = VD->getType();
  5916. if (Ty->isDependentType()) return;
  5917. // Require a complete type.
  5918. if (RequireCompleteType(VD->getLocation(),
  5919. Context.getBaseElementType(Ty),
  5920. diag::err_typecheck_decl_incomplete_type)) {
  5921. VD->setInvalidDecl();
  5922. return;
  5923. }
  5924. // Require an abstract type.
  5925. if (RequireNonAbstractType(VD->getLocation(), Ty,
  5926. diag::err_abstract_type_in_decl,
  5927. AbstractVariableType)) {
  5928. VD->setInvalidDecl();
  5929. return;
  5930. }
  5931. // Don't bother complaining about constructors or destructors,
  5932. // though.
  5933. }
  5934. void Sema::ActOnUninitializedDecl(Decl *RealDecl,
  5935. bool TypeMayContainAuto) {
  5936. // If there is no declaration, there was an error parsing it. Just ignore it.
  5937. if (RealDecl == 0)
  5938. return;
  5939. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  5940. QualType Type = Var->getType();
  5941. // C++11 [dcl.spec.auto]p3
  5942. if (TypeMayContainAuto && Type->getContainedAutoType()) {
  5943. Diag(Var->getLocation(), diag::err_auto_var_requires_init)
  5944. << Var->getDeclName() << Type;
  5945. Var->setInvalidDecl();
  5946. return;
  5947. }
  5948. // C++11 [class.static.data]p3: A static data member can be declared with
  5949. // the constexpr specifier; if so, its declaration shall specify
  5950. // a brace-or-equal-initializer.
  5951. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  5952. // the definition of a variable [...] or the declaration of a static data
  5953. // member.
  5954. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
  5955. if (Var->isStaticDataMember())
  5956. Diag(Var->getLocation(),
  5957. diag::err_constexpr_static_mem_var_requires_init)
  5958. << Var->getDeclName();
  5959. else
  5960. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  5961. Var->setInvalidDecl();
  5962. return;
  5963. }
  5964. switch (Var->isThisDeclarationADefinition()) {
  5965. case VarDecl::Definition:
  5966. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  5967. break;
  5968. // We have an out-of-line definition of a static data member
  5969. // that has an in-class initializer, so we type-check this like
  5970. // a declaration.
  5971. //
  5972. // Fall through
  5973. case VarDecl::DeclarationOnly:
  5974. // It's only a declaration.
  5975. // Block scope. C99 6.7p7: If an identifier for an object is
  5976. // declared with no linkage (C99 6.2.2p6), the type for the
  5977. // object shall be complete.
  5978. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  5979. !Var->getLinkage() && !Var->isInvalidDecl() &&
  5980. RequireCompleteType(Var->getLocation(), Type,
  5981. diag::err_typecheck_decl_incomplete_type))
  5982. Var->setInvalidDecl();
  5983. // Make sure that the type is not abstract.
  5984. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  5985. RequireNonAbstractType(Var->getLocation(), Type,
  5986. diag::err_abstract_type_in_decl,
  5987. AbstractVariableType))
  5988. Var->setInvalidDecl();
  5989. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  5990. Var->getStorageClass() == SC_PrivateExtern) {
  5991. Diag(Var->getLocation(), diag::warn_private_extern);
  5992. Diag(Var->getLocation(), diag::note_private_extern);
  5993. }
  5994. return;
  5995. case VarDecl::TentativeDefinition:
  5996. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  5997. // object that has file scope without an initializer, and without a
  5998. // storage-class specifier or with the storage-class specifier "static",
  5999. // constitutes a tentative definition. Note: A tentative definition with
  6000. // external linkage is valid (C99 6.2.2p5).
  6001. if (!Var->isInvalidDecl()) {
  6002. if (const IncompleteArrayType *ArrayT
  6003. = Context.getAsIncompleteArrayType(Type)) {
  6004. if (RequireCompleteType(Var->getLocation(),
  6005. ArrayT->getElementType(),
  6006. diag::err_illegal_decl_array_incomplete_type))
  6007. Var->setInvalidDecl();
  6008. } else if (Var->getStorageClass() == SC_Static) {
  6009. // C99 6.9.2p3: If the declaration of an identifier for an object is
  6010. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  6011. // declared type shall not be an incomplete type.
  6012. // NOTE: code such as the following
  6013. // static struct s;
  6014. // struct s { int a; };
  6015. // is accepted by gcc. Hence here we issue a warning instead of
  6016. // an error and we do not invalidate the static declaration.
  6017. // NOTE: to avoid multiple warnings, only check the first declaration.
  6018. if (Var->getPreviousDecl() == 0)
  6019. RequireCompleteType(Var->getLocation(), Type,
  6020. diag::ext_typecheck_decl_incomplete_type);
  6021. }
  6022. }
  6023. // Record the tentative definition; we're done.
  6024. if (!Var->isInvalidDecl())
  6025. TentativeDefinitions.push_back(Var);
  6026. return;
  6027. }
  6028. // Provide a specific diagnostic for uninitialized variable
  6029. // definitions with incomplete array type.
  6030. if (Type->isIncompleteArrayType()) {
  6031. Diag(Var->getLocation(),
  6032. diag::err_typecheck_incomplete_array_needs_initializer);
  6033. Var->setInvalidDecl();
  6034. return;
  6035. }
  6036. // Provide a specific diagnostic for uninitialized variable
  6037. // definitions with reference type.
  6038. if (Type->isReferenceType()) {
  6039. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  6040. << Var->getDeclName()
  6041. << SourceRange(Var->getLocation(), Var->getLocation());
  6042. Var->setInvalidDecl();
  6043. return;
  6044. }
  6045. // Do not attempt to type-check the default initializer for a
  6046. // variable with dependent type.
  6047. if (Type->isDependentType())
  6048. return;
  6049. if (Var->isInvalidDecl())
  6050. return;
  6051. if (RequireCompleteType(Var->getLocation(),
  6052. Context.getBaseElementType(Type),
  6053. diag::err_typecheck_decl_incomplete_type)) {
  6054. Var->setInvalidDecl();
  6055. return;
  6056. }
  6057. // The variable can not have an abstract class type.
  6058. if (RequireNonAbstractType(Var->getLocation(), Type,
  6059. diag::err_abstract_type_in_decl,
  6060. AbstractVariableType)) {
  6061. Var->setInvalidDecl();
  6062. return;
  6063. }
  6064. // Check for jumps past the implicit initializer. C++0x
  6065. // clarifies that this applies to a "variable with automatic
  6066. // storage duration", not a "local variable".
  6067. // C++11 [stmt.dcl]p3
  6068. // A program that jumps from a point where a variable with automatic
  6069. // storage duration is not in scope to a point where it is in scope is
  6070. // ill-formed unless the variable has scalar type, class type with a
  6071. // trivial default constructor and a trivial destructor, a cv-qualified
  6072. // version of one of these types, or an array of one of the preceding
  6073. // types and is declared without an initializer.
  6074. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  6075. if (const RecordType *Record
  6076. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  6077. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  6078. // Mark the function for further checking even if the looser rules of
  6079. // C++11 do not require such checks, so that we can diagnose
  6080. // incompatibilities with C++98.
  6081. if (!CXXRecord->isPOD())
  6082. getCurFunction()->setHasBranchProtectedScope();
  6083. }
  6084. }
  6085. // C++03 [dcl.init]p9:
  6086. // If no initializer is specified for an object, and the
  6087. // object is of (possibly cv-qualified) non-POD class type (or
  6088. // array thereof), the object shall be default-initialized; if
  6089. // the object is of const-qualified type, the underlying class
  6090. // type shall have a user-declared default
  6091. // constructor. Otherwise, if no initializer is specified for
  6092. // a non- static object, the object and its subobjects, if
  6093. // any, have an indeterminate initial value); if the object
  6094. // or any of its subobjects are of const-qualified type, the
  6095. // program is ill-formed.
  6096. // C++0x [dcl.init]p11:
  6097. // If no initializer is specified for an object, the object is
  6098. // default-initialized; [...].
  6099. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  6100. InitializationKind Kind
  6101. = InitializationKind::CreateDefault(Var->getLocation());
  6102. InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
  6103. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, MultiExprArg());
  6104. if (Init.isInvalid())
  6105. Var->setInvalidDecl();
  6106. else if (Init.get()) {
  6107. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  6108. // This is important for template substitution.
  6109. Var->setInitStyle(VarDecl::CallInit);
  6110. }
  6111. CheckCompleteVariableDeclaration(Var);
  6112. }
  6113. }
  6114. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  6115. VarDecl *VD = dyn_cast<VarDecl>(D);
  6116. if (!VD) {
  6117. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  6118. D->setInvalidDecl();
  6119. return;
  6120. }
  6121. VD->setCXXForRangeDecl(true);
  6122. // for-range-declaration cannot be given a storage class specifier.
  6123. int Error = -1;
  6124. switch (VD->getStorageClassAsWritten()) {
  6125. case SC_None:
  6126. break;
  6127. case SC_Extern:
  6128. Error = 0;
  6129. break;
  6130. case SC_Static:
  6131. Error = 1;
  6132. break;
  6133. case SC_PrivateExtern:
  6134. Error = 2;
  6135. break;
  6136. case SC_Auto:
  6137. Error = 3;
  6138. break;
  6139. case SC_Register:
  6140. Error = 4;
  6141. break;
  6142. case SC_OpenCLWorkGroupLocal:
  6143. llvm_unreachable("Unexpected storage class");
  6144. }
  6145. if (VD->isConstexpr())
  6146. Error = 5;
  6147. if (Error != -1) {
  6148. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  6149. << VD->getDeclName() << Error;
  6150. D->setInvalidDecl();
  6151. }
  6152. }
  6153. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  6154. if (var->isInvalidDecl()) return;
  6155. // In ARC, don't allow jumps past the implicit initialization of a
  6156. // local retaining variable.
  6157. if (getLangOpts().ObjCAutoRefCount &&
  6158. var->hasLocalStorage()) {
  6159. switch (var->getType().getObjCLifetime()) {
  6160. case Qualifiers::OCL_None:
  6161. case Qualifiers::OCL_ExplicitNone:
  6162. case Qualifiers::OCL_Autoreleasing:
  6163. break;
  6164. case Qualifiers::OCL_Weak:
  6165. case Qualifiers::OCL_Strong:
  6166. getCurFunction()->setHasBranchProtectedScope();
  6167. break;
  6168. }
  6169. }
  6170. // All the following checks are C++ only.
  6171. if (!getLangOpts().CPlusPlus) return;
  6172. QualType baseType = Context.getBaseElementType(var->getType());
  6173. if (baseType->isDependentType()) return;
  6174. // __block variables might require us to capture a copy-initializer.
  6175. if (var->hasAttr<BlocksAttr>()) {
  6176. // It's currently invalid to ever have a __block variable with an
  6177. // array type; should we diagnose that here?
  6178. // Regardless, we don't want to ignore array nesting when
  6179. // constructing this copy.
  6180. QualType type = var->getType();
  6181. if (type->isStructureOrClassType()) {
  6182. SourceLocation poi = var->getLocation();
  6183. Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
  6184. ExprResult result =
  6185. PerformCopyInitialization(
  6186. InitializedEntity::InitializeBlock(poi, type, false),
  6187. poi, Owned(varRef));
  6188. if (!result.isInvalid()) {
  6189. result = MaybeCreateExprWithCleanups(result);
  6190. Expr *init = result.takeAs<Expr>();
  6191. Context.setBlockVarCopyInits(var, init);
  6192. }
  6193. }
  6194. }
  6195. Expr *Init = var->getInit();
  6196. bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
  6197. if (!var->getDeclContext()->isDependentContext() && Init) {
  6198. if (IsGlobal && !var->isConstexpr() &&
  6199. getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
  6200. var->getLocation())
  6201. != DiagnosticsEngine::Ignored &&
  6202. !Init->isConstantInitializer(Context, baseType->isReferenceType()))
  6203. Diag(var->getLocation(), diag::warn_global_constructor)
  6204. << Init->getSourceRange();
  6205. if (var->isConstexpr()) {
  6206. llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
  6207. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  6208. SourceLocation DiagLoc = var->getLocation();
  6209. // If the note doesn't add any useful information other than a source
  6210. // location, fold it into the primary diagnostic.
  6211. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  6212. diag::note_invalid_subexpr_in_const_expr) {
  6213. DiagLoc = Notes[0].first;
  6214. Notes.clear();
  6215. }
  6216. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  6217. << var << Init->getSourceRange();
  6218. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  6219. Diag(Notes[I].first, Notes[I].second);
  6220. }
  6221. } else if (var->isUsableInConstantExpressions(Context)) {
  6222. // Check whether the initializer of a const variable of integral or
  6223. // enumeration type is an ICE now, since we can't tell whether it was
  6224. // initialized by a constant expression if we check later.
  6225. var->checkInitIsICE();
  6226. }
  6227. }
  6228. // Require the destructor.
  6229. if (const RecordType *recordType = baseType->getAs<RecordType>())
  6230. FinalizeVarWithDestructor(var, recordType);
  6231. }
  6232. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  6233. /// any semantic actions necessary after any initializer has been attached.
  6234. void
  6235. Sema::FinalizeDeclaration(Decl *ThisDecl) {
  6236. // Note that we are no longer parsing the initializer for this declaration.
  6237. ParsingInitForAutoVars.erase(ThisDecl);
  6238. // Now we have parsed the initializer and can update the table of magic
  6239. // tag values.
  6240. if (ThisDecl && ThisDecl->hasAttr<TypeTagForDatatypeAttr>()) {
  6241. const VarDecl *VD = dyn_cast<VarDecl>(ThisDecl);
  6242. if (VD && VD->getType()->isIntegralOrEnumerationType()) {
  6243. for (specific_attr_iterator<TypeTagForDatatypeAttr>
  6244. I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
  6245. E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
  6246. I != E; ++I) {
  6247. const Expr *MagicValueExpr = VD->getInit();
  6248. if (!MagicValueExpr) {
  6249. continue;
  6250. }
  6251. llvm::APSInt MagicValueInt;
  6252. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  6253. Diag(I->getRange().getBegin(),
  6254. diag::err_type_tag_for_datatype_not_ice)
  6255. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  6256. continue;
  6257. }
  6258. if (MagicValueInt.getActiveBits() > 64) {
  6259. Diag(I->getRange().getBegin(),
  6260. diag::err_type_tag_for_datatype_too_large)
  6261. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  6262. continue;
  6263. }
  6264. uint64_t MagicValue = MagicValueInt.getZExtValue();
  6265. RegisterTypeTagForDatatype(I->getArgumentKind(),
  6266. MagicValue,
  6267. I->getMatchingCType(),
  6268. I->getLayoutCompatible(),
  6269. I->getMustBeNull());
  6270. }
  6271. }
  6272. }
  6273. }
  6274. Sema::DeclGroupPtrTy
  6275. Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  6276. Decl **Group, unsigned NumDecls) {
  6277. SmallVector<Decl*, 8> Decls;
  6278. if (DS.isTypeSpecOwned())
  6279. Decls.push_back(DS.getRepAsDecl());
  6280. for (unsigned i = 0; i != NumDecls; ++i)
  6281. if (Decl *D = Group[i])
  6282. Decls.push_back(D);
  6283. return BuildDeclaratorGroup(Decls.data(), Decls.size(),
  6284. DS.getTypeSpecType() == DeclSpec::TST_auto);
  6285. }
  6286. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  6287. /// group, performing any necessary semantic checking.
  6288. Sema::DeclGroupPtrTy
  6289. Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
  6290. bool TypeMayContainAuto) {
  6291. // C++0x [dcl.spec.auto]p7:
  6292. // If the type deduced for the template parameter U is not the same in each
  6293. // deduction, the program is ill-formed.
  6294. // FIXME: When initializer-list support is added, a distinction is needed
  6295. // between the deduced type U and the deduced type which 'auto' stands for.
  6296. // auto a = 0, b = { 1, 2, 3 };
  6297. // is legal because the deduced type U is 'int' in both cases.
  6298. if (TypeMayContainAuto && NumDecls > 1) {
  6299. QualType Deduced;
  6300. CanQualType DeducedCanon;
  6301. VarDecl *DeducedDecl = 0;
  6302. for (unsigned i = 0; i != NumDecls; ++i) {
  6303. if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
  6304. AutoType *AT = D->getType()->getContainedAutoType();
  6305. // Don't reissue diagnostics when instantiating a template.
  6306. if (AT && D->isInvalidDecl())
  6307. break;
  6308. if (AT && AT->isDeduced()) {
  6309. QualType U = AT->getDeducedType();
  6310. CanQualType UCanon = Context.getCanonicalType(U);
  6311. if (Deduced.isNull()) {
  6312. Deduced = U;
  6313. DeducedCanon = UCanon;
  6314. DeducedDecl = D;
  6315. } else if (DeducedCanon != UCanon) {
  6316. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  6317. diag::err_auto_different_deductions)
  6318. << Deduced << DeducedDecl->getDeclName()
  6319. << U << D->getDeclName()
  6320. << DeducedDecl->getInit()->getSourceRange()
  6321. << D->getInit()->getSourceRange();
  6322. D->setInvalidDecl();
  6323. break;
  6324. }
  6325. }
  6326. }
  6327. }
  6328. }
  6329. ActOnDocumentableDecls(Group, NumDecls);
  6330. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
  6331. }
  6332. void Sema::ActOnDocumentableDecl(Decl *D) {
  6333. ActOnDocumentableDecls(&D, 1);
  6334. }
  6335. void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) {
  6336. // Don't parse the comment if Doxygen diagnostics are ignored.
  6337. if (NumDecls == 0 || !Group[0])
  6338. return;
  6339. if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
  6340. Group[0]->getLocation())
  6341. == DiagnosticsEngine::Ignored)
  6342. return;
  6343. if (NumDecls >= 2) {
  6344. // This is a decl group. Normally it will contain only declarations
  6345. // procuded from declarator list. But in case we have any definitions or
  6346. // additional declaration references:
  6347. // 'typedef struct S {} S;'
  6348. // 'typedef struct S *S;'
  6349. // 'struct S *pS;'
  6350. // FinalizeDeclaratorGroup adds these as separate declarations.
  6351. Decl *MaybeTagDecl = Group[0];
  6352. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  6353. Group++;
  6354. NumDecls--;
  6355. }
  6356. }
  6357. // See if there are any new comments that are not attached to a decl.
  6358. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  6359. if (!Comments.empty() &&
  6360. !Comments.back()->isAttached()) {
  6361. // There is at least one comment that not attached to a decl.
  6362. // Maybe it should be attached to one of these decls?
  6363. //
  6364. // Note that this way we pick up not only comments that precede the
  6365. // declaration, but also comments that *follow* the declaration -- thanks to
  6366. // the lookahead in the lexer: we've consumed the semicolon and looked
  6367. // ahead through comments.
  6368. for (unsigned i = 0; i != NumDecls; ++i)
  6369. Context.getCommentForDecl(Group[i]);
  6370. }
  6371. }
  6372. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  6373. /// to introduce parameters into function prototype scope.
  6374. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  6375. const DeclSpec &DS = D.getDeclSpec();
  6376. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  6377. // C++03 [dcl.stc]p2 also permits 'auto'.
  6378. VarDecl::StorageClass StorageClass = SC_None;
  6379. VarDecl::StorageClass StorageClassAsWritten = SC_None;
  6380. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  6381. StorageClass = SC_Register;
  6382. StorageClassAsWritten = SC_Register;
  6383. } else if (getLangOpts().CPlusPlus &&
  6384. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  6385. StorageClass = SC_Auto;
  6386. StorageClassAsWritten = SC_Auto;
  6387. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  6388. Diag(DS.getStorageClassSpecLoc(),
  6389. diag::err_invalid_storage_class_in_func_decl);
  6390. D.getMutableDeclSpec().ClearStorageClassSpecs();
  6391. }
  6392. if (D.getDeclSpec().isThreadSpecified())
  6393. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  6394. if (D.getDeclSpec().isConstexprSpecified())
  6395. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  6396. << 0;
  6397. DiagnoseFunctionSpecifiers(D);
  6398. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  6399. QualType parmDeclType = TInfo->getType();
  6400. if (getLangOpts().CPlusPlus) {
  6401. // Check that there are no default arguments inside the type of this
  6402. // parameter.
  6403. CheckExtraCXXDefaultArguments(D);
  6404. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  6405. if (D.getCXXScopeSpec().isSet()) {
  6406. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  6407. << D.getCXXScopeSpec().getRange();
  6408. D.getCXXScopeSpec().clear();
  6409. }
  6410. }
  6411. // Ensure we have a valid name
  6412. IdentifierInfo *II = 0;
  6413. if (D.hasName()) {
  6414. II = D.getIdentifier();
  6415. if (!II) {
  6416. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  6417. << GetNameForDeclarator(D).getName().getAsString();
  6418. D.setInvalidType(true);
  6419. }
  6420. }
  6421. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  6422. if (II) {
  6423. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  6424. ForRedeclaration);
  6425. LookupName(R, S);
  6426. if (R.isSingleResult()) {
  6427. NamedDecl *PrevDecl = R.getFoundDecl();
  6428. if (PrevDecl->isTemplateParameter()) {
  6429. // Maybe we will complain about the shadowed template parameter.
  6430. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  6431. // Just pretend that we didn't see the previous declaration.
  6432. PrevDecl = 0;
  6433. } else if (S->isDeclScope(PrevDecl)) {
  6434. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  6435. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  6436. // Recover by removing the name
  6437. II = 0;
  6438. D.SetIdentifier(0, D.getIdentifierLoc());
  6439. D.setInvalidType(true);
  6440. }
  6441. }
  6442. }
  6443. // Temporarily put parameter variables in the translation unit, not
  6444. // the enclosing context. This prevents them from accidentally
  6445. // looking like class members in C++.
  6446. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  6447. D.getLocStart(),
  6448. D.getIdentifierLoc(), II,
  6449. parmDeclType, TInfo,
  6450. StorageClass, StorageClassAsWritten);
  6451. if (D.isInvalidType())
  6452. New->setInvalidDecl();
  6453. assert(S->isFunctionPrototypeScope());
  6454. assert(S->getFunctionPrototypeDepth() >= 1);
  6455. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  6456. S->getNextFunctionPrototypeIndex());
  6457. // Add the parameter declaration into this scope.
  6458. S->AddDecl(New);
  6459. if (II)
  6460. IdResolver.AddDecl(New);
  6461. ProcessDeclAttributes(S, New, D);
  6462. if (D.getDeclSpec().isModulePrivateSpecified())
  6463. Diag(New->getLocation(), diag::err_module_private_local)
  6464. << 1 << New->getDeclName()
  6465. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  6466. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6467. if (New->hasAttr<BlocksAttr>()) {
  6468. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  6469. }
  6470. return New;
  6471. }
  6472. /// \brief Synthesizes a variable for a parameter arising from a
  6473. /// typedef.
  6474. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  6475. SourceLocation Loc,
  6476. QualType T) {
  6477. /* FIXME: setting StartLoc == Loc.
  6478. Would it be worth to modify callers so as to provide proper source
  6479. location for the unnamed parameters, embedding the parameter's type? */
  6480. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
  6481. T, Context.getTrivialTypeSourceInfo(T, Loc),
  6482. SC_None, SC_None, 0);
  6483. Param->setImplicit();
  6484. return Param;
  6485. }
  6486. void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
  6487. ParmVarDecl * const *ParamEnd) {
  6488. // Don't diagnose unused-parameter errors in template instantiations; we
  6489. // will already have done so in the template itself.
  6490. if (!ActiveTemplateInstantiations.empty())
  6491. return;
  6492. for (; Param != ParamEnd; ++Param) {
  6493. if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
  6494. !(*Param)->hasAttr<UnusedAttr>()) {
  6495. Diag((*Param)->getLocation(), diag::warn_unused_parameter)
  6496. << (*Param)->getDeclName();
  6497. }
  6498. }
  6499. }
  6500. void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
  6501. ParmVarDecl * const *ParamEnd,
  6502. QualType ReturnTy,
  6503. NamedDecl *D) {
  6504. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  6505. return;
  6506. // Warn if the return value is pass-by-value and larger than the specified
  6507. // threshold.
  6508. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  6509. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  6510. if (Size > LangOpts.NumLargeByValueCopy)
  6511. Diag(D->getLocation(), diag::warn_return_value_size)
  6512. << D->getDeclName() << Size;
  6513. }
  6514. // Warn if any parameter is pass-by-value and larger than the specified
  6515. // threshold.
  6516. for (; Param != ParamEnd; ++Param) {
  6517. QualType T = (*Param)->getType();
  6518. if (T->isDependentType() || !T.isPODType(Context))
  6519. continue;
  6520. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  6521. if (Size > LangOpts.NumLargeByValueCopy)
  6522. Diag((*Param)->getLocation(), diag::warn_parameter_size)
  6523. << (*Param)->getDeclName() << Size;
  6524. }
  6525. }
  6526. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  6527. SourceLocation NameLoc, IdentifierInfo *Name,
  6528. QualType T, TypeSourceInfo *TSInfo,
  6529. VarDecl::StorageClass StorageClass,
  6530. VarDecl::StorageClass StorageClassAsWritten) {
  6531. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  6532. if (getLangOpts().ObjCAutoRefCount &&
  6533. T.getObjCLifetime() == Qualifiers::OCL_None &&
  6534. T->isObjCLifetimeType()) {
  6535. Qualifiers::ObjCLifetime lifetime;
  6536. // Special cases for arrays:
  6537. // - if it's const, use __unsafe_unretained
  6538. // - otherwise, it's an error
  6539. if (T->isArrayType()) {
  6540. if (!T.isConstQualified()) {
  6541. DelayedDiagnostics.add(
  6542. sema::DelayedDiagnostic::makeForbiddenType(
  6543. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  6544. }
  6545. lifetime = Qualifiers::OCL_ExplicitNone;
  6546. } else {
  6547. lifetime = T->getObjCARCImplicitLifetime();
  6548. }
  6549. T = Context.getLifetimeQualifiedType(T, lifetime);
  6550. }
  6551. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  6552. Context.getAdjustedParameterType(T),
  6553. TSInfo,
  6554. StorageClass, StorageClassAsWritten,
  6555. 0);
  6556. // Parameters can not be abstract class types.
  6557. // For record types, this is done by the AbstractClassUsageDiagnoser once
  6558. // the class has been completely parsed.
  6559. if (!CurContext->isRecord() &&
  6560. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  6561. AbstractParamType))
  6562. New->setInvalidDecl();
  6563. // Parameter declarators cannot be interface types. All ObjC objects are
  6564. // passed by reference.
  6565. if (T->isObjCObjectType()) {
  6566. SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
  6567. Diag(NameLoc,
  6568. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  6569. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  6570. T = Context.getObjCObjectPointerType(T);
  6571. New->setType(T);
  6572. }
  6573. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  6574. // duration shall not be qualified by an address-space qualifier."
  6575. // Since all parameters have automatic store duration, they can not have
  6576. // an address space.
  6577. if (T.getAddressSpace() != 0) {
  6578. Diag(NameLoc, diag::err_arg_with_address_space);
  6579. New->setInvalidDecl();
  6580. }
  6581. return New;
  6582. }
  6583. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  6584. SourceLocation LocAfterDecls) {
  6585. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  6586. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  6587. // for a K&R function.
  6588. if (!FTI.hasPrototype) {
  6589. for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
  6590. --i;
  6591. if (FTI.ArgInfo[i].Param == 0) {
  6592. SmallString<256> Code;
  6593. llvm::raw_svector_ostream(Code) << " int "
  6594. << FTI.ArgInfo[i].Ident->getName()
  6595. << ";\n";
  6596. Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
  6597. << FTI.ArgInfo[i].Ident
  6598. << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
  6599. // Implicitly declare the argument as type 'int' for lack of a better
  6600. // type.
  6601. AttributeFactory attrs;
  6602. DeclSpec DS(attrs);
  6603. const char* PrevSpec; // unused
  6604. unsigned DiagID; // unused
  6605. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
  6606. PrevSpec, DiagID);
  6607. Declarator ParamD(DS, Declarator::KNRTypeListContext);
  6608. ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
  6609. FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
  6610. }
  6611. }
  6612. }
  6613. }
  6614. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
  6615. assert(getCurFunctionDecl() == 0 && "Function parsing confused");
  6616. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  6617. Scope *ParentScope = FnBodyScope->getParent();
  6618. D.setFunctionDefinitionKind(FDK_Definition);
  6619. Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
  6620. return ActOnStartOfFunctionDef(FnBodyScope, DP);
  6621. }
  6622. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
  6623. // Don't warn about invalid declarations.
  6624. if (FD->isInvalidDecl())
  6625. return false;
  6626. // Or declarations that aren't global.
  6627. if (!FD->isGlobal())
  6628. return false;
  6629. // Don't warn about C++ member functions.
  6630. if (isa<CXXMethodDecl>(FD))
  6631. return false;
  6632. // Don't warn about 'main'.
  6633. if (FD->isMain())
  6634. return false;
  6635. // Don't warn about inline functions.
  6636. if (FD->isInlined())
  6637. return false;
  6638. // Don't warn about function templates.
  6639. if (FD->getDescribedFunctionTemplate())
  6640. return false;
  6641. // Don't warn about function template specializations.
  6642. if (FD->isFunctionTemplateSpecialization())
  6643. return false;
  6644. // Don't warn for OpenCL kernels.
  6645. if (FD->hasAttr<OpenCLKernelAttr>())
  6646. return false;
  6647. bool MissingPrototype = true;
  6648. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  6649. Prev; Prev = Prev->getPreviousDecl()) {
  6650. // Ignore any declarations that occur in function or method
  6651. // scope, because they aren't visible from the header.
  6652. if (Prev->getDeclContext()->isFunctionOrMethod())
  6653. continue;
  6654. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  6655. break;
  6656. }
  6657. return MissingPrototype;
  6658. }
  6659. void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
  6660. // Don't complain if we're in GNU89 mode and the previous definition
  6661. // was an extern inline function.
  6662. const FunctionDecl *Definition;
  6663. if (FD->isDefined(Definition) &&
  6664. !canRedefineFunction(Definition, getLangOpts())) {
  6665. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  6666. Definition->getStorageClass() == SC_Extern)
  6667. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  6668. << FD->getDeclName() << getLangOpts().CPlusPlus;
  6669. else
  6670. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  6671. Diag(Definition->getLocation(), diag::note_previous_definition);
  6672. FD->setInvalidDecl();
  6673. }
  6674. }
  6675. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
  6676. // Clear the last template instantiation error context.
  6677. LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
  6678. if (!D)
  6679. return D;
  6680. FunctionDecl *FD = 0;
  6681. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  6682. FD = FunTmpl->getTemplatedDecl();
  6683. else
  6684. FD = cast<FunctionDecl>(D);
  6685. // Enter a new function scope
  6686. PushFunctionScope();
  6687. // See if this is a redefinition.
  6688. if (!FD->isLateTemplateParsed())
  6689. CheckForFunctionRedefinition(FD);
  6690. // Builtin functions cannot be defined.
  6691. if (unsigned BuiltinID = FD->getBuiltinID()) {
  6692. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  6693. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  6694. FD->setInvalidDecl();
  6695. }
  6696. }
  6697. // The return type of a function definition must be complete
  6698. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  6699. QualType ResultType = FD->getResultType();
  6700. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  6701. !FD->isInvalidDecl() &&
  6702. RequireCompleteType(FD->getLocation(), ResultType,
  6703. diag::err_func_def_incomplete_result))
  6704. FD->setInvalidDecl();
  6705. // GNU warning -Wmissing-prototypes:
  6706. // Warn if a global function is defined without a previous
  6707. // prototype declaration. This warning is issued even if the
  6708. // definition itself provides a prototype. The aim is to detect
  6709. // global functions that fail to be declared in header files.
  6710. if (ShouldWarnAboutMissingPrototype(FD))
  6711. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  6712. if (FnBodyScope)
  6713. PushDeclContext(FnBodyScope, FD);
  6714. // Check the validity of our function parameters
  6715. CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
  6716. /*CheckParameterNames=*/true);
  6717. // Introduce our parameters into the function scope
  6718. for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
  6719. ParmVarDecl *Param = FD->getParamDecl(p);
  6720. Param->setOwningFunction(FD);
  6721. // If this has an identifier, add it to the scope stack.
  6722. if (Param->getIdentifier() && FnBodyScope) {
  6723. CheckShadow(FnBodyScope, Param);
  6724. PushOnScopeChains(Param, FnBodyScope);
  6725. }
  6726. }
  6727. // If we had any tags defined in the function prototype,
  6728. // introduce them into the function scope.
  6729. if (FnBodyScope) {
  6730. for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
  6731. E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
  6732. NamedDecl *D = *I;
  6733. // Some of these decls (like enums) may have been pinned to the translation unit
  6734. // for lack of a real context earlier. If so, remove from the translation unit
  6735. // and reattach to the current context.
  6736. if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
  6737. // Is the decl actually in the context?
  6738. for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
  6739. DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
  6740. if (*DI == D) {
  6741. Context.getTranslationUnitDecl()->removeDecl(D);
  6742. break;
  6743. }
  6744. }
  6745. // Either way, reassign the lexical decl context to our FunctionDecl.
  6746. D->setLexicalDeclContext(CurContext);
  6747. }
  6748. // If the decl has a non-null name, make accessible in the current scope.
  6749. if (!D->getName().empty())
  6750. PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
  6751. // Similarly, dive into enums and fish their constants out, making them
  6752. // accessible in this scope.
  6753. if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
  6754. for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
  6755. EE = ED->enumerator_end(); EI != EE; ++EI)
  6756. PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
  6757. }
  6758. }
  6759. }
  6760. // Ensure that the function's exception specification is instantiated.
  6761. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  6762. ResolveExceptionSpec(D->getLocation(), FPT);
  6763. // Checking attributes of current function definition
  6764. // dllimport attribute.
  6765. DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
  6766. if (DA && (!FD->getAttr<DLLExportAttr>())) {
  6767. // dllimport attribute cannot be directly applied to definition.
  6768. // Microsoft accepts dllimport for functions defined within class scope.
  6769. if (!DA->isInherited() &&
  6770. !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
  6771. Diag(FD->getLocation(),
  6772. diag::err_attribute_can_be_applied_only_to_symbol_declaration)
  6773. << "dllimport";
  6774. FD->setInvalidDecl();
  6775. return FD;
  6776. }
  6777. // Visual C++ appears to not think this is an issue, so only issue
  6778. // a warning when Microsoft extensions are disabled.
  6779. if (!LangOpts.MicrosoftExt) {
  6780. // If a symbol previously declared dllimport is later defined, the
  6781. // attribute is ignored in subsequent references, and a warning is
  6782. // emitted.
  6783. Diag(FD->getLocation(),
  6784. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  6785. << FD->getName() << "dllimport";
  6786. }
  6787. }
  6788. // We want to attach documentation to original Decl (which might be
  6789. // a function template).
  6790. ActOnDocumentableDecl(D);
  6791. return FD;
  6792. }
  6793. /// \brief Given the set of return statements within a function body,
  6794. /// compute the variables that are subject to the named return value
  6795. /// optimization.
  6796. ///
  6797. /// Each of the variables that is subject to the named return value
  6798. /// optimization will be marked as NRVO variables in the AST, and any
  6799. /// return statement that has a marked NRVO variable as its NRVO candidate can
  6800. /// use the named return value optimization.
  6801. ///
  6802. /// This function applies a very simplistic algorithm for NRVO: if every return
  6803. /// statement in the function has the same NRVO candidate, that candidate is
  6804. /// the NRVO variable.
  6805. ///
  6806. /// FIXME: Employ a smarter algorithm that accounts for multiple return
  6807. /// statements and the lifetimes of the NRVO candidates. We should be able to
  6808. /// find a maximal set of NRVO variables.
  6809. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  6810. ReturnStmt **Returns = Scope->Returns.data();
  6811. const VarDecl *NRVOCandidate = 0;
  6812. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  6813. if (!Returns[I]->getNRVOCandidate())
  6814. return;
  6815. if (!NRVOCandidate)
  6816. NRVOCandidate = Returns[I]->getNRVOCandidate();
  6817. else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
  6818. return;
  6819. }
  6820. if (NRVOCandidate)
  6821. const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
  6822. }
  6823. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  6824. return ActOnFinishFunctionBody(D, BodyArg, false);
  6825. }
  6826. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  6827. bool IsInstantiation) {
  6828. FunctionDecl *FD = 0;
  6829. FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
  6830. if (FunTmpl)
  6831. FD = FunTmpl->getTemplatedDecl();
  6832. else
  6833. FD = dyn_cast_or_null<FunctionDecl>(dcl);
  6834. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  6835. sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
  6836. if (FD) {
  6837. FD->setBody(Body);
  6838. // If the function implicitly returns zero (like 'main') or is naked,
  6839. // don't complain about missing return statements.
  6840. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  6841. WP.disableCheckFallThrough();
  6842. // MSVC permits the use of pure specifier (=0) on function definition,
  6843. // defined at class scope, warn about this non standard construct.
  6844. if (getLangOpts().MicrosoftExt && FD->isPure())
  6845. Diag(FD->getLocation(), diag::warn_pure_function_definition);
  6846. if (!FD->isInvalidDecl()) {
  6847. DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
  6848. DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
  6849. FD->getResultType(), FD);
  6850. // If this is a constructor, we need a vtable.
  6851. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  6852. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  6853. // Try to apply the named return value optimization. We have to check
  6854. // if we can do this here because lambdas keep return statements around
  6855. // to deduce an implicit return type.
  6856. if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
  6857. !FD->isDependentContext())
  6858. computeNRVO(Body, getCurFunction());
  6859. }
  6860. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  6861. "Function parsing confused");
  6862. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  6863. assert(MD == getCurMethodDecl() && "Method parsing confused");
  6864. MD->setBody(Body);
  6865. if (!MD->isInvalidDecl()) {
  6866. DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
  6867. DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
  6868. MD->getResultType(), MD);
  6869. if (Body)
  6870. computeNRVO(Body, getCurFunction());
  6871. }
  6872. if (getCurFunction()->ObjCShouldCallSuperDealloc) {
  6873. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
  6874. << MD->getSelector().getAsString();
  6875. getCurFunction()->ObjCShouldCallSuperDealloc = false;
  6876. }
  6877. if (getCurFunction()->ObjCShouldCallSuperFinalize) {
  6878. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize);
  6879. getCurFunction()->ObjCShouldCallSuperFinalize = false;
  6880. }
  6881. } else {
  6882. return 0;
  6883. }
  6884. assert(!getCurFunction()->ObjCShouldCallSuperDealloc &&
  6885. "This should only be set for ObjC methods, which should have been "
  6886. "handled in the block above.");
  6887. assert(!getCurFunction()->ObjCShouldCallSuperFinalize &&
  6888. "This should only be set for ObjC methods, which should have been "
  6889. "handled in the block above.");
  6890. // Verify and clean out per-function state.
  6891. if (Body) {
  6892. // C++ constructors that have function-try-blocks can't have return
  6893. // statements in the handlers of that block. (C++ [except.handle]p14)
  6894. // Verify this.
  6895. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  6896. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  6897. // Verify that gotos and switch cases don't jump into scopes illegally.
  6898. if (getCurFunction()->NeedsScopeChecking() &&
  6899. !dcl->isInvalidDecl() &&
  6900. !hasAnyUnrecoverableErrorsInThisFunction() &&
  6901. !PP.isCodeCompletionEnabled())
  6902. DiagnoseInvalidJumps(Body);
  6903. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  6904. if (!Destructor->getParent()->isDependentType())
  6905. CheckDestructor(Destructor);
  6906. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  6907. Destructor->getParent());
  6908. }
  6909. // If any errors have occurred, clear out any temporaries that may have
  6910. // been leftover. This ensures that these temporaries won't be picked up for
  6911. // deletion in some later function.
  6912. if (PP.getDiagnostics().hasErrorOccurred() ||
  6913. PP.getDiagnostics().getSuppressAllDiagnostics()) {
  6914. DiscardCleanupsInEvaluationContext();
  6915. } else if (!isa<FunctionTemplateDecl>(dcl)) {
  6916. // Since the body is valid, issue any analysis-based warnings that are
  6917. // enabled.
  6918. ActivePolicy = &WP;
  6919. }
  6920. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  6921. (!CheckConstexprFunctionDecl(FD) ||
  6922. !CheckConstexprFunctionBody(FD, Body)))
  6923. FD->setInvalidDecl();
  6924. assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
  6925. assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
  6926. assert(MaybeODRUseExprs.empty() &&
  6927. "Leftover expressions for odr-use checking");
  6928. }
  6929. if (!IsInstantiation)
  6930. PopDeclContext();
  6931. PopFunctionScopeInfo(ActivePolicy, dcl);
  6932. // If any errors have occurred, clear out any temporaries that may have
  6933. // been leftover. This ensures that these temporaries won't be picked up for
  6934. // deletion in some later function.
  6935. if (getDiagnostics().hasErrorOccurred()) {
  6936. DiscardCleanupsInEvaluationContext();
  6937. }
  6938. return dcl;
  6939. }
  6940. /// When we finish delayed parsing of an attribute, we must attach it to the
  6941. /// relevant Decl.
  6942. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  6943. ParsedAttributes &Attrs) {
  6944. // Always attach attributes to the underlying decl.
  6945. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  6946. D = TD->getTemplatedDecl();
  6947. ProcessDeclAttributeList(S, D, Attrs.getList());
  6948. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  6949. if (Method->isStatic())
  6950. checkThisInStaticMemberFunctionAttributes(Method);
  6951. }
  6952. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  6953. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  6954. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  6955. IdentifierInfo &II, Scope *S) {
  6956. // Before we produce a declaration for an implicitly defined
  6957. // function, see whether there was a locally-scoped declaration of
  6958. // this name as a function or variable. If so, use that
  6959. // (non-visible) declaration, and complain about it.
  6960. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  6961. = findLocallyScopedExternalDecl(&II);
  6962. if (Pos != LocallyScopedExternalDecls.end()) {
  6963. Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
  6964. Diag(Pos->second->getLocation(), diag::note_previous_declaration);
  6965. return Pos->second;
  6966. }
  6967. // Extension in C99. Legal in C90, but warn about it.
  6968. unsigned diag_id;
  6969. if (II.getName().startswith("__builtin_"))
  6970. diag_id = diag::warn_builtin_unknown;
  6971. else if (getLangOpts().C99)
  6972. diag_id = diag::ext_implicit_function_decl;
  6973. else
  6974. diag_id = diag::warn_implicit_function_decl;
  6975. Diag(Loc, diag_id) << &II;
  6976. // Because typo correction is expensive, only do it if the implicit
  6977. // function declaration is going to be treated as an error.
  6978. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  6979. TypoCorrection Corrected;
  6980. DeclFilterCCC<FunctionDecl> Validator;
  6981. if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
  6982. LookupOrdinaryName, S, 0, Validator))) {
  6983. std::string CorrectedStr = Corrected.getAsString(getLangOpts());
  6984. std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
  6985. FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
  6986. Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
  6987. << FixItHint::CreateReplacement(Loc, CorrectedStr);
  6988. if (Func->getLocation().isValid()
  6989. && !II.getName().startswith("__builtin_"))
  6990. Diag(Func->getLocation(), diag::note_previous_decl)
  6991. << CorrectedQuotedStr;
  6992. }
  6993. }
  6994. // Set a Declarator for the implicit definition: int foo();
  6995. const char *Dummy;
  6996. AttributeFactory attrFactory;
  6997. DeclSpec DS(attrFactory);
  6998. unsigned DiagID;
  6999. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
  7000. (void)Error; // Silence warning.
  7001. assert(!Error && "Error setting up implicit decl!");
  7002. Declarator D(DS, Declarator::BlockContext);
  7003. D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, false,
  7004. SourceLocation(), 0, 0, 0, true,
  7005. SourceLocation(), SourceLocation(),
  7006. SourceLocation(), SourceLocation(),
  7007. EST_None, SourceLocation(),
  7008. 0, 0, 0, 0, Loc, Loc, D),
  7009. DS.getAttributes(),
  7010. SourceLocation());
  7011. D.SetIdentifier(&II, Loc);
  7012. // Insert this function into translation-unit scope.
  7013. DeclContext *PrevDC = CurContext;
  7014. CurContext = Context.getTranslationUnitDecl();
  7015. FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
  7016. FD->setImplicit();
  7017. CurContext = PrevDC;
  7018. AddKnownFunctionAttributes(FD);
  7019. return FD;
  7020. }
  7021. /// \brief Adds any function attributes that we know a priori based on
  7022. /// the declaration of this function.
  7023. ///
  7024. /// These attributes can apply both to implicitly-declared builtins
  7025. /// (like __builtin___printf_chk) or to library-declared functions
  7026. /// like NSLog or printf.
  7027. ///
  7028. /// We need to check for duplicate attributes both here and where user-written
  7029. /// attributes are applied to declarations.
  7030. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  7031. if (FD->isInvalidDecl())
  7032. return;
  7033. // If this is a built-in function, map its builtin attributes to
  7034. // actual attributes.
  7035. if (unsigned BuiltinID = FD->getBuiltinID()) {
  7036. // Handle printf-formatting attributes.
  7037. unsigned FormatIdx;
  7038. bool HasVAListArg;
  7039. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  7040. if (!FD->getAttr<FormatAttr>()) {
  7041. const char *fmt = "printf";
  7042. unsigned int NumParams = FD->getNumParams();
  7043. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  7044. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  7045. fmt = "NSString";
  7046. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  7047. fmt, FormatIdx+1,
  7048. HasVAListArg ? 0 : FormatIdx+2));
  7049. }
  7050. }
  7051. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  7052. HasVAListArg)) {
  7053. if (!FD->getAttr<FormatAttr>())
  7054. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  7055. "scanf", FormatIdx+1,
  7056. HasVAListArg ? 0 : FormatIdx+2));
  7057. }
  7058. // Mark const if we don't care about errno and that is the only
  7059. // thing preventing the function from being const. This allows
  7060. // IRgen to use LLVM intrinsics for such functions.
  7061. if (!getLangOpts().MathErrno &&
  7062. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
  7063. if (!FD->getAttr<ConstAttr>())
  7064. FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
  7065. }
  7066. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  7067. !FD->getAttr<ReturnsTwiceAttr>())
  7068. FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
  7069. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
  7070. FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
  7071. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
  7072. FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
  7073. }
  7074. IdentifierInfo *Name = FD->getIdentifier();
  7075. if (!Name)
  7076. return;
  7077. if ((!getLangOpts().CPlusPlus &&
  7078. FD->getDeclContext()->isTranslationUnit()) ||
  7079. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  7080. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  7081. LinkageSpecDecl::lang_c)) {
  7082. // Okay: this could be a libc/libm/Objective-C function we know
  7083. // about.
  7084. } else
  7085. return;
  7086. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  7087. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  7088. // target-specific builtins, perhaps?
  7089. if (!FD->getAttr<FormatAttr>())
  7090. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  7091. "printf", 2,
  7092. Name->isStr("vasprintf") ? 0 : 3));
  7093. }
  7094. if (Name->isStr("__CFStringMakeConstantString")) {
  7095. // We already have a __builtin___CFStringMakeConstantString,
  7096. // but builds that use -fno-constant-cfstrings don't go through that.
  7097. if (!FD->getAttr<FormatArgAttr>())
  7098. FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
  7099. }
  7100. }
  7101. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  7102. TypeSourceInfo *TInfo) {
  7103. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  7104. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  7105. if (!TInfo) {
  7106. assert(D.isInvalidType() && "no declarator info for valid type");
  7107. TInfo = Context.getTrivialTypeSourceInfo(T);
  7108. }
  7109. // Scope manipulation handled by caller.
  7110. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  7111. D.getLocStart(),
  7112. D.getIdentifierLoc(),
  7113. D.getIdentifier(),
  7114. TInfo);
  7115. // Bail out immediately if we have an invalid declaration.
  7116. if (D.isInvalidType()) {
  7117. NewTD->setInvalidDecl();
  7118. return NewTD;
  7119. }
  7120. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7121. if (CurContext->isFunctionOrMethod())
  7122. Diag(NewTD->getLocation(), diag::err_module_private_local)
  7123. << 2 << NewTD->getDeclName()
  7124. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  7125. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  7126. else
  7127. NewTD->setModulePrivate();
  7128. }
  7129. // C++ [dcl.typedef]p8:
  7130. // If the typedef declaration defines an unnamed class (or
  7131. // enum), the first typedef-name declared by the declaration
  7132. // to be that class type (or enum type) is used to denote the
  7133. // class type (or enum type) for linkage purposes only.
  7134. // We need to check whether the type was declared in the declaration.
  7135. switch (D.getDeclSpec().getTypeSpecType()) {
  7136. case TST_enum:
  7137. case TST_struct:
  7138. case TST_interface:
  7139. case TST_union:
  7140. case TST_class: {
  7141. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  7142. // Do nothing if the tag is not anonymous or already has an
  7143. // associated typedef (from an earlier typedef in this decl group).
  7144. if (tagFromDeclSpec->getIdentifier()) break;
  7145. if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
  7146. // A well-formed anonymous tag must always be a TUK_Definition.
  7147. assert(tagFromDeclSpec->isThisDeclarationADefinition());
  7148. // The type must match the tag exactly; no qualifiers allowed.
  7149. if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
  7150. break;
  7151. // Otherwise, set this is the anon-decl typedef for the tag.
  7152. tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  7153. break;
  7154. }
  7155. default:
  7156. break;
  7157. }
  7158. return NewTD;
  7159. }
  7160. /// \brief Check that this is a valid underlying type for an enum declaration.
  7161. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  7162. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  7163. QualType T = TI->getType();
  7164. if (T->isDependentType() || T->isIntegralType(Context))
  7165. return false;
  7166. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  7167. return true;
  7168. }
  7169. /// Check whether this is a valid redeclaration of a previous enumeration.
  7170. /// \return true if the redeclaration was invalid.
  7171. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  7172. QualType EnumUnderlyingTy,
  7173. const EnumDecl *Prev) {
  7174. bool IsFixed = !EnumUnderlyingTy.isNull();
  7175. if (IsScoped != Prev->isScoped()) {
  7176. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  7177. << Prev->isScoped();
  7178. Diag(Prev->getLocation(), diag::note_previous_use);
  7179. return true;
  7180. }
  7181. if (IsFixed && Prev->isFixed()) {
  7182. if (!EnumUnderlyingTy->isDependentType() &&
  7183. !Prev->getIntegerType()->isDependentType() &&
  7184. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  7185. Prev->getIntegerType())) {
  7186. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  7187. << EnumUnderlyingTy << Prev->getIntegerType();
  7188. Diag(Prev->getLocation(), diag::note_previous_use);
  7189. return true;
  7190. }
  7191. } else if (IsFixed != Prev->isFixed()) {
  7192. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  7193. << Prev->isFixed();
  7194. Diag(Prev->getLocation(), diag::note_previous_use);
  7195. return true;
  7196. }
  7197. return false;
  7198. }
  7199. /// \brief Get diagnostic %select index for tag kind for
  7200. /// redeclaration diagnostic message.
  7201. /// WARNING: Indexes apply to particular diagnostics only!
  7202. ///
  7203. /// \returns diagnostic %select index.
  7204. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  7205. switch (Tag) {
  7206. case TTK_Struct: return 0;
  7207. case TTK_Interface: return 1;
  7208. case TTK_Class: return 2;
  7209. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  7210. }
  7211. }
  7212. /// \brief Determine if tag kind is a class-key compatible with
  7213. /// class for redeclaration (class, struct, or __interface).
  7214. ///
  7215. /// \returns true if the tag kind is compatible.
  7216. static bool isClassCompatTagKind(TagTypeKind Tag)
  7217. {
  7218. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  7219. }
  7220. /// \brief Determine whether a tag with a given kind is acceptable
  7221. /// as a redeclaration of the given tag declaration.
  7222. ///
  7223. /// \returns true if the new tag kind is acceptable, false otherwise.
  7224. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  7225. TagTypeKind NewTag, bool isDefinition,
  7226. SourceLocation NewTagLoc,
  7227. const IdentifierInfo &Name) {
  7228. // C++ [dcl.type.elab]p3:
  7229. // The class-key or enum keyword present in the
  7230. // elaborated-type-specifier shall agree in kind with the
  7231. // declaration to which the name in the elaborated-type-specifier
  7232. // refers. This rule also applies to the form of
  7233. // elaborated-type-specifier that declares a class-name or
  7234. // friend class since it can be construed as referring to the
  7235. // definition of the class. Thus, in any
  7236. // elaborated-type-specifier, the enum keyword shall be used to
  7237. // refer to an enumeration (7.2), the union class-key shall be
  7238. // used to refer to a union (clause 9), and either the class or
  7239. // struct class-key shall be used to refer to a class (clause 9)
  7240. // declared using the class or struct class-key.
  7241. TagTypeKind OldTag = Previous->getTagKind();
  7242. if (!isDefinition || !isClassCompatTagKind(NewTag))
  7243. if (OldTag == NewTag)
  7244. return true;
  7245. if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
  7246. // Warn about the struct/class tag mismatch.
  7247. bool isTemplate = false;
  7248. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  7249. isTemplate = Record->getDescribedClassTemplate();
  7250. if (!ActiveTemplateInstantiations.empty()) {
  7251. // In a template instantiation, do not offer fix-its for tag mismatches
  7252. // since they usually mess up the template instead of fixing the problem.
  7253. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  7254. << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
  7255. << getRedeclDiagFromTagKind(OldTag);
  7256. return true;
  7257. }
  7258. if (isDefinition) {
  7259. // On definitions, check previous tags and issue a fix-it for each
  7260. // one that doesn't match the current tag.
  7261. if (Previous->getDefinition()) {
  7262. // Don't suggest fix-its for redefinitions.
  7263. return true;
  7264. }
  7265. bool previousMismatch = false;
  7266. for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
  7267. E(Previous->redecls_end()); I != E; ++I) {
  7268. if (I->getTagKind() != NewTag) {
  7269. if (!previousMismatch) {
  7270. previousMismatch = true;
  7271. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  7272. << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
  7273. << getRedeclDiagFromTagKind(I->getTagKind());
  7274. }
  7275. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  7276. << getRedeclDiagFromTagKind(NewTag)
  7277. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  7278. TypeWithKeyword::getTagTypeKindName(NewTag));
  7279. }
  7280. }
  7281. return true;
  7282. }
  7283. // Check for a previous definition. If current tag and definition
  7284. // are same type, do nothing. If no definition, but disagree with
  7285. // with previous tag type, give a warning, but no fix-it.
  7286. const TagDecl *Redecl = Previous->getDefinition() ?
  7287. Previous->getDefinition() : Previous;
  7288. if (Redecl->getTagKind() == NewTag) {
  7289. return true;
  7290. }
  7291. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  7292. << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
  7293. << getRedeclDiagFromTagKind(OldTag);
  7294. Diag(Redecl->getLocation(), diag::note_previous_use);
  7295. // If there is a previous defintion, suggest a fix-it.
  7296. if (Previous->getDefinition()) {
  7297. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  7298. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  7299. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  7300. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  7301. }
  7302. return true;
  7303. }
  7304. return false;
  7305. }
  7306. /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
  7307. /// former case, Name will be non-null. In the later case, Name will be null.
  7308. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  7309. /// reference/declaration/definition of a tag.
  7310. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  7311. SourceLocation KWLoc, CXXScopeSpec &SS,
  7312. IdentifierInfo *Name, SourceLocation NameLoc,
  7313. AttributeList *Attr, AccessSpecifier AS,
  7314. SourceLocation ModulePrivateLoc,
  7315. MultiTemplateParamsArg TemplateParameterLists,
  7316. bool &OwnedDecl, bool &IsDependent,
  7317. SourceLocation ScopedEnumKWLoc,
  7318. bool ScopedEnumUsesClassTag,
  7319. TypeResult UnderlyingType) {
  7320. // If this is not a definition, it must have a name.
  7321. IdentifierInfo *OrigName = Name;
  7322. assert((Name != 0 || TUK == TUK_Definition) &&
  7323. "Nameless record must be a definition!");
  7324. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  7325. OwnedDecl = false;
  7326. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  7327. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  7328. // FIXME: Check explicit specializations more carefully.
  7329. bool isExplicitSpecialization = false;
  7330. bool Invalid = false;
  7331. // We only need to do this matching if we have template parameters
  7332. // or a scope specifier, which also conveniently avoids this work
  7333. // for non-C++ cases.
  7334. if (TemplateParameterLists.size() > 0 ||
  7335. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  7336. if (TemplateParameterList *TemplateParams
  7337. = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
  7338. TemplateParameterLists.data(),
  7339. TemplateParameterLists.size(),
  7340. TUK == TUK_Friend,
  7341. isExplicitSpecialization,
  7342. Invalid)) {
  7343. if (TemplateParams->size() > 0) {
  7344. // This is a declaration or definition of a class template (which may
  7345. // be a member of another template).
  7346. if (Invalid)
  7347. return 0;
  7348. OwnedDecl = false;
  7349. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  7350. SS, Name, NameLoc, Attr,
  7351. TemplateParams, AS,
  7352. ModulePrivateLoc,
  7353. TemplateParameterLists.size()-1,
  7354. TemplateParameterLists.data());
  7355. return Result.get();
  7356. } else {
  7357. // The "template<>" header is extraneous.
  7358. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  7359. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  7360. isExplicitSpecialization = true;
  7361. }
  7362. }
  7363. }
  7364. // Figure out the underlying type if this a enum declaration. We need to do
  7365. // this early, because it's needed to detect if this is an incompatible
  7366. // redeclaration.
  7367. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  7368. if (Kind == TTK_Enum) {
  7369. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
  7370. // No underlying type explicitly specified, or we failed to parse the
  7371. // type, default to int.
  7372. EnumUnderlying = Context.IntTy.getTypePtr();
  7373. else if (UnderlyingType.get()) {
  7374. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  7375. // integral type; any cv-qualification is ignored.
  7376. TypeSourceInfo *TI = 0;
  7377. GetTypeFromParser(UnderlyingType.get(), &TI);
  7378. EnumUnderlying = TI;
  7379. if (CheckEnumUnderlyingType(TI))
  7380. // Recover by falling back to int.
  7381. EnumUnderlying = Context.IntTy.getTypePtr();
  7382. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  7383. UPPC_FixedUnderlyingType))
  7384. EnumUnderlying = Context.IntTy.getTypePtr();
  7385. } else if (getLangOpts().MicrosoftMode)
  7386. // Microsoft enums are always of int type.
  7387. EnumUnderlying = Context.IntTy.getTypePtr();
  7388. }
  7389. DeclContext *SearchDC = CurContext;
  7390. DeclContext *DC = CurContext;
  7391. bool isStdBadAlloc = false;
  7392. RedeclarationKind Redecl = ForRedeclaration;
  7393. if (TUK == TUK_Friend || TUK == TUK_Reference)
  7394. Redecl = NotForRedeclaration;
  7395. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  7396. if (Name && SS.isNotEmpty()) {
  7397. // We have a nested-name tag ('struct foo::bar').
  7398. // Check for invalid 'foo::'.
  7399. if (SS.isInvalid()) {
  7400. Name = 0;
  7401. goto CreateNewDecl;
  7402. }
  7403. // If this is a friend or a reference to a class in a dependent
  7404. // context, don't try to make a decl for it.
  7405. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  7406. DC = computeDeclContext(SS, false);
  7407. if (!DC) {
  7408. IsDependent = true;
  7409. return 0;
  7410. }
  7411. } else {
  7412. DC = computeDeclContext(SS, true);
  7413. if (!DC) {
  7414. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  7415. << SS.getRange();
  7416. return 0;
  7417. }
  7418. }
  7419. if (RequireCompleteDeclContext(SS, DC))
  7420. return 0;
  7421. SearchDC = DC;
  7422. // Look-up name inside 'foo::'.
  7423. LookupQualifiedName(Previous, DC);
  7424. if (Previous.isAmbiguous())
  7425. return 0;
  7426. if (Previous.empty()) {
  7427. // Name lookup did not find anything. However, if the
  7428. // nested-name-specifier refers to the current instantiation,
  7429. // and that current instantiation has any dependent base
  7430. // classes, we might find something at instantiation time: treat
  7431. // this as a dependent elaborated-type-specifier.
  7432. // But this only makes any sense for reference-like lookups.
  7433. if (Previous.wasNotFoundInCurrentInstantiation() &&
  7434. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  7435. IsDependent = true;
  7436. return 0;
  7437. }
  7438. // A tag 'foo::bar' must already exist.
  7439. Diag(NameLoc, diag::err_not_tag_in_scope)
  7440. << Kind << Name << DC << SS.getRange();
  7441. Name = 0;
  7442. Invalid = true;
  7443. goto CreateNewDecl;
  7444. }
  7445. } else if (Name) {
  7446. // If this is a named struct, check to see if there was a previous forward
  7447. // declaration or definition.
  7448. // FIXME: We're looking into outer scopes here, even when we
  7449. // shouldn't be. Doing so can result in ambiguities that we
  7450. // shouldn't be diagnosing.
  7451. LookupName(Previous, S);
  7452. if (Previous.isAmbiguous() &&
  7453. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  7454. LookupResult::Filter F = Previous.makeFilter();
  7455. while (F.hasNext()) {
  7456. NamedDecl *ND = F.next();
  7457. if (ND->getDeclContext()->getRedeclContext() != SearchDC)
  7458. F.erase();
  7459. }
  7460. F.done();
  7461. }
  7462. // Note: there used to be some attempt at recovery here.
  7463. if (Previous.isAmbiguous())
  7464. return 0;
  7465. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  7466. // FIXME: This makes sure that we ignore the contexts associated
  7467. // with C structs, unions, and enums when looking for a matching
  7468. // tag declaration or definition. See the similar lookup tweak
  7469. // in Sema::LookupName; is there a better way to deal with this?
  7470. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  7471. SearchDC = SearchDC->getParent();
  7472. }
  7473. } else if (S->isFunctionPrototypeScope()) {
  7474. // If this is an enum declaration in function prototype scope, set its
  7475. // initial context to the translation unit.
  7476. // FIXME: [citation needed]
  7477. SearchDC = Context.getTranslationUnitDecl();
  7478. }
  7479. if (Previous.isSingleResult() &&
  7480. Previous.getFoundDecl()->isTemplateParameter()) {
  7481. // Maybe we will complain about the shadowed template parameter.
  7482. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  7483. // Just pretend that we didn't see the previous declaration.
  7484. Previous.clear();
  7485. }
  7486. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  7487. DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
  7488. // This is a declaration of or a reference to "std::bad_alloc".
  7489. isStdBadAlloc = true;
  7490. if (Previous.empty() && StdBadAlloc) {
  7491. // std::bad_alloc has been implicitly declared (but made invisible to
  7492. // name lookup). Fill in this implicit declaration as the previous
  7493. // declaration, so that the declarations get chained appropriately.
  7494. Previous.addDecl(getStdBadAlloc());
  7495. }
  7496. }
  7497. // If we didn't find a previous declaration, and this is a reference
  7498. // (or friend reference), move to the correct scope. In C++, we
  7499. // also need to do a redeclaration lookup there, just in case
  7500. // there's a shadow friend decl.
  7501. if (Name && Previous.empty() &&
  7502. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  7503. if (Invalid) goto CreateNewDecl;
  7504. assert(SS.isEmpty());
  7505. if (TUK == TUK_Reference) {
  7506. // C++ [basic.scope.pdecl]p5:
  7507. // -- for an elaborated-type-specifier of the form
  7508. //
  7509. // class-key identifier
  7510. //
  7511. // if the elaborated-type-specifier is used in the
  7512. // decl-specifier-seq or parameter-declaration-clause of a
  7513. // function defined in namespace scope, the identifier is
  7514. // declared as a class-name in the namespace that contains
  7515. // the declaration; otherwise, except as a friend
  7516. // declaration, the identifier is declared in the smallest
  7517. // non-class, non-function-prototype scope that contains the
  7518. // declaration.
  7519. //
  7520. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  7521. // C structs and unions.
  7522. //
  7523. // It is an error in C++ to declare (rather than define) an enum
  7524. // type, including via an elaborated type specifier. We'll
  7525. // diagnose that later; for now, declare the enum in the same
  7526. // scope as we would have picked for any other tag type.
  7527. //
  7528. // GNU C also supports this behavior as part of its incomplete
  7529. // enum types extension, while GNU C++ does not.
  7530. //
  7531. // Find the context where we'll be declaring the tag.
  7532. // FIXME: We would like to maintain the current DeclContext as the
  7533. // lexical context,
  7534. while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
  7535. SearchDC = SearchDC->getParent();
  7536. // Find the scope where we'll be declaring the tag.
  7537. while (S->isClassScope() ||
  7538. (getLangOpts().CPlusPlus &&
  7539. S->isFunctionPrototypeScope()) ||
  7540. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7541. (S->getEntity() &&
  7542. ((DeclContext *)S->getEntity())->isTransparentContext()))
  7543. S = S->getParent();
  7544. } else {
  7545. assert(TUK == TUK_Friend);
  7546. // C++ [namespace.memdef]p3:
  7547. // If a friend declaration in a non-local class first declares a
  7548. // class or function, the friend class or function is a member of
  7549. // the innermost enclosing namespace.
  7550. SearchDC = SearchDC->getEnclosingNamespaceContext();
  7551. }
  7552. // In C++, we need to do a redeclaration lookup to properly
  7553. // diagnose some problems.
  7554. if (getLangOpts().CPlusPlus) {
  7555. Previous.setRedeclarationKind(ForRedeclaration);
  7556. LookupQualifiedName(Previous, SearchDC);
  7557. }
  7558. }
  7559. if (!Previous.empty()) {
  7560. NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
  7561. // It's okay to have a tag decl in the same scope as a typedef
  7562. // which hides a tag decl in the same scope. Finding this
  7563. // insanity with a redeclaration lookup can only actually happen
  7564. // in C++.
  7565. //
  7566. // This is also okay for elaborated-type-specifiers, which is
  7567. // technically forbidden by the current standard but which is
  7568. // okay according to the likely resolution of an open issue;
  7569. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  7570. if (getLangOpts().CPlusPlus) {
  7571. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  7572. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  7573. TagDecl *Tag = TT->getDecl();
  7574. if (Tag->getDeclName() == Name &&
  7575. Tag->getDeclContext()->getRedeclContext()
  7576. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  7577. PrevDecl = Tag;
  7578. Previous.clear();
  7579. Previous.addDecl(Tag);
  7580. Previous.resolveKind();
  7581. }
  7582. }
  7583. }
  7584. }
  7585. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  7586. // If this is a use of a previous tag, or if the tag is already declared
  7587. // in the same scope (so that the definition/declaration completes or
  7588. // rementions the tag), reuse the decl.
  7589. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  7590. isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
  7591. // Make sure that this wasn't declared as an enum and now used as a
  7592. // struct or something similar.
  7593. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  7594. TUK == TUK_Definition, KWLoc,
  7595. *Name)) {
  7596. bool SafeToContinue
  7597. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  7598. Kind != TTK_Enum);
  7599. if (SafeToContinue)
  7600. Diag(KWLoc, diag::err_use_with_wrong_tag)
  7601. << Name
  7602. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  7603. PrevTagDecl->getKindName());
  7604. else
  7605. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  7606. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  7607. if (SafeToContinue)
  7608. Kind = PrevTagDecl->getTagKind();
  7609. else {
  7610. // Recover by making this an anonymous redefinition.
  7611. Name = 0;
  7612. Previous.clear();
  7613. Invalid = true;
  7614. }
  7615. }
  7616. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  7617. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  7618. // If this is an elaborated-type-specifier for a scoped enumeration,
  7619. // the 'class' keyword is not necessary and not permitted.
  7620. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  7621. if (ScopedEnum)
  7622. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  7623. << PrevEnum->isScoped()
  7624. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  7625. return PrevTagDecl;
  7626. }
  7627. QualType EnumUnderlyingTy;
  7628. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  7629. EnumUnderlyingTy = TI->getType();
  7630. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  7631. EnumUnderlyingTy = QualType(T, 0);
  7632. // All conflicts with previous declarations are recovered by
  7633. // returning the previous declaration, unless this is a definition,
  7634. // in which case we want the caller to bail out.
  7635. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  7636. ScopedEnum, EnumUnderlyingTy, PrevEnum))
  7637. return TUK == TUK_Declaration ? PrevTagDecl : 0;
  7638. }
  7639. if (!Invalid) {
  7640. // If this is a use, just return the declaration we found.
  7641. // FIXME: In the future, return a variant or some other clue
  7642. // for the consumer of this Decl to know it doesn't own it.
  7643. // For our current ASTs this shouldn't be a problem, but will
  7644. // need to be changed with DeclGroups.
  7645. if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
  7646. getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
  7647. return PrevTagDecl;
  7648. // Diagnose attempts to redefine a tag.
  7649. if (TUK == TUK_Definition) {
  7650. if (TagDecl *Def = PrevTagDecl->getDefinition()) {
  7651. // If we're defining a specialization and the previous definition
  7652. // is from an implicit instantiation, don't emit an error
  7653. // here; we'll catch this in the general case below.
  7654. bool IsExplicitSpecializationAfterInstantiation = false;
  7655. if (isExplicitSpecialization) {
  7656. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  7657. IsExplicitSpecializationAfterInstantiation =
  7658. RD->getTemplateSpecializationKind() !=
  7659. TSK_ExplicitSpecialization;
  7660. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  7661. IsExplicitSpecializationAfterInstantiation =
  7662. ED->getTemplateSpecializationKind() !=
  7663. TSK_ExplicitSpecialization;
  7664. }
  7665. if (!IsExplicitSpecializationAfterInstantiation) {
  7666. // A redeclaration in function prototype scope in C isn't
  7667. // visible elsewhere, so merely issue a warning.
  7668. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  7669. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  7670. else
  7671. Diag(NameLoc, diag::err_redefinition) << Name;
  7672. Diag(Def->getLocation(), diag::note_previous_definition);
  7673. // If this is a redefinition, recover by making this
  7674. // struct be anonymous, which will make any later
  7675. // references get the previous definition.
  7676. Name = 0;
  7677. Previous.clear();
  7678. Invalid = true;
  7679. }
  7680. } else {
  7681. // If the type is currently being defined, complain
  7682. // about a nested redefinition.
  7683. const TagType *Tag
  7684. = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
  7685. if (Tag->isBeingDefined()) {
  7686. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  7687. Diag(PrevTagDecl->getLocation(),
  7688. diag::note_previous_definition);
  7689. Name = 0;
  7690. Previous.clear();
  7691. Invalid = true;
  7692. }
  7693. }
  7694. // Okay, this is definition of a previously declared or referenced
  7695. // tag PrevDecl. We're going to create a new Decl for it.
  7696. }
  7697. }
  7698. // If we get here we have (another) forward declaration or we
  7699. // have a definition. Just create a new decl.
  7700. } else {
  7701. // If we get here, this is a definition of a new tag type in a nested
  7702. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  7703. // new decl/type. We set PrevDecl to NULL so that the entities
  7704. // have distinct types.
  7705. Previous.clear();
  7706. }
  7707. // If we get here, we're going to create a new Decl. If PrevDecl
  7708. // is non-NULL, it's a definition of the tag declared by
  7709. // PrevDecl. If it's NULL, we have a new definition.
  7710. // Otherwise, PrevDecl is not a tag, but was found with tag
  7711. // lookup. This is only actually possible in C++, where a few
  7712. // things like templates still live in the tag namespace.
  7713. } else {
  7714. // Use a better diagnostic if an elaborated-type-specifier
  7715. // found the wrong kind of type on the first
  7716. // (non-redeclaration) lookup.
  7717. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  7718. !Previous.isForRedeclaration()) {
  7719. unsigned Kind = 0;
  7720. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  7721. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  7722. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  7723. Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
  7724. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  7725. Invalid = true;
  7726. // Otherwise, only diagnose if the declaration is in scope.
  7727. } else if (!isDeclInScope(PrevDecl, SearchDC, S,
  7728. isExplicitSpecialization)) {
  7729. // do nothing
  7730. // Diagnose implicit declarations introduced by elaborated types.
  7731. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  7732. unsigned Kind = 0;
  7733. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  7734. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  7735. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  7736. Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
  7737. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  7738. Invalid = true;
  7739. // Otherwise it's a declaration. Call out a particularly common
  7740. // case here.
  7741. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  7742. unsigned Kind = 0;
  7743. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  7744. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  7745. << Name << Kind << TND->getUnderlyingType();
  7746. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  7747. Invalid = true;
  7748. // Otherwise, diagnose.
  7749. } else {
  7750. // The tag name clashes with something else in the target scope,
  7751. // issue an error and recover by making this tag be anonymous.
  7752. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  7753. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  7754. Name = 0;
  7755. Invalid = true;
  7756. }
  7757. // The existing declaration isn't relevant to us; we're in a
  7758. // new scope, so clear out the previous declaration.
  7759. Previous.clear();
  7760. }
  7761. }
  7762. CreateNewDecl:
  7763. TagDecl *PrevDecl = 0;
  7764. if (Previous.isSingleResult())
  7765. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  7766. // If there is an identifier, use the location of the identifier as the
  7767. // location of the decl, otherwise use the location of the struct/union
  7768. // keyword.
  7769. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  7770. // Otherwise, create a new declaration. If there is a previous
  7771. // declaration of the same entity, the two will be linked via
  7772. // PrevDecl.
  7773. TagDecl *New;
  7774. bool IsForwardReference = false;
  7775. if (Kind == TTK_Enum) {
  7776. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  7777. // enum X { A, B, C } D; D should chain to X.
  7778. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  7779. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  7780. ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
  7781. // If this is an undefined enum, warn.
  7782. if (TUK != TUK_Definition && !Invalid) {
  7783. TagDecl *Def;
  7784. if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
  7785. // C++0x: 7.2p2: opaque-enum-declaration.
  7786. // Conflicts are diagnosed above. Do nothing.
  7787. }
  7788. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  7789. Diag(Loc, diag::ext_forward_ref_enum_def)
  7790. << New;
  7791. Diag(Def->getLocation(), diag::note_previous_definition);
  7792. } else {
  7793. unsigned DiagID = diag::ext_forward_ref_enum;
  7794. if (getLangOpts().MicrosoftMode)
  7795. DiagID = diag::ext_ms_forward_ref_enum;
  7796. else if (getLangOpts().CPlusPlus)
  7797. DiagID = diag::err_forward_ref_enum;
  7798. Diag(Loc, DiagID);
  7799. // If this is a forward-declared reference to an enumeration, make a
  7800. // note of it; we won't actually be introducing the declaration into
  7801. // the declaration context.
  7802. if (TUK == TUK_Reference)
  7803. IsForwardReference = true;
  7804. }
  7805. }
  7806. if (EnumUnderlying) {
  7807. EnumDecl *ED = cast<EnumDecl>(New);
  7808. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  7809. ED->setIntegerTypeSourceInfo(TI);
  7810. else
  7811. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  7812. ED->setPromotionType(ED->getIntegerType());
  7813. }
  7814. } else {
  7815. // struct/union/class
  7816. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  7817. // struct X { int A; } D; D should chain to X.
  7818. if (getLangOpts().CPlusPlus) {
  7819. // FIXME: Look for a way to use RecordDecl for simple structs.
  7820. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  7821. cast_or_null<CXXRecordDecl>(PrevDecl));
  7822. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  7823. StdBadAlloc = cast<CXXRecordDecl>(New);
  7824. } else
  7825. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  7826. cast_or_null<RecordDecl>(PrevDecl));
  7827. }
  7828. // Maybe add qualifier info.
  7829. if (SS.isNotEmpty()) {
  7830. if (SS.isSet()) {
  7831. // If this is either a declaration or a definition, check the
  7832. // nested-name-specifier against the current context. We don't do this
  7833. // for explicit specializations, because they have similar checking
  7834. // (with more specific diagnostics) in the call to
  7835. // CheckMemberSpecialization, below.
  7836. if (!isExplicitSpecialization &&
  7837. (TUK == TUK_Definition || TUK == TUK_Declaration) &&
  7838. diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
  7839. Invalid = true;
  7840. New->setQualifierInfo(SS.getWithLocInContext(Context));
  7841. if (TemplateParameterLists.size() > 0) {
  7842. New->setTemplateParameterListsInfo(Context,
  7843. TemplateParameterLists.size(),
  7844. TemplateParameterLists.data());
  7845. }
  7846. }
  7847. else
  7848. Invalid = true;
  7849. }
  7850. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  7851. // Add alignment attributes if necessary; these attributes are checked when
  7852. // the ASTContext lays out the structure.
  7853. //
  7854. // It is important for implementing the correct semantics that this
  7855. // happen here (in act on tag decl). The #pragma pack stack is
  7856. // maintained as a result of parser callbacks which can occur at
  7857. // many points during the parsing of a struct declaration (because
  7858. // the #pragma tokens are effectively skipped over during the
  7859. // parsing of the struct).
  7860. if (TUK == TUK_Definition) {
  7861. AddAlignmentAttributesForRecord(RD);
  7862. AddMsStructLayoutForRecord(RD);
  7863. }
  7864. }
  7865. if (ModulePrivateLoc.isValid()) {
  7866. if (isExplicitSpecialization)
  7867. Diag(New->getLocation(), diag::err_module_private_specialization)
  7868. << 2
  7869. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7870. // __module_private__ does not apply to local classes. However, we only
  7871. // diagnose this as an error when the declaration specifiers are
  7872. // freestanding. Here, we just ignore the __module_private__.
  7873. else if (!SearchDC->isFunctionOrMethod())
  7874. New->setModulePrivate();
  7875. }
  7876. // If this is a specialization of a member class (of a class template),
  7877. // check the specialization.
  7878. if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
  7879. Invalid = true;
  7880. if (Invalid)
  7881. New->setInvalidDecl();
  7882. if (Attr)
  7883. ProcessDeclAttributeList(S, New, Attr);
  7884. // If we're declaring or defining a tag in function prototype scope
  7885. // in C, note that this type can only be used within the function.
  7886. if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
  7887. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  7888. // Set the lexical context. If the tag has a C++ scope specifier, the
  7889. // lexical context will be different from the semantic context.
  7890. New->setLexicalDeclContext(CurContext);
  7891. // Mark this as a friend decl if applicable.
  7892. // In Microsoft mode, a friend declaration also acts as a forward
  7893. // declaration so we always pass true to setObjectOfFriendDecl to make
  7894. // the tag name visible.
  7895. if (TUK == TUK_Friend)
  7896. New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
  7897. getLangOpts().MicrosoftExt);
  7898. // Set the access specifier.
  7899. if (!Invalid && SearchDC->isRecord())
  7900. SetMemberAccessSpecifier(New, PrevDecl, AS);
  7901. if (TUK == TUK_Definition)
  7902. New->startDefinition();
  7903. // If this has an identifier, add it to the scope stack.
  7904. if (TUK == TUK_Friend) {
  7905. // We might be replacing an existing declaration in the lookup tables;
  7906. // if so, borrow its access specifier.
  7907. if (PrevDecl)
  7908. New->setAccess(PrevDecl->getAccess());
  7909. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  7910. DC->makeDeclVisibleInContext(New);
  7911. if (Name) // can be null along some error paths
  7912. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  7913. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  7914. } else if (Name) {
  7915. S = getNonFieldDeclScope(S);
  7916. PushOnScopeChains(New, S, !IsForwardReference);
  7917. if (IsForwardReference)
  7918. SearchDC->makeDeclVisibleInContext(New);
  7919. } else {
  7920. CurContext->addDecl(New);
  7921. }
  7922. // If this is the C FILE type, notify the AST context.
  7923. if (IdentifierInfo *II = New->getIdentifier())
  7924. if (!New->isInvalidDecl() &&
  7925. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  7926. II->isStr("FILE"))
  7927. Context.setFILEDecl(New);
  7928. // If we were in function prototype scope (and not in C++ mode), add this
  7929. // tag to the list of decls to inject into the function definition scope.
  7930. if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
  7931. InFunctionDeclarator && Name)
  7932. DeclsInPrototypeScope.push_back(New);
  7933. if (PrevDecl)
  7934. mergeDeclAttributes(New, PrevDecl);
  7935. // If there's a #pragma GCC visibility in scope, set the visibility of this
  7936. // record.
  7937. AddPushedVisibilityAttribute(New);
  7938. OwnedDecl = true;
  7939. return New;
  7940. }
  7941. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  7942. AdjustDeclIfTemplate(TagD);
  7943. TagDecl *Tag = cast<TagDecl>(TagD);
  7944. // Enter the tag context.
  7945. PushDeclContext(S, Tag);
  7946. ActOnDocumentableDecl(TagD);
  7947. // If there's a #pragma GCC visibility in scope, set the visibility of this
  7948. // record.
  7949. AddPushedVisibilityAttribute(Tag);
  7950. }
  7951. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  7952. assert(isa<ObjCContainerDecl>(IDecl) &&
  7953. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  7954. DeclContext *OCD = cast<DeclContext>(IDecl);
  7955. assert(getContainingDC(OCD) == CurContext &&
  7956. "The next DeclContext should be lexically contained in the current one.");
  7957. CurContext = OCD;
  7958. return IDecl;
  7959. }
  7960. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  7961. SourceLocation FinalLoc,
  7962. SourceLocation LBraceLoc) {
  7963. AdjustDeclIfTemplate(TagD);
  7964. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  7965. FieldCollector->StartClass();
  7966. if (!Record->getIdentifier())
  7967. return;
  7968. if (FinalLoc.isValid())
  7969. Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
  7970. // C++ [class]p2:
  7971. // [...] The class-name is also inserted into the scope of the
  7972. // class itself; this is known as the injected-class-name. For
  7973. // purposes of access checking, the injected-class-name is treated
  7974. // as if it were a public member name.
  7975. CXXRecordDecl *InjectedClassName
  7976. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  7977. Record->getLocStart(), Record->getLocation(),
  7978. Record->getIdentifier(),
  7979. /*PrevDecl=*/0,
  7980. /*DelayTypeCreation=*/true);
  7981. Context.getTypeDeclType(InjectedClassName, Record);
  7982. InjectedClassName->setImplicit();
  7983. InjectedClassName->setAccess(AS_public);
  7984. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  7985. InjectedClassName->setDescribedClassTemplate(Template);
  7986. PushOnScopeChains(InjectedClassName, S);
  7987. assert(InjectedClassName->isInjectedClassName() &&
  7988. "Broken injected-class-name");
  7989. }
  7990. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  7991. SourceLocation RBraceLoc) {
  7992. AdjustDeclIfTemplate(TagD);
  7993. TagDecl *Tag = cast<TagDecl>(TagD);
  7994. Tag->setRBraceLoc(RBraceLoc);
  7995. // Make sure we "complete" the definition even it is invalid.
  7996. if (Tag->isBeingDefined()) {
  7997. assert(Tag->isInvalidDecl() && "We should already have completed it");
  7998. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  7999. RD->completeDefinition();
  8000. }
  8001. if (isa<CXXRecordDecl>(Tag))
  8002. FieldCollector->FinishClass();
  8003. // Exit this scope of this tag's definition.
  8004. PopDeclContext();
  8005. // Notify the consumer that we've defined a tag.
  8006. Consumer.HandleTagDeclDefinition(Tag);
  8007. }
  8008. void Sema::ActOnObjCContainerFinishDefinition() {
  8009. // Exit this scope of this interface definition.
  8010. PopDeclContext();
  8011. }
  8012. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  8013. assert(DC == CurContext && "Mismatch of container contexts");
  8014. OriginalLexicalContext = DC;
  8015. ActOnObjCContainerFinishDefinition();
  8016. }
  8017. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  8018. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  8019. OriginalLexicalContext = 0;
  8020. }
  8021. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  8022. AdjustDeclIfTemplate(TagD);
  8023. TagDecl *Tag = cast<TagDecl>(TagD);
  8024. Tag->setInvalidDecl();
  8025. // Make sure we "complete" the definition even it is invalid.
  8026. if (Tag->isBeingDefined()) {
  8027. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  8028. RD->completeDefinition();
  8029. }
  8030. // We're undoing ActOnTagStartDefinition here, not
  8031. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  8032. // the FieldCollector.
  8033. PopDeclContext();
  8034. }
  8035. // Note that FieldName may be null for anonymous bitfields.
  8036. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  8037. IdentifierInfo *FieldName,
  8038. QualType FieldTy, Expr *BitWidth,
  8039. bool *ZeroWidth) {
  8040. // Default to true; that shouldn't confuse checks for emptiness
  8041. if (ZeroWidth)
  8042. *ZeroWidth = true;
  8043. // C99 6.7.2.1p4 - verify the field type.
  8044. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  8045. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  8046. // Handle incomplete types with specific error.
  8047. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  8048. return ExprError();
  8049. if (FieldName)
  8050. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  8051. << FieldName << FieldTy << BitWidth->getSourceRange();
  8052. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  8053. << FieldTy << BitWidth->getSourceRange();
  8054. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  8055. UPPC_BitFieldWidth))
  8056. return ExprError();
  8057. // If the bit-width is type- or value-dependent, don't try to check
  8058. // it now.
  8059. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  8060. return Owned(BitWidth);
  8061. llvm::APSInt Value;
  8062. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  8063. if (ICE.isInvalid())
  8064. return ICE;
  8065. BitWidth = ICE.take();
  8066. if (Value != 0 && ZeroWidth)
  8067. *ZeroWidth = false;
  8068. // Zero-width bitfield is ok for anonymous field.
  8069. if (Value == 0 && FieldName)
  8070. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  8071. if (Value.isSigned() && Value.isNegative()) {
  8072. if (FieldName)
  8073. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  8074. << FieldName << Value.toString(10);
  8075. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  8076. << Value.toString(10);
  8077. }
  8078. if (!FieldTy->isDependentType()) {
  8079. uint64_t TypeSize = Context.getTypeSize(FieldTy);
  8080. if (Value.getZExtValue() > TypeSize) {
  8081. if (!getLangOpts().CPlusPlus) {
  8082. if (FieldName)
  8083. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
  8084. << FieldName << (unsigned)Value.getZExtValue()
  8085. << (unsigned)TypeSize;
  8086. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
  8087. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  8088. }
  8089. if (FieldName)
  8090. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
  8091. << FieldName << (unsigned)Value.getZExtValue()
  8092. << (unsigned)TypeSize;
  8093. else
  8094. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
  8095. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  8096. }
  8097. }
  8098. return Owned(BitWidth);
  8099. }
  8100. /// ActOnField - Each field of a C struct/union is passed into this in order
  8101. /// to create a FieldDecl object for it.
  8102. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  8103. Declarator &D, Expr *BitfieldWidth) {
  8104. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  8105. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  8106. /*InitStyle=*/ICIS_NoInit, AS_public);
  8107. return Res;
  8108. }
  8109. /// HandleField - Analyze a field of a C struct or a C++ data member.
  8110. ///
  8111. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  8112. SourceLocation DeclStart,
  8113. Declarator &D, Expr *BitWidth,
  8114. InClassInitStyle InitStyle,
  8115. AccessSpecifier AS) {
  8116. IdentifierInfo *II = D.getIdentifier();
  8117. SourceLocation Loc = DeclStart;
  8118. if (II) Loc = D.getIdentifierLoc();
  8119. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  8120. QualType T = TInfo->getType();
  8121. if (getLangOpts().CPlusPlus) {
  8122. CheckExtraCXXDefaultArguments(D);
  8123. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  8124. UPPC_DataMemberType)) {
  8125. D.setInvalidType();
  8126. T = Context.IntTy;
  8127. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  8128. }
  8129. }
  8130. DiagnoseFunctionSpecifiers(D);
  8131. if (D.getDeclSpec().isThreadSpecified())
  8132. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  8133. if (D.getDeclSpec().isConstexprSpecified())
  8134. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  8135. << 2;
  8136. // Check to see if this name was declared as a member previously
  8137. NamedDecl *PrevDecl = 0;
  8138. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  8139. LookupName(Previous, S);
  8140. switch (Previous.getResultKind()) {
  8141. case LookupResult::Found:
  8142. case LookupResult::FoundUnresolvedValue:
  8143. PrevDecl = Previous.getAsSingle<NamedDecl>();
  8144. break;
  8145. case LookupResult::FoundOverloaded:
  8146. PrevDecl = Previous.getRepresentativeDecl();
  8147. break;
  8148. case LookupResult::NotFound:
  8149. case LookupResult::NotFoundInCurrentInstantiation:
  8150. case LookupResult::Ambiguous:
  8151. break;
  8152. }
  8153. Previous.suppressDiagnostics();
  8154. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  8155. // Maybe we will complain about the shadowed template parameter.
  8156. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  8157. // Just pretend that we didn't see the previous declaration.
  8158. PrevDecl = 0;
  8159. }
  8160. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  8161. PrevDecl = 0;
  8162. bool Mutable
  8163. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  8164. SourceLocation TSSL = D.getLocStart();
  8165. FieldDecl *NewFD
  8166. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  8167. TSSL, AS, PrevDecl, &D);
  8168. if (NewFD->isInvalidDecl())
  8169. Record->setInvalidDecl();
  8170. if (D.getDeclSpec().isModulePrivateSpecified())
  8171. NewFD->setModulePrivate();
  8172. if (NewFD->isInvalidDecl() && PrevDecl) {
  8173. // Don't introduce NewFD into scope; there's already something
  8174. // with the same name in the same scope.
  8175. } else if (II) {
  8176. PushOnScopeChains(NewFD, S);
  8177. } else
  8178. Record->addDecl(NewFD);
  8179. return NewFD;
  8180. }
  8181. /// \brief Build a new FieldDecl and check its well-formedness.
  8182. ///
  8183. /// This routine builds a new FieldDecl given the fields name, type,
  8184. /// record, etc. \p PrevDecl should refer to any previous declaration
  8185. /// with the same name and in the same scope as the field to be
  8186. /// created.
  8187. ///
  8188. /// \returns a new FieldDecl.
  8189. ///
  8190. /// \todo The Declarator argument is a hack. It will be removed once
  8191. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  8192. TypeSourceInfo *TInfo,
  8193. RecordDecl *Record, SourceLocation Loc,
  8194. bool Mutable, Expr *BitWidth,
  8195. InClassInitStyle InitStyle,
  8196. SourceLocation TSSL,
  8197. AccessSpecifier AS, NamedDecl *PrevDecl,
  8198. Declarator *D) {
  8199. IdentifierInfo *II = Name.getAsIdentifierInfo();
  8200. bool InvalidDecl = false;
  8201. if (D) InvalidDecl = D->isInvalidType();
  8202. // If we receive a broken type, recover by assuming 'int' and
  8203. // marking this declaration as invalid.
  8204. if (T.isNull()) {
  8205. InvalidDecl = true;
  8206. T = Context.IntTy;
  8207. }
  8208. QualType EltTy = Context.getBaseElementType(T);
  8209. if (!EltTy->isDependentType()) {
  8210. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  8211. // Fields of incomplete type force their record to be invalid.
  8212. Record->setInvalidDecl();
  8213. InvalidDecl = true;
  8214. } else {
  8215. NamedDecl *Def;
  8216. EltTy->isIncompleteType(&Def);
  8217. if (Def && Def->isInvalidDecl()) {
  8218. Record->setInvalidDecl();
  8219. InvalidDecl = true;
  8220. }
  8221. }
  8222. }
  8223. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  8224. // than a variably modified type.
  8225. if (!InvalidDecl && T->isVariablyModifiedType()) {
  8226. bool SizeIsNegative;
  8227. llvm::APSInt Oversized;
  8228. QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
  8229. SizeIsNegative,
  8230. Oversized);
  8231. if (!FixedTy.isNull()) {
  8232. Diag(Loc, diag::warn_illegal_constant_array_size);
  8233. T = FixedTy;
  8234. } else {
  8235. if (SizeIsNegative)
  8236. Diag(Loc, diag::err_typecheck_negative_array_size);
  8237. else if (Oversized.getBoolValue())
  8238. Diag(Loc, diag::err_array_too_large)
  8239. << Oversized.toString(10);
  8240. else
  8241. Diag(Loc, diag::err_typecheck_field_variable_size);
  8242. InvalidDecl = true;
  8243. }
  8244. }
  8245. // Fields can not have abstract class types
  8246. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  8247. diag::err_abstract_type_in_decl,
  8248. AbstractFieldType))
  8249. InvalidDecl = true;
  8250. bool ZeroWidth = false;
  8251. // If this is declared as a bit-field, check the bit-field.
  8252. if (!InvalidDecl && BitWidth) {
  8253. BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
  8254. if (!BitWidth) {
  8255. InvalidDecl = true;
  8256. BitWidth = 0;
  8257. ZeroWidth = false;
  8258. }
  8259. }
  8260. // Check that 'mutable' is consistent with the type of the declaration.
  8261. if (!InvalidDecl && Mutable) {
  8262. unsigned DiagID = 0;
  8263. if (T->isReferenceType())
  8264. DiagID = diag::err_mutable_reference;
  8265. else if (T.isConstQualified())
  8266. DiagID = diag::err_mutable_const;
  8267. if (DiagID) {
  8268. SourceLocation ErrLoc = Loc;
  8269. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  8270. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  8271. Diag(ErrLoc, DiagID);
  8272. Mutable = false;
  8273. InvalidDecl = true;
  8274. }
  8275. }
  8276. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  8277. BitWidth, Mutable, InitStyle);
  8278. if (InvalidDecl)
  8279. NewFD->setInvalidDecl();
  8280. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  8281. Diag(Loc, diag::err_duplicate_member) << II;
  8282. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  8283. NewFD->setInvalidDecl();
  8284. }
  8285. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  8286. if (Record->isUnion()) {
  8287. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  8288. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  8289. if (RDecl->getDefinition()) {
  8290. // C++ [class.union]p1: An object of a class with a non-trivial
  8291. // constructor, a non-trivial copy constructor, a non-trivial
  8292. // destructor, or a non-trivial copy assignment operator
  8293. // cannot be a member of a union, nor can an array of such
  8294. // objects.
  8295. if (CheckNontrivialField(NewFD))
  8296. NewFD->setInvalidDecl();
  8297. }
  8298. }
  8299. // C++ [class.union]p1: If a union contains a member of reference type,
  8300. // the program is ill-formed.
  8301. if (EltTy->isReferenceType()) {
  8302. Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
  8303. << NewFD->getDeclName() << EltTy;
  8304. NewFD->setInvalidDecl();
  8305. }
  8306. }
  8307. }
  8308. // FIXME: We need to pass in the attributes given an AST
  8309. // representation, not a parser representation.
  8310. if (D)
  8311. // FIXME: What to pass instead of TUScope?
  8312. ProcessDeclAttributes(TUScope, NewFD, *D);
  8313. // In auto-retain/release, infer strong retension for fields of
  8314. // retainable type.
  8315. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  8316. NewFD->setInvalidDecl();
  8317. if (T.isObjCGCWeak())
  8318. Diag(Loc, diag::warn_attribute_weak_on_field);
  8319. NewFD->setAccess(AS);
  8320. return NewFD;
  8321. }
  8322. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  8323. assert(FD);
  8324. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  8325. if (FD->isInvalidDecl())
  8326. return true;
  8327. QualType EltTy = Context.getBaseElementType(FD->getType());
  8328. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  8329. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  8330. if (RDecl->getDefinition()) {
  8331. // We check for copy constructors before constructors
  8332. // because otherwise we'll never get complaints about
  8333. // copy constructors.
  8334. CXXSpecialMember member = CXXInvalid;
  8335. if (!RDecl->hasTrivialCopyConstructor())
  8336. member = CXXCopyConstructor;
  8337. else if (!RDecl->hasTrivialDefaultConstructor())
  8338. member = CXXDefaultConstructor;
  8339. else if (!RDecl->hasTrivialCopyAssignment())
  8340. member = CXXCopyAssignment;
  8341. else if (!RDecl->hasTrivialDestructor())
  8342. member = CXXDestructor;
  8343. if (member != CXXInvalid) {
  8344. if (!getLangOpts().CPlusPlus0x &&
  8345. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  8346. // Objective-C++ ARC: it is an error to have a non-trivial field of
  8347. // a union. However, system headers in Objective-C programs
  8348. // occasionally have Objective-C lifetime objects within unions,
  8349. // and rather than cause the program to fail, we make those
  8350. // members unavailable.
  8351. SourceLocation Loc = FD->getLocation();
  8352. if (getSourceManager().isInSystemHeader(Loc)) {
  8353. if (!FD->hasAttr<UnavailableAttr>())
  8354. FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
  8355. "this system field has retaining ownership"));
  8356. return false;
  8357. }
  8358. }
  8359. Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ?
  8360. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  8361. diag::err_illegal_union_or_anon_struct_member)
  8362. << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
  8363. DiagnoseNontrivial(RT, member);
  8364. return !getLangOpts().CPlusPlus0x;
  8365. }
  8366. }
  8367. }
  8368. return false;
  8369. }
  8370. /// If the given constructor is user-declared, produce a diagnostic explaining
  8371. /// that it makes the class non-trivial.
  8372. static bool diagnoseNonTrivialUserDeclaredCtor(Sema &S, QualType QT,
  8373. CXXConstructorDecl *CD,
  8374. Sema::CXXSpecialMember CSM) {
  8375. if (CD->isImplicit())
  8376. return false;
  8377. SourceLocation CtorLoc = CD->getLocation();
  8378. S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM;
  8379. return true;
  8380. }
  8381. /// DiagnoseNontrivial - Given that a class has a non-trivial
  8382. /// special member, figure out why.
  8383. void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
  8384. QualType QT(T, 0U);
  8385. CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
  8386. // Check whether the member was user-declared.
  8387. switch (member) {
  8388. case CXXInvalid:
  8389. break;
  8390. case CXXDefaultConstructor:
  8391. if (RD->hasUserDeclaredConstructor()) {
  8392. typedef CXXRecordDecl::ctor_iterator ctor_iter;
  8393. for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI)
  8394. if (diagnoseNonTrivialUserDeclaredCtor(*this, QT, *CI, member))
  8395. return;
  8396. // No user-delcared constructors; look for constructor templates.
  8397. typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
  8398. tmpl_iter;
  8399. for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end());
  8400. TI != TE; ++TI) {
  8401. CXXConstructorDecl *CD =
  8402. dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl());
  8403. if (CD && diagnoseNonTrivialUserDeclaredCtor(*this, QT, CD, member))
  8404. return;
  8405. }
  8406. }
  8407. break;
  8408. case CXXCopyConstructor:
  8409. if (RD->hasUserDeclaredCopyConstructor()) {
  8410. SourceLocation CtorLoc =
  8411. RD->getCopyConstructor(0)->getLocation();
  8412. Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
  8413. return;
  8414. }
  8415. break;
  8416. case CXXMoveConstructor:
  8417. if (RD->hasUserDeclaredMoveConstructor()) {
  8418. SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
  8419. Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
  8420. return;
  8421. }
  8422. break;
  8423. case CXXCopyAssignment:
  8424. if (RD->hasUserDeclaredCopyAssignment()) {
  8425. SourceLocation AssignLoc =
  8426. RD->getCopyAssignmentOperator(0)->getLocation();
  8427. Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
  8428. return;
  8429. }
  8430. break;
  8431. case CXXMoveAssignment:
  8432. if (RD->hasUserDeclaredMoveAssignment()) {
  8433. SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
  8434. Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
  8435. return;
  8436. }
  8437. break;
  8438. case CXXDestructor:
  8439. if (RD->hasUserDeclaredDestructor()) {
  8440. SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
  8441. Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
  8442. return;
  8443. }
  8444. break;
  8445. }
  8446. typedef CXXRecordDecl::base_class_iterator base_iter;
  8447. // Virtual bases and members inhibit trivial copying/construction,
  8448. // but not trivial destruction.
  8449. if (member != CXXDestructor) {
  8450. // Check for virtual bases. vbases includes indirect virtual bases,
  8451. // so we just iterate through the direct bases.
  8452. for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
  8453. if (bi->isVirtual()) {
  8454. SourceLocation BaseLoc = bi->getLocStart();
  8455. Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
  8456. return;
  8457. }
  8458. // Check for virtual methods.
  8459. typedef CXXRecordDecl::method_iterator meth_iter;
  8460. for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
  8461. ++mi) {
  8462. if (mi->isVirtual()) {
  8463. SourceLocation MLoc = mi->getLocStart();
  8464. Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
  8465. return;
  8466. }
  8467. }
  8468. }
  8469. bool (CXXRecordDecl::*hasTrivial)() const;
  8470. switch (member) {
  8471. case CXXDefaultConstructor:
  8472. hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
  8473. case CXXCopyConstructor:
  8474. hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
  8475. case CXXCopyAssignment:
  8476. hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
  8477. case CXXDestructor:
  8478. hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
  8479. default:
  8480. llvm_unreachable("unexpected special member");
  8481. }
  8482. // Check for nontrivial bases (and recurse).
  8483. for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
  8484. const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
  8485. assert(BaseRT && "Don't know how to handle dependent bases");
  8486. CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
  8487. if (!(BaseRecTy->*hasTrivial)()) {
  8488. SourceLocation BaseLoc = bi->getLocStart();
  8489. Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
  8490. DiagnoseNontrivial(BaseRT, member);
  8491. return;
  8492. }
  8493. }
  8494. // Check for nontrivial members (and recurse).
  8495. typedef RecordDecl::field_iterator field_iter;
  8496. for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
  8497. ++fi) {
  8498. QualType EltTy = Context.getBaseElementType(fi->getType());
  8499. if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
  8500. CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
  8501. if (!(EltRD->*hasTrivial)()) {
  8502. SourceLocation FLoc = fi->getLocation();
  8503. Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
  8504. DiagnoseNontrivial(EltRT, member);
  8505. return;
  8506. }
  8507. }
  8508. if (EltTy->isObjCLifetimeType()) {
  8509. switch (EltTy.getObjCLifetime()) {
  8510. case Qualifiers::OCL_None:
  8511. case Qualifiers::OCL_ExplicitNone:
  8512. break;
  8513. case Qualifiers::OCL_Autoreleasing:
  8514. case Qualifiers::OCL_Weak:
  8515. case Qualifiers::OCL_Strong:
  8516. Diag(fi->getLocation(), diag::note_nontrivial_objc_ownership)
  8517. << QT << EltTy.getObjCLifetime();
  8518. return;
  8519. }
  8520. }
  8521. }
  8522. llvm_unreachable("found no explanation for non-trivial member");
  8523. }
  8524. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  8525. /// AST enum value.
  8526. static ObjCIvarDecl::AccessControl
  8527. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  8528. switch (ivarVisibility) {
  8529. default: llvm_unreachable("Unknown visitibility kind");
  8530. case tok::objc_private: return ObjCIvarDecl::Private;
  8531. case tok::objc_public: return ObjCIvarDecl::Public;
  8532. case tok::objc_protected: return ObjCIvarDecl::Protected;
  8533. case tok::objc_package: return ObjCIvarDecl::Package;
  8534. }
  8535. }
  8536. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  8537. /// in order to create an IvarDecl object for it.
  8538. Decl *Sema::ActOnIvar(Scope *S,
  8539. SourceLocation DeclStart,
  8540. Declarator &D, Expr *BitfieldWidth,
  8541. tok::ObjCKeywordKind Visibility) {
  8542. IdentifierInfo *II = D.getIdentifier();
  8543. Expr *BitWidth = (Expr*)BitfieldWidth;
  8544. SourceLocation Loc = DeclStart;
  8545. if (II) Loc = D.getIdentifierLoc();
  8546. // FIXME: Unnamed fields can be handled in various different ways, for
  8547. // example, unnamed unions inject all members into the struct namespace!
  8548. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  8549. QualType T = TInfo->getType();
  8550. if (BitWidth) {
  8551. // 6.7.2.1p3, 6.7.2.1p4
  8552. BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
  8553. if (!BitWidth)
  8554. D.setInvalidType();
  8555. } else {
  8556. // Not a bitfield.
  8557. // validate II.
  8558. }
  8559. if (T->isReferenceType()) {
  8560. Diag(Loc, diag::err_ivar_reference_type);
  8561. D.setInvalidType();
  8562. }
  8563. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  8564. // than a variably modified type.
  8565. else if (T->isVariablyModifiedType()) {
  8566. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  8567. D.setInvalidType();
  8568. }
  8569. // Get the visibility (access control) for this ivar.
  8570. ObjCIvarDecl::AccessControl ac =
  8571. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  8572. : ObjCIvarDecl::None;
  8573. // Must set ivar's DeclContext to its enclosing interface.
  8574. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  8575. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  8576. return 0;
  8577. ObjCContainerDecl *EnclosingContext;
  8578. if (ObjCImplementationDecl *IMPDecl =
  8579. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  8580. if (LangOpts.ObjCRuntime.isFragile()) {
  8581. // Case of ivar declared in an implementation. Context is that of its class.
  8582. EnclosingContext = IMPDecl->getClassInterface();
  8583. assert(EnclosingContext && "Implementation has no class interface!");
  8584. }
  8585. else
  8586. EnclosingContext = EnclosingDecl;
  8587. } else {
  8588. if (ObjCCategoryDecl *CDecl =
  8589. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  8590. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  8591. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  8592. return 0;
  8593. }
  8594. }
  8595. EnclosingContext = EnclosingDecl;
  8596. }
  8597. // Construct the decl.
  8598. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  8599. DeclStart, Loc, II, T,
  8600. TInfo, ac, (Expr *)BitfieldWidth);
  8601. if (II) {
  8602. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  8603. ForRedeclaration);
  8604. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  8605. && !isa<TagDecl>(PrevDecl)) {
  8606. Diag(Loc, diag::err_duplicate_member) << II;
  8607. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  8608. NewID->setInvalidDecl();
  8609. }
  8610. }
  8611. // Process attributes attached to the ivar.
  8612. ProcessDeclAttributes(S, NewID, D);
  8613. if (D.isInvalidType())
  8614. NewID->setInvalidDecl();
  8615. // In ARC, infer 'retaining' for ivars of retainable type.
  8616. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  8617. NewID->setInvalidDecl();
  8618. if (D.getDeclSpec().isModulePrivateSpecified())
  8619. NewID->setModulePrivate();
  8620. if (II) {
  8621. // FIXME: When interfaces are DeclContexts, we'll need to add
  8622. // these to the interface.
  8623. S->AddDecl(NewID);
  8624. IdResolver.AddDecl(NewID);
  8625. }
  8626. if (LangOpts.ObjCRuntime.isNonFragile() &&
  8627. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  8628. Diag(Loc, diag::warn_ivars_in_interface);
  8629. return NewID;
  8630. }
  8631. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  8632. /// class and class extensions. For every class @interface and class
  8633. /// extension @interface, if the last ivar is a bitfield of any type,
  8634. /// then add an implicit `char :0` ivar to the end of that interface.
  8635. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  8636. SmallVectorImpl<Decl *> &AllIvarDecls) {
  8637. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  8638. return;
  8639. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  8640. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  8641. if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
  8642. return;
  8643. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  8644. if (!ID) {
  8645. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  8646. if (!CD->IsClassExtension())
  8647. return;
  8648. }
  8649. // No need to add this to end of @implementation.
  8650. else
  8651. return;
  8652. }
  8653. // All conditions are met. Add a new bitfield to the tail end of ivars.
  8654. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  8655. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  8656. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  8657. DeclLoc, DeclLoc, 0,
  8658. Context.CharTy,
  8659. Context.getTrivialTypeSourceInfo(Context.CharTy,
  8660. DeclLoc),
  8661. ObjCIvarDecl::Private, BW,
  8662. true);
  8663. AllIvarDecls.push_back(Ivar);
  8664. }
  8665. void Sema::ActOnFields(Scope* S,
  8666. SourceLocation RecLoc, Decl *EnclosingDecl,
  8667. llvm::ArrayRef<Decl *> Fields,
  8668. SourceLocation LBrac, SourceLocation RBrac,
  8669. AttributeList *Attr) {
  8670. assert(EnclosingDecl && "missing record or interface decl");
  8671. // If this is an Objective-C @implementation or category and we have
  8672. // new fields here we should reset the layout of the interface since
  8673. // it will now change.
  8674. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  8675. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  8676. switch (DC->getKind()) {
  8677. default: break;
  8678. case Decl::ObjCCategory:
  8679. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  8680. break;
  8681. case Decl::ObjCImplementation:
  8682. Context.
  8683. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  8684. break;
  8685. }
  8686. }
  8687. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  8688. // Start counting up the number of named members; make sure to include
  8689. // members of anonymous structs and unions in the total.
  8690. unsigned NumNamedMembers = 0;
  8691. if (Record) {
  8692. for (RecordDecl::decl_iterator i = Record->decls_begin(),
  8693. e = Record->decls_end(); i != e; i++) {
  8694. if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
  8695. if (IFD->getDeclName())
  8696. ++NumNamedMembers;
  8697. }
  8698. }
  8699. // Verify that all the fields are okay.
  8700. SmallVector<FieldDecl*, 32> RecFields;
  8701. bool ARCErrReported = false;
  8702. for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  8703. i != end; ++i) {
  8704. FieldDecl *FD = cast<FieldDecl>(*i);
  8705. // Get the type for the field.
  8706. const Type *FDTy = FD->getType().getTypePtr();
  8707. if (!FD->isAnonymousStructOrUnion()) {
  8708. // Remember all fields written by the user.
  8709. RecFields.push_back(FD);
  8710. }
  8711. // If the field is already invalid for some reason, don't emit more
  8712. // diagnostics about it.
  8713. if (FD->isInvalidDecl()) {
  8714. EnclosingDecl->setInvalidDecl();
  8715. continue;
  8716. }
  8717. // C99 6.7.2.1p2:
  8718. // A structure or union shall not contain a member with
  8719. // incomplete or function type (hence, a structure shall not
  8720. // contain an instance of itself, but may contain a pointer to
  8721. // an instance of itself), except that the last member of a
  8722. // structure with more than one named member may have incomplete
  8723. // array type; such a structure (and any union containing,
  8724. // possibly recursively, a member that is such a structure)
  8725. // shall not be a member of a structure or an element of an
  8726. // array.
  8727. if (FDTy->isFunctionType()) {
  8728. // Field declared as a function.
  8729. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  8730. << FD->getDeclName();
  8731. FD->setInvalidDecl();
  8732. EnclosingDecl->setInvalidDecl();
  8733. continue;
  8734. } else if (FDTy->isIncompleteArrayType() && Record &&
  8735. ((i + 1 == Fields.end() && !Record->isUnion()) ||
  8736. ((getLangOpts().MicrosoftExt ||
  8737. getLangOpts().CPlusPlus) &&
  8738. (i + 1 == Fields.end() || Record->isUnion())))) {
  8739. // Flexible array member.
  8740. // Microsoft and g++ is more permissive regarding flexible array.
  8741. // It will accept flexible array in union and also
  8742. // as the sole element of a struct/class.
  8743. if (getLangOpts().MicrosoftExt) {
  8744. if (Record->isUnion())
  8745. Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
  8746. << FD->getDeclName();
  8747. else if (Fields.size() == 1)
  8748. Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
  8749. << FD->getDeclName() << Record->getTagKind();
  8750. } else if (getLangOpts().CPlusPlus) {
  8751. if (Record->isUnion())
  8752. Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
  8753. << FD->getDeclName();
  8754. else if (Fields.size() == 1)
  8755. Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
  8756. << FD->getDeclName() << Record->getTagKind();
  8757. } else if (!getLangOpts().C99) {
  8758. if (Record->isUnion())
  8759. Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
  8760. << FD->getDeclName();
  8761. else
  8762. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  8763. << FD->getDeclName() << Record->getTagKind();
  8764. } else if (NumNamedMembers < 1) {
  8765. Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
  8766. << FD->getDeclName();
  8767. FD->setInvalidDecl();
  8768. EnclosingDecl->setInvalidDecl();
  8769. continue;
  8770. }
  8771. if (!FD->getType()->isDependentType() &&
  8772. !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
  8773. Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
  8774. << FD->getDeclName() << FD->getType();
  8775. FD->setInvalidDecl();
  8776. EnclosingDecl->setInvalidDecl();
  8777. continue;
  8778. }
  8779. // Okay, we have a legal flexible array member at the end of the struct.
  8780. if (Record)
  8781. Record->setHasFlexibleArrayMember(true);
  8782. } else if (!FDTy->isDependentType() &&
  8783. RequireCompleteType(FD->getLocation(), FD->getType(),
  8784. diag::err_field_incomplete)) {
  8785. // Incomplete type
  8786. FD->setInvalidDecl();
  8787. EnclosingDecl->setInvalidDecl();
  8788. continue;
  8789. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  8790. if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
  8791. // If this is a member of a union, then entire union becomes "flexible".
  8792. if (Record && Record->isUnion()) {
  8793. Record->setHasFlexibleArrayMember(true);
  8794. } else {
  8795. // If this is a struct/class and this is not the last element, reject
  8796. // it. Note that GCC supports variable sized arrays in the middle of
  8797. // structures.
  8798. if (i + 1 != Fields.end())
  8799. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  8800. << FD->getDeclName() << FD->getType();
  8801. else {
  8802. // We support flexible arrays at the end of structs in
  8803. // other structs as an extension.
  8804. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  8805. << FD->getDeclName();
  8806. if (Record)
  8807. Record->setHasFlexibleArrayMember(true);
  8808. }
  8809. }
  8810. }
  8811. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  8812. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  8813. diag::err_abstract_type_in_decl,
  8814. AbstractIvarType)) {
  8815. // Ivars can not have abstract class types
  8816. FD->setInvalidDecl();
  8817. }
  8818. if (Record && FDTTy->getDecl()->hasObjectMember())
  8819. Record->setHasObjectMember(true);
  8820. } else if (FDTy->isObjCObjectType()) {
  8821. /// A field cannot be an Objective-c object
  8822. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  8823. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  8824. QualType T = Context.getObjCObjectPointerType(FD->getType());
  8825. FD->setType(T);
  8826. } else if (!getLangOpts().CPlusPlus) {
  8827. if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
  8828. // It's an error in ARC if a field has lifetime.
  8829. // We don't want to report this in a system header, though,
  8830. // so we just make the field unavailable.
  8831. // FIXME: that's really not sufficient; we need to make the type
  8832. // itself invalid to, say, initialize or copy.
  8833. QualType T = FD->getType();
  8834. Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
  8835. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
  8836. SourceLocation loc = FD->getLocation();
  8837. if (getSourceManager().isInSystemHeader(loc)) {
  8838. if (!FD->hasAttr<UnavailableAttr>()) {
  8839. FD->addAttr(new (Context) UnavailableAttr(loc, Context,
  8840. "this system field has retaining ownership"));
  8841. }
  8842. } else {
  8843. Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
  8844. << T->isBlockPointerType();
  8845. }
  8846. ARCErrReported = true;
  8847. }
  8848. }
  8849. else if (getLangOpts().ObjC1 &&
  8850. getLangOpts().getGC() != LangOptions::NonGC &&
  8851. Record && !Record->hasObjectMember()) {
  8852. if (FD->getType()->isObjCObjectPointerType() ||
  8853. FD->getType().isObjCGCStrong())
  8854. Record->setHasObjectMember(true);
  8855. else if (Context.getAsArrayType(FD->getType())) {
  8856. QualType BaseType = Context.getBaseElementType(FD->getType());
  8857. if (BaseType->isRecordType() &&
  8858. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  8859. Record->setHasObjectMember(true);
  8860. else if (BaseType->isObjCObjectPointerType() ||
  8861. BaseType.isObjCGCStrong())
  8862. Record->setHasObjectMember(true);
  8863. }
  8864. }
  8865. }
  8866. // Keep track of the number of named members.
  8867. if (FD->getIdentifier())
  8868. ++NumNamedMembers;
  8869. }
  8870. // Okay, we successfully defined 'Record'.
  8871. if (Record) {
  8872. bool Completed = false;
  8873. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  8874. if (!CXXRecord->isInvalidDecl()) {
  8875. // Set access bits correctly on the directly-declared conversions.
  8876. UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
  8877. for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
  8878. I != E; ++I)
  8879. Convs->setAccess(I, (*I)->getAccess());
  8880. if (!CXXRecord->isDependentType()) {
  8881. // Adjust user-defined destructor exception spec.
  8882. if (getLangOpts().CPlusPlus0x &&
  8883. CXXRecord->hasUserDeclaredDestructor())
  8884. AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
  8885. // Add any implicitly-declared members to this class.
  8886. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  8887. // If we have virtual base classes, we may end up finding multiple
  8888. // final overriders for a given virtual function. Check for this
  8889. // problem now.
  8890. if (CXXRecord->getNumVBases()) {
  8891. CXXFinalOverriderMap FinalOverriders;
  8892. CXXRecord->getFinalOverriders(FinalOverriders);
  8893. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  8894. MEnd = FinalOverriders.end();
  8895. M != MEnd; ++M) {
  8896. for (OverridingMethods::iterator SO = M->second.begin(),
  8897. SOEnd = M->second.end();
  8898. SO != SOEnd; ++SO) {
  8899. assert(SO->second.size() > 0 &&
  8900. "Virtual function without overridding functions?");
  8901. if (SO->second.size() == 1)
  8902. continue;
  8903. // C++ [class.virtual]p2:
  8904. // In a derived class, if a virtual member function of a base
  8905. // class subobject has more than one final overrider the
  8906. // program is ill-formed.
  8907. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  8908. << (const NamedDecl *)M->first << Record;
  8909. Diag(M->first->getLocation(),
  8910. diag::note_overridden_virtual_function);
  8911. for (OverridingMethods::overriding_iterator
  8912. OM = SO->second.begin(),
  8913. OMEnd = SO->second.end();
  8914. OM != OMEnd; ++OM)
  8915. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  8916. << (const NamedDecl *)M->first << OM->Method->getParent();
  8917. Record->setInvalidDecl();
  8918. }
  8919. }
  8920. CXXRecord->completeDefinition(&FinalOverriders);
  8921. Completed = true;
  8922. }
  8923. }
  8924. }
  8925. }
  8926. if (!Completed)
  8927. Record->completeDefinition();
  8928. } else {
  8929. ObjCIvarDecl **ClsFields =
  8930. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  8931. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  8932. ID->setEndOfDefinitionLoc(RBrac);
  8933. // Add ivar's to class's DeclContext.
  8934. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  8935. ClsFields[i]->setLexicalDeclContext(ID);
  8936. ID->addDecl(ClsFields[i]);
  8937. }
  8938. // Must enforce the rule that ivars in the base classes may not be
  8939. // duplicates.
  8940. if (ID->getSuperClass())
  8941. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  8942. } else if (ObjCImplementationDecl *IMPDecl =
  8943. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  8944. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  8945. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  8946. // Ivar declared in @implementation never belongs to the implementation.
  8947. // Only it is in implementation's lexical context.
  8948. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  8949. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  8950. IMPDecl->setIvarLBraceLoc(LBrac);
  8951. IMPDecl->setIvarRBraceLoc(RBrac);
  8952. } else if (ObjCCategoryDecl *CDecl =
  8953. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  8954. // case of ivars in class extension; all other cases have been
  8955. // reported as errors elsewhere.
  8956. // FIXME. Class extension does not have a LocEnd field.
  8957. // CDecl->setLocEnd(RBrac);
  8958. // Add ivar's to class extension's DeclContext.
  8959. // Diagnose redeclaration of private ivars.
  8960. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  8961. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  8962. if (IDecl) {
  8963. if (const ObjCIvarDecl *ClsIvar =
  8964. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  8965. Diag(ClsFields[i]->getLocation(),
  8966. diag::err_duplicate_ivar_declaration);
  8967. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  8968. continue;
  8969. }
  8970. for (const ObjCCategoryDecl *ClsExtDecl =
  8971. IDecl->getFirstClassExtension();
  8972. ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
  8973. if (const ObjCIvarDecl *ClsExtIvar =
  8974. ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  8975. Diag(ClsFields[i]->getLocation(),
  8976. diag::err_duplicate_ivar_declaration);
  8977. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  8978. continue;
  8979. }
  8980. }
  8981. }
  8982. ClsFields[i]->setLexicalDeclContext(CDecl);
  8983. CDecl->addDecl(ClsFields[i]);
  8984. }
  8985. CDecl->setIvarLBraceLoc(LBrac);
  8986. CDecl->setIvarRBraceLoc(RBrac);
  8987. }
  8988. }
  8989. if (Attr)
  8990. ProcessDeclAttributeList(S, Record, Attr);
  8991. }
  8992. /// \brief Determine whether the given integral value is representable within
  8993. /// the given type T.
  8994. static bool isRepresentableIntegerValue(ASTContext &Context,
  8995. llvm::APSInt &Value,
  8996. QualType T) {
  8997. assert(T->isIntegralType(Context) && "Integral type required!");
  8998. unsigned BitWidth = Context.getIntWidth(T);
  8999. if (Value.isUnsigned() || Value.isNonNegative()) {
  9000. if (T->isSignedIntegerOrEnumerationType())
  9001. --BitWidth;
  9002. return Value.getActiveBits() <= BitWidth;
  9003. }
  9004. return Value.getMinSignedBits() <= BitWidth;
  9005. }
  9006. // \brief Given an integral type, return the next larger integral type
  9007. // (or a NULL type of no such type exists).
  9008. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  9009. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  9010. // enum checking below.
  9011. assert(T->isIntegralType(Context) && "Integral type required!");
  9012. const unsigned NumTypes = 4;
  9013. QualType SignedIntegralTypes[NumTypes] = {
  9014. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  9015. };
  9016. QualType UnsignedIntegralTypes[NumTypes] = {
  9017. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  9018. Context.UnsignedLongLongTy
  9019. };
  9020. unsigned BitWidth = Context.getTypeSize(T);
  9021. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  9022. : UnsignedIntegralTypes;
  9023. for (unsigned I = 0; I != NumTypes; ++I)
  9024. if (Context.getTypeSize(Types[I]) > BitWidth)
  9025. return Types[I];
  9026. return QualType();
  9027. }
  9028. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  9029. EnumConstantDecl *LastEnumConst,
  9030. SourceLocation IdLoc,
  9031. IdentifierInfo *Id,
  9032. Expr *Val) {
  9033. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  9034. llvm::APSInt EnumVal(IntWidth);
  9035. QualType EltTy;
  9036. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  9037. Val = 0;
  9038. if (Val)
  9039. Val = DefaultLvalueConversion(Val).take();
  9040. if (Val) {
  9041. if (Enum->isDependentType() || Val->isTypeDependent())
  9042. EltTy = Context.DependentTy;
  9043. else {
  9044. SourceLocation ExpLoc;
  9045. if (getLangOpts().CPlusPlus0x && Enum->isFixed() &&
  9046. !getLangOpts().MicrosoftMode) {
  9047. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  9048. // constant-expression in the enumerator-definition shall be a converted
  9049. // constant expression of the underlying type.
  9050. EltTy = Enum->getIntegerType();
  9051. ExprResult Converted =
  9052. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  9053. CCEK_Enumerator);
  9054. if (Converted.isInvalid())
  9055. Val = 0;
  9056. else
  9057. Val = Converted.take();
  9058. } else if (!Val->isValueDependent() &&
  9059. !(Val = VerifyIntegerConstantExpression(Val,
  9060. &EnumVal).take())) {
  9061. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  9062. } else {
  9063. if (Enum->isFixed()) {
  9064. EltTy = Enum->getIntegerType();
  9065. // In Obj-C and Microsoft mode, require the enumeration value to be
  9066. // representable in the underlying type of the enumeration. In C++11,
  9067. // we perform a non-narrowing conversion as part of converted constant
  9068. // expression checking.
  9069. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  9070. if (getLangOpts().MicrosoftMode) {
  9071. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  9072. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
  9073. } else
  9074. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  9075. } else
  9076. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
  9077. } else if (getLangOpts().CPlusPlus) {
  9078. // C++11 [dcl.enum]p5:
  9079. // If the underlying type is not fixed, the type of each enumerator
  9080. // is the type of its initializing value:
  9081. // - If an initializer is specified for an enumerator, the
  9082. // initializing value has the same type as the expression.
  9083. EltTy = Val->getType();
  9084. } else {
  9085. // C99 6.7.2.2p2:
  9086. // The expression that defines the value of an enumeration constant
  9087. // shall be an integer constant expression that has a value
  9088. // representable as an int.
  9089. // Complain if the value is not representable in an int.
  9090. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  9091. Diag(IdLoc, diag::ext_enum_value_not_int)
  9092. << EnumVal.toString(10) << Val->getSourceRange()
  9093. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  9094. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  9095. // Force the type of the expression to 'int'.
  9096. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
  9097. }
  9098. EltTy = Val->getType();
  9099. }
  9100. }
  9101. }
  9102. }
  9103. if (!Val) {
  9104. if (Enum->isDependentType())
  9105. EltTy = Context.DependentTy;
  9106. else if (!LastEnumConst) {
  9107. // C++0x [dcl.enum]p5:
  9108. // If the underlying type is not fixed, the type of each enumerator
  9109. // is the type of its initializing value:
  9110. // - If no initializer is specified for the first enumerator, the
  9111. // initializing value has an unspecified integral type.
  9112. //
  9113. // GCC uses 'int' for its unspecified integral type, as does
  9114. // C99 6.7.2.2p3.
  9115. if (Enum->isFixed()) {
  9116. EltTy = Enum->getIntegerType();
  9117. }
  9118. else {
  9119. EltTy = Context.IntTy;
  9120. }
  9121. } else {
  9122. // Assign the last value + 1.
  9123. EnumVal = LastEnumConst->getInitVal();
  9124. ++EnumVal;
  9125. EltTy = LastEnumConst->getType();
  9126. // Check for overflow on increment.
  9127. if (EnumVal < LastEnumConst->getInitVal()) {
  9128. // C++0x [dcl.enum]p5:
  9129. // If the underlying type is not fixed, the type of each enumerator
  9130. // is the type of its initializing value:
  9131. //
  9132. // - Otherwise the type of the initializing value is the same as
  9133. // the type of the initializing value of the preceding enumerator
  9134. // unless the incremented value is not representable in that type,
  9135. // in which case the type is an unspecified integral type
  9136. // sufficient to contain the incremented value. If no such type
  9137. // exists, the program is ill-formed.
  9138. QualType T = getNextLargerIntegralType(Context, EltTy);
  9139. if (T.isNull() || Enum->isFixed()) {
  9140. // There is no integral type larger enough to represent this
  9141. // value. Complain, then allow the value to wrap around.
  9142. EnumVal = LastEnumConst->getInitVal();
  9143. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  9144. ++EnumVal;
  9145. if (Enum->isFixed())
  9146. // When the underlying type is fixed, this is ill-formed.
  9147. Diag(IdLoc, diag::err_enumerator_wrapped)
  9148. << EnumVal.toString(10)
  9149. << EltTy;
  9150. else
  9151. Diag(IdLoc, diag::warn_enumerator_too_large)
  9152. << EnumVal.toString(10);
  9153. } else {
  9154. EltTy = T;
  9155. }
  9156. // Retrieve the last enumerator's value, extent that type to the
  9157. // type that is supposed to be large enough to represent the incremented
  9158. // value, then increment.
  9159. EnumVal = LastEnumConst->getInitVal();
  9160. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  9161. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  9162. ++EnumVal;
  9163. // If we're not in C++, diagnose the overflow of enumerator values,
  9164. // which in C99 means that the enumerator value is not representable in
  9165. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  9166. // permits enumerator values that are representable in some larger
  9167. // integral type.
  9168. if (!getLangOpts().CPlusPlus && !T.isNull())
  9169. Diag(IdLoc, diag::warn_enum_value_overflow);
  9170. } else if (!getLangOpts().CPlusPlus &&
  9171. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  9172. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  9173. Diag(IdLoc, diag::ext_enum_value_not_int)
  9174. << EnumVal.toString(10) << 1;
  9175. }
  9176. }
  9177. }
  9178. if (!EltTy->isDependentType()) {
  9179. // Make the enumerator value match the signedness and size of the
  9180. // enumerator's type.
  9181. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  9182. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  9183. }
  9184. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  9185. Val, EnumVal);
  9186. }
  9187. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  9188. SourceLocation IdLoc, IdentifierInfo *Id,
  9189. AttributeList *Attr,
  9190. SourceLocation EqualLoc, Expr *Val) {
  9191. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  9192. EnumConstantDecl *LastEnumConst =
  9193. cast_or_null<EnumConstantDecl>(lastEnumConst);
  9194. // The scope passed in may not be a decl scope. Zip up the scope tree until
  9195. // we find one that is.
  9196. S = getNonFieldDeclScope(S);
  9197. // Verify that there isn't already something declared with this name in this
  9198. // scope.
  9199. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  9200. ForRedeclaration);
  9201. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  9202. // Maybe we will complain about the shadowed template parameter.
  9203. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  9204. // Just pretend that we didn't see the previous declaration.
  9205. PrevDecl = 0;
  9206. }
  9207. if (PrevDecl) {
  9208. // When in C++, we may get a TagDecl with the same name; in this case the
  9209. // enum constant will 'hide' the tag.
  9210. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  9211. "Received TagDecl when not in C++!");
  9212. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  9213. if (isa<EnumConstantDecl>(PrevDecl))
  9214. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  9215. else
  9216. Diag(IdLoc, diag::err_redefinition) << Id;
  9217. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  9218. return 0;
  9219. }
  9220. }
  9221. // C++ [class.mem]p15:
  9222. // If T is the name of a class, then each of the following shall have a name
  9223. // different from T:
  9224. // - every enumerator of every member of class T that is an unscoped
  9225. // enumerated type
  9226. if (CXXRecordDecl *Record
  9227. = dyn_cast<CXXRecordDecl>(
  9228. TheEnumDecl->getDeclContext()->getRedeclContext()))
  9229. if (!TheEnumDecl->isScoped() &&
  9230. Record->getIdentifier() && Record->getIdentifier() == Id)
  9231. Diag(IdLoc, diag::err_member_name_of_class) << Id;
  9232. EnumConstantDecl *New =
  9233. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  9234. if (New) {
  9235. // Process attributes.
  9236. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  9237. // Register this decl in the current scope stack.
  9238. New->setAccess(TheEnumDecl->getAccess());
  9239. PushOnScopeChains(New, S);
  9240. }
  9241. ActOnDocumentableDecl(New);
  9242. return New;
  9243. }
  9244. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
  9245. SourceLocation RBraceLoc, Decl *EnumDeclX,
  9246. Decl **Elements, unsigned NumElements,
  9247. Scope *S, AttributeList *Attr) {
  9248. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  9249. QualType EnumType = Context.getTypeDeclType(Enum);
  9250. if (Attr)
  9251. ProcessDeclAttributeList(S, Enum, Attr);
  9252. if (Enum->isDependentType()) {
  9253. for (unsigned i = 0; i != NumElements; ++i) {
  9254. EnumConstantDecl *ECD =
  9255. cast_or_null<EnumConstantDecl>(Elements[i]);
  9256. if (!ECD) continue;
  9257. ECD->setType(EnumType);
  9258. }
  9259. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  9260. return;
  9261. }
  9262. // TODO: If the result value doesn't fit in an int, it must be a long or long
  9263. // long value. ISO C does not support this, but GCC does as an extension,
  9264. // emit a warning.
  9265. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  9266. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  9267. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  9268. // Verify that all the values are okay, compute the size of the values, and
  9269. // reverse the list.
  9270. unsigned NumNegativeBits = 0;
  9271. unsigned NumPositiveBits = 0;
  9272. // Keep track of whether all elements have type int.
  9273. bool AllElementsInt = true;
  9274. for (unsigned i = 0; i != NumElements; ++i) {
  9275. EnumConstantDecl *ECD =
  9276. cast_or_null<EnumConstantDecl>(Elements[i]);
  9277. if (!ECD) continue; // Already issued a diagnostic.
  9278. const llvm::APSInt &InitVal = ECD->getInitVal();
  9279. // Keep track of the size of positive and negative values.
  9280. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  9281. NumPositiveBits = std::max(NumPositiveBits,
  9282. (unsigned)InitVal.getActiveBits());
  9283. else
  9284. NumNegativeBits = std::max(NumNegativeBits,
  9285. (unsigned)InitVal.getMinSignedBits());
  9286. // Keep track of whether every enum element has type int (very commmon).
  9287. if (AllElementsInt)
  9288. AllElementsInt = ECD->getType() == Context.IntTy;
  9289. }
  9290. // Figure out the type that should be used for this enum.
  9291. QualType BestType;
  9292. unsigned BestWidth;
  9293. // C++0x N3000 [conv.prom]p3:
  9294. // An rvalue of an unscoped enumeration type whose underlying
  9295. // type is not fixed can be converted to an rvalue of the first
  9296. // of the following types that can represent all the values of
  9297. // the enumeration: int, unsigned int, long int, unsigned long
  9298. // int, long long int, or unsigned long long int.
  9299. // C99 6.4.4.3p2:
  9300. // An identifier declared as an enumeration constant has type int.
  9301. // The C99 rule is modified by a gcc extension
  9302. QualType BestPromotionType;
  9303. bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
  9304. // -fshort-enums is the equivalent to specifying the packed attribute on all
  9305. // enum definitions.
  9306. if (LangOpts.ShortEnums)
  9307. Packed = true;
  9308. if (Enum->isFixed()) {
  9309. BestType = Enum->getIntegerType();
  9310. if (BestType->isPromotableIntegerType())
  9311. BestPromotionType = Context.getPromotedIntegerType(BestType);
  9312. else
  9313. BestPromotionType = BestType;
  9314. // We don't need to set BestWidth, because BestType is going to be the type
  9315. // of the enumerators, but we do anyway because otherwise some compilers
  9316. // warn that it might be used uninitialized.
  9317. BestWidth = CharWidth;
  9318. }
  9319. else if (NumNegativeBits) {
  9320. // If there is a negative value, figure out the smallest integer type (of
  9321. // int/long/longlong) that fits.
  9322. // If it's packed, check also if it fits a char or a short.
  9323. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  9324. BestType = Context.SignedCharTy;
  9325. BestWidth = CharWidth;
  9326. } else if (Packed && NumNegativeBits <= ShortWidth &&
  9327. NumPositiveBits < ShortWidth) {
  9328. BestType = Context.ShortTy;
  9329. BestWidth = ShortWidth;
  9330. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  9331. BestType = Context.IntTy;
  9332. BestWidth = IntWidth;
  9333. } else {
  9334. BestWidth = Context.getTargetInfo().getLongWidth();
  9335. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  9336. BestType = Context.LongTy;
  9337. } else {
  9338. BestWidth = Context.getTargetInfo().getLongLongWidth();
  9339. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  9340. Diag(Enum->getLocation(), diag::warn_enum_too_large);
  9341. BestType = Context.LongLongTy;
  9342. }
  9343. }
  9344. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  9345. } else {
  9346. // If there is no negative value, figure out the smallest type that fits
  9347. // all of the enumerator values.
  9348. // If it's packed, check also if it fits a char or a short.
  9349. if (Packed && NumPositiveBits <= CharWidth) {
  9350. BestType = Context.UnsignedCharTy;
  9351. BestPromotionType = Context.IntTy;
  9352. BestWidth = CharWidth;
  9353. } else if (Packed && NumPositiveBits <= ShortWidth) {
  9354. BestType = Context.UnsignedShortTy;
  9355. BestPromotionType = Context.IntTy;
  9356. BestWidth = ShortWidth;
  9357. } else if (NumPositiveBits <= IntWidth) {
  9358. BestType = Context.UnsignedIntTy;
  9359. BestWidth = IntWidth;
  9360. BestPromotionType
  9361. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  9362. ? Context.UnsignedIntTy : Context.IntTy;
  9363. } else if (NumPositiveBits <=
  9364. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  9365. BestType = Context.UnsignedLongTy;
  9366. BestPromotionType
  9367. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  9368. ? Context.UnsignedLongTy : Context.LongTy;
  9369. } else {
  9370. BestWidth = Context.getTargetInfo().getLongLongWidth();
  9371. assert(NumPositiveBits <= BestWidth &&
  9372. "How could an initializer get larger than ULL?");
  9373. BestType = Context.UnsignedLongLongTy;
  9374. BestPromotionType
  9375. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  9376. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  9377. }
  9378. }
  9379. // Loop over all of the enumerator constants, changing their types to match
  9380. // the type of the enum if needed.
  9381. for (unsigned i = 0; i != NumElements; ++i) {
  9382. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  9383. if (!ECD) continue; // Already issued a diagnostic.
  9384. // Standard C says the enumerators have int type, but we allow, as an
  9385. // extension, the enumerators to be larger than int size. If each
  9386. // enumerator value fits in an int, type it as an int, otherwise type it the
  9387. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  9388. // that X has type 'int', not 'unsigned'.
  9389. // Determine whether the value fits into an int.
  9390. llvm::APSInt InitVal = ECD->getInitVal();
  9391. // If it fits into an integer type, force it. Otherwise force it to match
  9392. // the enum decl type.
  9393. QualType NewTy;
  9394. unsigned NewWidth;
  9395. bool NewSign;
  9396. if (!getLangOpts().CPlusPlus &&
  9397. !Enum->isFixed() &&
  9398. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  9399. NewTy = Context.IntTy;
  9400. NewWidth = IntWidth;
  9401. NewSign = true;
  9402. } else if (ECD->getType() == BestType) {
  9403. // Already the right type!
  9404. if (getLangOpts().CPlusPlus)
  9405. // C++ [dcl.enum]p4: Following the closing brace of an
  9406. // enum-specifier, each enumerator has the type of its
  9407. // enumeration.
  9408. ECD->setType(EnumType);
  9409. continue;
  9410. } else {
  9411. NewTy = BestType;
  9412. NewWidth = BestWidth;
  9413. NewSign = BestType->isSignedIntegerOrEnumerationType();
  9414. }
  9415. // Adjust the APSInt value.
  9416. InitVal = InitVal.extOrTrunc(NewWidth);
  9417. InitVal.setIsSigned(NewSign);
  9418. ECD->setInitVal(InitVal);
  9419. // Adjust the Expr initializer and type.
  9420. if (ECD->getInitExpr() &&
  9421. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  9422. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  9423. CK_IntegralCast,
  9424. ECD->getInitExpr(),
  9425. /*base paths*/ 0,
  9426. VK_RValue));
  9427. if (getLangOpts().CPlusPlus)
  9428. // C++ [dcl.enum]p4: Following the closing brace of an
  9429. // enum-specifier, each enumerator has the type of its
  9430. // enumeration.
  9431. ECD->setType(EnumType);
  9432. else
  9433. ECD->setType(NewTy);
  9434. }
  9435. Enum->completeDefinition(BestType, BestPromotionType,
  9436. NumPositiveBits, NumNegativeBits);
  9437. // If we're declaring a function, ensure this decl isn't forgotten about -
  9438. // it needs to go into the function scope.
  9439. if (InFunctionDeclarator)
  9440. DeclsInPrototypeScope.push_back(Enum);
  9441. }
  9442. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  9443. SourceLocation StartLoc,
  9444. SourceLocation EndLoc) {
  9445. StringLiteral *AsmString = cast<StringLiteral>(expr);
  9446. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  9447. AsmString, StartLoc,
  9448. EndLoc);
  9449. CurContext->addDecl(New);
  9450. return New;
  9451. }
  9452. DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
  9453. SourceLocation ImportLoc,
  9454. ModuleIdPath Path) {
  9455. Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
  9456. Module::AllVisible,
  9457. /*IsIncludeDirective=*/false);
  9458. if (!Mod)
  9459. return true;
  9460. llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
  9461. Module *ModCheck = Mod;
  9462. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  9463. // If we've run out of module parents, just drop the remaining identifiers.
  9464. // We need the length to be consistent.
  9465. if (!ModCheck)
  9466. break;
  9467. ModCheck = ModCheck->Parent;
  9468. IdentifierLocs.push_back(Path[I].second);
  9469. }
  9470. ImportDecl *Import = ImportDecl::Create(Context,
  9471. Context.getTranslationUnitDecl(),
  9472. AtLoc.isValid()? AtLoc : ImportLoc,
  9473. Mod, IdentifierLocs);
  9474. Context.getTranslationUnitDecl()->addDecl(Import);
  9475. return Import;
  9476. }
  9477. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  9478. IdentifierInfo* AliasName,
  9479. SourceLocation PragmaLoc,
  9480. SourceLocation NameLoc,
  9481. SourceLocation AliasNameLoc) {
  9482. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  9483. LookupOrdinaryName);
  9484. AsmLabelAttr *Attr =
  9485. ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
  9486. if (PrevDecl)
  9487. PrevDecl->addAttr(Attr);
  9488. else
  9489. (void)ExtnameUndeclaredIdentifiers.insert(
  9490. std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
  9491. }
  9492. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  9493. SourceLocation PragmaLoc,
  9494. SourceLocation NameLoc) {
  9495. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  9496. if (PrevDecl) {
  9497. PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
  9498. } else {
  9499. (void)WeakUndeclaredIdentifiers.insert(
  9500. std::pair<IdentifierInfo*,WeakInfo>
  9501. (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
  9502. }
  9503. }
  9504. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  9505. IdentifierInfo* AliasName,
  9506. SourceLocation PragmaLoc,
  9507. SourceLocation NameLoc,
  9508. SourceLocation AliasNameLoc) {
  9509. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  9510. LookupOrdinaryName);
  9511. WeakInfo W = WeakInfo(Name, NameLoc);
  9512. if (PrevDecl) {
  9513. if (!PrevDecl->hasAttr<AliasAttr>())
  9514. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  9515. DeclApplyPragmaWeak(TUScope, ND, W);
  9516. } else {
  9517. (void)WeakUndeclaredIdentifiers.insert(
  9518. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  9519. }
  9520. }
  9521. Decl *Sema::getObjCDeclContext() const {
  9522. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  9523. }
  9524. AvailabilityResult Sema::getCurContextAvailability() const {
  9525. const Decl *D = cast<Decl>(getCurObjCLexicalContext());
  9526. return D->getAvailability();
  9527. }