SemaDecl.cpp 391 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106
  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/DeclCXX.h"
  24. #include "clang/AST/DeclObjC.h"
  25. #include "clang/AST/DeclTemplate.h"
  26. #include "clang/AST/EvaluatedExprVisitor.h"
  27. #include "clang/AST/ExprCXX.h"
  28. #include "clang/AST/StmtCXX.h"
  29. #include "clang/AST/CharUnits.h"
  30. #include "clang/Sema/DeclSpec.h"
  31. #include "clang/Sema/ParsedTemplate.h"
  32. #include "clang/Parse/ParseDiagnostic.h"
  33. #include "clang/Basic/PartialDiagnostic.h"
  34. #include "clang/Sema/DelayedDiagnostic.h"
  35. #include "clang/Basic/SourceManager.h"
  36. #include "clang/Basic/TargetInfo.h"
  37. // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
  38. #include "clang/Lex/Preprocessor.h"
  39. #include "clang/Lex/HeaderSearch.h"
  40. #include "clang/Lex/ModuleLoader.h"
  41. #include "llvm/ADT/SmallString.h"
  42. #include "llvm/ADT/Triple.h"
  43. #include <algorithm>
  44. #include <cstring>
  45. #include <functional>
  46. using namespace clang;
  47. using namespace sema;
  48. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  49. if (OwnedType) {
  50. Decl *Group[2] = { OwnedType, Ptr };
  51. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  52. }
  53. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  54. }
  55. namespace {
  56. class TypeNameValidatorCCC : public CorrectionCandidateCallback {
  57. public:
  58. TypeNameValidatorCCC(bool AllowInvalid) : AllowInvalidDecl(AllowInvalid) {
  59. WantExpressionKeywords = false;
  60. WantCXXNamedCasts = false;
  61. WantRemainingKeywords = false;
  62. }
  63. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  64. if (NamedDecl *ND = candidate.getCorrectionDecl())
  65. return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
  66. (AllowInvalidDecl || !ND->isInvalidDecl());
  67. else
  68. return candidate.isKeyword();
  69. }
  70. private:
  71. bool AllowInvalidDecl;
  72. };
  73. }
  74. /// \brief If the identifier refers to a type name within this scope,
  75. /// return the declaration of that type.
  76. ///
  77. /// This routine performs ordinary name lookup of the identifier II
  78. /// within the given scope, with optional C++ scope specifier SS, to
  79. /// determine whether the name refers to a type. If so, returns an
  80. /// opaque pointer (actually a QualType) corresponding to that
  81. /// type. Otherwise, returns NULL.
  82. ///
  83. /// If name lookup results in an ambiguity, this routine will complain
  84. /// and then return NULL.
  85. ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
  86. Scope *S, CXXScopeSpec *SS,
  87. bool isClassName, bool HasTrailingDot,
  88. ParsedType ObjectTypePtr,
  89. bool IsCtorOrDtorName,
  90. bool WantNontrivialTypeSourceInfo,
  91. IdentifierInfo **CorrectedII) {
  92. // Determine where we will perform name lookup.
  93. DeclContext *LookupCtx = 0;
  94. if (ObjectTypePtr) {
  95. QualType ObjectType = ObjectTypePtr.get();
  96. if (ObjectType->isRecordType())
  97. LookupCtx = computeDeclContext(ObjectType);
  98. } else if (SS && SS->isNotEmpty()) {
  99. LookupCtx = computeDeclContext(*SS, false);
  100. if (!LookupCtx) {
  101. if (isDependentScopeSpecifier(*SS)) {
  102. // C++ [temp.res]p3:
  103. // A qualified-id that refers to a type and in which the
  104. // nested-name-specifier depends on a template-parameter (14.6.2)
  105. // shall be prefixed by the keyword typename to indicate that the
  106. // qualified-id denotes a type, forming an
  107. // elaborated-type-specifier (7.1.5.3).
  108. //
  109. // We therefore do not perform any name lookup if the result would
  110. // refer to a member of an unknown specialization.
  111. if (!isClassName)
  112. return ParsedType();
  113. // We know from the grammar that this name refers to a type,
  114. // so build a dependent node to describe the type.
  115. if (WantNontrivialTypeSourceInfo)
  116. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  117. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  118. QualType T =
  119. CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  120. II, NameLoc);
  121. return ParsedType::make(T);
  122. }
  123. return ParsedType();
  124. }
  125. if (!LookupCtx->isDependentContext() &&
  126. RequireCompleteDeclContext(*SS, LookupCtx))
  127. return ParsedType();
  128. }
  129. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  130. // lookup for class-names.
  131. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  132. LookupOrdinaryName;
  133. LookupResult Result(*this, &II, NameLoc, Kind);
  134. if (LookupCtx) {
  135. // Perform "qualified" name lookup into the declaration context we
  136. // computed, which is either the type of the base of a member access
  137. // expression or the declaration context associated with a prior
  138. // nested-name-specifier.
  139. LookupQualifiedName(Result, LookupCtx);
  140. if (ObjectTypePtr && Result.empty()) {
  141. // C++ [basic.lookup.classref]p3:
  142. // If the unqualified-id is ~type-name, the type-name is looked up
  143. // in the context of the entire postfix-expression. If the type T of
  144. // the object expression is of a class type C, the type-name is also
  145. // looked up in the scope of class C. At least one of the lookups shall
  146. // find a name that refers to (possibly cv-qualified) T.
  147. LookupName(Result, S);
  148. }
  149. } else {
  150. // Perform unqualified name lookup.
  151. LookupName(Result, S);
  152. }
  153. NamedDecl *IIDecl = 0;
  154. switch (Result.getResultKind()) {
  155. case LookupResult::NotFound:
  156. case LookupResult::NotFoundInCurrentInstantiation:
  157. if (CorrectedII) {
  158. TypeNameValidatorCCC Validator(true);
  159. TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
  160. Kind, S, SS, Validator);
  161. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  162. TemplateTy Template;
  163. bool MemberOfUnknownSpecialization;
  164. UnqualifiedId TemplateName;
  165. TemplateName.setIdentifier(NewII, NameLoc);
  166. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  167. CXXScopeSpec NewSS, *NewSSPtr = SS;
  168. if (SS && NNS) {
  169. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  170. NewSSPtr = &NewSS;
  171. }
  172. if (Correction && (NNS || NewII != &II) &&
  173. // Ignore a correction to a template type as the to-be-corrected
  174. // identifier is not a template (typo correction for template names
  175. // is handled elsewhere).
  176. !(getLangOptions().CPlusPlus && NewSSPtr &&
  177. isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
  178. false, Template, MemberOfUnknownSpecialization))) {
  179. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  180. isClassName, HasTrailingDot, ObjectTypePtr,
  181. IsCtorOrDtorName,
  182. WantNontrivialTypeSourceInfo);
  183. if (Ty) {
  184. std::string CorrectedStr(Correction.getAsString(getLangOptions()));
  185. std::string CorrectedQuotedStr(
  186. Correction.getQuoted(getLangOptions()));
  187. Diag(NameLoc, diag::err_unknown_typename_suggest)
  188. << Result.getLookupName() << CorrectedQuotedStr
  189. << FixItHint::CreateReplacement(SourceRange(NameLoc),
  190. CorrectedStr);
  191. if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
  192. Diag(FirstDecl->getLocation(), diag::note_previous_decl)
  193. << CorrectedQuotedStr;
  194. if (SS && NNS)
  195. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  196. *CorrectedII = NewII;
  197. return Ty;
  198. }
  199. }
  200. }
  201. // If typo correction failed or was not performed, fall through
  202. case LookupResult::FoundOverloaded:
  203. case LookupResult::FoundUnresolvedValue:
  204. Result.suppressDiagnostics();
  205. return ParsedType();
  206. case LookupResult::Ambiguous:
  207. // Recover from type-hiding ambiguities by hiding the type. We'll
  208. // do the lookup again when looking for an object, and we can
  209. // diagnose the error then. If we don't do this, then the error
  210. // about hiding the type will be immediately followed by an error
  211. // that only makes sense if the identifier was treated like a type.
  212. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  213. Result.suppressDiagnostics();
  214. return ParsedType();
  215. }
  216. // Look to see if we have a type anywhere in the list of results.
  217. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  218. Res != ResEnd; ++Res) {
  219. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
  220. if (!IIDecl ||
  221. (*Res)->getLocation().getRawEncoding() <
  222. IIDecl->getLocation().getRawEncoding())
  223. IIDecl = *Res;
  224. }
  225. }
  226. if (!IIDecl) {
  227. // None of the entities we found is a type, so there is no way
  228. // to even assume that the result is a type. In this case, don't
  229. // complain about the ambiguity. The parser will either try to
  230. // perform this lookup again (e.g., as an object name), which
  231. // will produce the ambiguity, or will complain that it expected
  232. // a type name.
  233. Result.suppressDiagnostics();
  234. return ParsedType();
  235. }
  236. // We found a type within the ambiguous lookup; diagnose the
  237. // ambiguity and then return that type. This might be the right
  238. // answer, or it might not be, but it suppresses any attempt to
  239. // perform the name lookup again.
  240. break;
  241. case LookupResult::Found:
  242. IIDecl = Result.getFoundDecl();
  243. break;
  244. }
  245. assert(IIDecl && "Didn't find decl");
  246. QualType T;
  247. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  248. DiagnoseUseOfDecl(IIDecl, NameLoc);
  249. if (T.isNull())
  250. T = Context.getTypeDeclType(TD);
  251. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  252. // constructor or destructor name (in such a case, the scope specifier
  253. // will be attached to the enclosing Expr or Decl node).
  254. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
  255. if (WantNontrivialTypeSourceInfo) {
  256. // Construct a type with type-source information.
  257. TypeLocBuilder Builder;
  258. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  259. T = getElaboratedType(ETK_None, *SS, T);
  260. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  261. ElabTL.setKeywordLoc(SourceLocation());
  262. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  263. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  264. } else {
  265. T = getElaboratedType(ETK_None, *SS, T);
  266. }
  267. }
  268. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  269. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  270. if (!HasTrailingDot)
  271. T = Context.getObjCInterfaceType(IDecl);
  272. }
  273. if (T.isNull()) {
  274. // If it's not plausibly a type, suppress diagnostics.
  275. Result.suppressDiagnostics();
  276. return ParsedType();
  277. }
  278. return ParsedType::make(T);
  279. }
  280. /// isTagName() - This method is called *for error recovery purposes only*
  281. /// to determine if the specified name is a valid tag name ("struct foo"). If
  282. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  283. /// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
  284. /// where the user forgot to specify the tag.
  285. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  286. // Do a tag name lookup in this scope.
  287. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  288. LookupName(R, S, false);
  289. R.suppressDiagnostics();
  290. if (R.getResultKind() == LookupResult::Found)
  291. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  292. switch (TD->getTagKind()) {
  293. case TTK_Struct: return DeclSpec::TST_struct;
  294. case TTK_Union: return DeclSpec::TST_union;
  295. case TTK_Class: return DeclSpec::TST_class;
  296. case TTK_Enum: return DeclSpec::TST_enum;
  297. }
  298. }
  299. return DeclSpec::TST_unspecified;
  300. }
  301. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  302. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  303. /// then downgrade the missing typename error to a warning.
  304. /// This is needed for MSVC compatibility; Example:
  305. /// @code
  306. /// template<class T> class A {
  307. /// public:
  308. /// typedef int TYPE;
  309. /// };
  310. /// template<class T> class B : public A<T> {
  311. /// public:
  312. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  313. /// };
  314. /// @endcode
  315. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  316. if (CurContext->isRecord()) {
  317. const Type *Ty = SS->getScopeRep()->getAsType();
  318. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  319. for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
  320. BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
  321. if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
  322. return true;
  323. return S->isFunctionPrototypeScope();
  324. }
  325. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  326. }
  327. bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
  328. SourceLocation IILoc,
  329. Scope *S,
  330. CXXScopeSpec *SS,
  331. ParsedType &SuggestedType) {
  332. // We don't have anything to suggest (yet).
  333. SuggestedType = ParsedType();
  334. // There may have been a typo in the name of the type. Look up typo
  335. // results, in case we have something that we can suggest.
  336. TypeNameValidatorCCC Validator(false);
  337. if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc),
  338. LookupOrdinaryName, S, SS,
  339. Validator)) {
  340. std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
  341. std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
  342. if (Corrected.isKeyword()) {
  343. // We corrected to a keyword.
  344. // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
  345. Diag(IILoc, diag::err_unknown_typename_suggest)
  346. << &II << CorrectedQuotedStr;
  347. } else {
  348. NamedDecl *Result = Corrected.getCorrectionDecl();
  349. // We found a similarly-named type or interface; suggest that.
  350. if (!SS || !SS->isSet())
  351. Diag(IILoc, diag::err_unknown_typename_suggest)
  352. << &II << CorrectedQuotedStr
  353. << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
  354. else if (DeclContext *DC = computeDeclContext(*SS, false))
  355. Diag(IILoc, diag::err_unknown_nested_typename_suggest)
  356. << &II << DC << CorrectedQuotedStr << SS->getRange()
  357. << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
  358. else
  359. llvm_unreachable("could not have corrected a typo here");
  360. Diag(Result->getLocation(), diag::note_previous_decl)
  361. << CorrectedQuotedStr;
  362. SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
  363. false, false, ParsedType(),
  364. /*IsCtorOrDtorName=*/false,
  365. /*NonTrivialTypeSourceInfo=*/true);
  366. }
  367. return true;
  368. }
  369. if (getLangOptions().CPlusPlus) {
  370. // See if II is a class template that the user forgot to pass arguments to.
  371. UnqualifiedId Name;
  372. Name.setIdentifier(&II, IILoc);
  373. CXXScopeSpec EmptySS;
  374. TemplateTy TemplateResult;
  375. bool MemberOfUnknownSpecialization;
  376. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  377. Name, ParsedType(), true, TemplateResult,
  378. MemberOfUnknownSpecialization) == TNK_Type_template) {
  379. TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
  380. Diag(IILoc, diag::err_template_missing_args) << TplName;
  381. if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
  382. Diag(TplDecl->getLocation(), diag::note_template_decl_here)
  383. << TplDecl->getTemplateParameters()->getSourceRange();
  384. }
  385. return true;
  386. }
  387. }
  388. // FIXME: Should we move the logic that tries to recover from a missing tag
  389. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  390. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  391. Diag(IILoc, diag::err_unknown_typename) << &II;
  392. else if (DeclContext *DC = computeDeclContext(*SS, false))
  393. Diag(IILoc, diag::err_typename_nested_not_found)
  394. << &II << DC << SS->getRange();
  395. else if (isDependentScopeSpecifier(*SS)) {
  396. unsigned DiagID = diag::err_typename_missing;
  397. if (getLangOptions().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
  398. DiagID = diag::warn_typename_missing;
  399. Diag(SS->getRange().getBegin(), DiagID)
  400. << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
  401. << SourceRange(SS->getRange().getBegin(), IILoc)
  402. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  403. SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc)
  404. .get();
  405. } else {
  406. assert(SS && SS->isInvalid() &&
  407. "Invalid scope specifier has already been diagnosed");
  408. }
  409. return true;
  410. }
  411. /// \brief Determine whether the given result set contains either a type name
  412. /// or
  413. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  414. bool CheckTemplate = R.getSema().getLangOptions().CPlusPlus &&
  415. NextToken.is(tok::less);
  416. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  417. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  418. return true;
  419. if (CheckTemplate && isa<TemplateDecl>(*I))
  420. return true;
  421. }
  422. return false;
  423. }
  424. Sema::NameClassification Sema::ClassifyName(Scope *S,
  425. CXXScopeSpec &SS,
  426. IdentifierInfo *&Name,
  427. SourceLocation NameLoc,
  428. const Token &NextToken) {
  429. DeclarationNameInfo NameInfo(Name, NameLoc);
  430. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  431. if (NextToken.is(tok::coloncolon)) {
  432. BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
  433. QualType(), false, SS, 0, false);
  434. }
  435. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  436. LookupParsedName(Result, S, &SS, !CurMethod);
  437. // Perform lookup for Objective-C instance variables (including automatically
  438. // synthesized instance variables), if we're in an Objective-C method.
  439. // FIXME: This lookup really, really needs to be folded in to the normal
  440. // unqualified lookup mechanism.
  441. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  442. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  443. if (E.get() || E.isInvalid())
  444. return E;
  445. }
  446. bool SecondTry = false;
  447. bool IsFilteredTemplateName = false;
  448. Corrected:
  449. switch (Result.getResultKind()) {
  450. case LookupResult::NotFound:
  451. // If an unqualified-id is followed by a '(', then we have a function
  452. // call.
  453. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  454. // In C++, this is an ADL-only call.
  455. // FIXME: Reference?
  456. if (getLangOptions().CPlusPlus)
  457. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  458. // C90 6.3.2.2:
  459. // If the expression that precedes the parenthesized argument list in a
  460. // function call consists solely of an identifier, and if no
  461. // declaration is visible for this identifier, the identifier is
  462. // implicitly declared exactly as if, in the innermost block containing
  463. // the function call, the declaration
  464. //
  465. // extern int identifier ();
  466. //
  467. // appeared.
  468. //
  469. // We also allow this in C99 as an extension.
  470. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  471. Result.addDecl(D);
  472. Result.resolveKind();
  473. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  474. }
  475. }
  476. // In C, we first see whether there is a tag type by the same name, in
  477. // which case it's likely that the user just forget to write "enum",
  478. // "struct", or "union".
  479. if (!getLangOptions().CPlusPlus && !SecondTry) {
  480. Result.clear(LookupTagName);
  481. LookupParsedName(Result, S, &SS);
  482. if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
  483. const char *TagName = 0;
  484. const char *FixItTagName = 0;
  485. switch (Tag->getTagKind()) {
  486. case TTK_Class:
  487. TagName = "class";
  488. FixItTagName = "class ";
  489. break;
  490. case TTK_Enum:
  491. TagName = "enum";
  492. FixItTagName = "enum ";
  493. break;
  494. case TTK_Struct:
  495. TagName = "struct";
  496. FixItTagName = "struct ";
  497. break;
  498. case TTK_Union:
  499. TagName = "union";
  500. FixItTagName = "union ";
  501. break;
  502. }
  503. Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  504. << Name << TagName << getLangOptions().CPlusPlus
  505. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  506. break;
  507. }
  508. Result.clear(LookupOrdinaryName);
  509. }
  510. // Perform typo correction to determine if there is another name that is
  511. // close to this name.
  512. if (!SecondTry) {
  513. SecondTry = true;
  514. CorrectionCandidateCallback DefaultValidator;
  515. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  516. Result.getLookupKind(), S,
  517. &SS, DefaultValidator)) {
  518. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  519. unsigned QualifiedDiag = diag::err_no_member_suggest;
  520. std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
  521. std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
  522. NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
  523. NamedDecl *UnderlyingFirstDecl
  524. = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
  525. if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
  526. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  527. UnqualifiedDiag = diag::err_no_template_suggest;
  528. QualifiedDiag = diag::err_no_member_template_suggest;
  529. } else if (UnderlyingFirstDecl &&
  530. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  531. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  532. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  533. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  534. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  535. }
  536. if (SS.isEmpty())
  537. Diag(NameLoc, UnqualifiedDiag)
  538. << Name << CorrectedQuotedStr
  539. << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
  540. else
  541. Diag(NameLoc, QualifiedDiag)
  542. << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
  543. << SS.getRange()
  544. << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
  545. // Update the name, so that the caller has the new name.
  546. Name = Corrected.getCorrectionAsIdentifierInfo();
  547. // Typo correction corrected to a keyword.
  548. if (Corrected.isKeyword())
  549. return Corrected.getCorrectionAsIdentifierInfo();
  550. // Also update the LookupResult...
  551. // FIXME: This should probably go away at some point
  552. Result.clear();
  553. Result.setLookupName(Corrected.getCorrection());
  554. if (FirstDecl) {
  555. Result.addDecl(FirstDecl);
  556. Diag(FirstDecl->getLocation(), diag::note_previous_decl)
  557. << CorrectedQuotedStr;
  558. }
  559. // If we found an Objective-C instance variable, let
  560. // LookupInObjCMethod build the appropriate expression to
  561. // reference the ivar.
  562. // FIXME: This is a gross hack.
  563. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  564. Result.clear();
  565. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  566. return move(E);
  567. }
  568. goto Corrected;
  569. }
  570. }
  571. // We failed to correct; just fall through and let the parser deal with it.
  572. Result.suppressDiagnostics();
  573. return NameClassification::Unknown();
  574. case LookupResult::NotFoundInCurrentInstantiation: {
  575. // We performed name lookup into the current instantiation, and there were
  576. // dependent bases, so we treat this result the same way as any other
  577. // dependent nested-name-specifier.
  578. // C++ [temp.res]p2:
  579. // A name used in a template declaration or definition and that is
  580. // dependent on a template-parameter is assumed not to name a type
  581. // unless the applicable name lookup finds a type name or the name is
  582. // qualified by the keyword typename.
  583. //
  584. // FIXME: If the next token is '<', we might want to ask the parser to
  585. // perform some heroics to see if we actually have a
  586. // template-argument-list, which would indicate a missing 'template'
  587. // keyword here.
  588. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  589. NameInfo, /*TemplateArgs=*/0);
  590. }
  591. case LookupResult::Found:
  592. case LookupResult::FoundOverloaded:
  593. case LookupResult::FoundUnresolvedValue:
  594. break;
  595. case LookupResult::Ambiguous:
  596. if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
  597. hasAnyAcceptableTemplateNames(Result)) {
  598. // C++ [temp.local]p3:
  599. // A lookup that finds an injected-class-name (10.2) can result in an
  600. // ambiguity in certain cases (for example, if it is found in more than
  601. // one base class). If all of the injected-class-names that are found
  602. // refer to specializations of the same class template, and if the name
  603. // is followed by a template-argument-list, the reference refers to the
  604. // class template itself and not a specialization thereof, and is not
  605. // ambiguous.
  606. //
  607. // This filtering can make an ambiguous result into an unambiguous one,
  608. // so try again after filtering out template names.
  609. FilterAcceptableTemplateNames(Result);
  610. if (!Result.isAmbiguous()) {
  611. IsFilteredTemplateName = true;
  612. break;
  613. }
  614. }
  615. // Diagnose the ambiguity and return an error.
  616. return NameClassification::Error();
  617. }
  618. if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
  619. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  620. // C++ [temp.names]p3:
  621. // After name lookup (3.4) finds that a name is a template-name or that
  622. // an operator-function-id or a literal- operator-id refers to a set of
  623. // overloaded functions any member of which is a function template if
  624. // this is followed by a <, the < is always taken as the delimiter of a
  625. // template-argument-list and never as the less-than operator.
  626. if (!IsFilteredTemplateName)
  627. FilterAcceptableTemplateNames(Result);
  628. if (!Result.empty()) {
  629. bool IsFunctionTemplate;
  630. TemplateName Template;
  631. if (Result.end() - Result.begin() > 1) {
  632. IsFunctionTemplate = true;
  633. Template = Context.getOverloadedTemplateName(Result.begin(),
  634. Result.end());
  635. } else {
  636. TemplateDecl *TD
  637. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  638. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  639. if (SS.isSet() && !SS.isInvalid())
  640. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  641. /*TemplateKeyword=*/false,
  642. TD);
  643. else
  644. Template = TemplateName(TD);
  645. }
  646. if (IsFunctionTemplate) {
  647. // Function templates always go through overload resolution, at which
  648. // point we'll perform the various checks (e.g., accessibility) we need
  649. // to based on which function we selected.
  650. Result.suppressDiagnostics();
  651. return NameClassification::FunctionTemplate(Template);
  652. }
  653. return NameClassification::TypeTemplate(Template);
  654. }
  655. }
  656. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  657. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  658. DiagnoseUseOfDecl(Type, NameLoc);
  659. QualType T = Context.getTypeDeclType(Type);
  660. return ParsedType::make(T);
  661. }
  662. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  663. if (!Class) {
  664. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  665. if (ObjCCompatibleAliasDecl *Alias
  666. = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  667. Class = Alias->getClassInterface();
  668. }
  669. if (Class) {
  670. DiagnoseUseOfDecl(Class, NameLoc);
  671. if (NextToken.is(tok::period)) {
  672. // Interface. <something> is parsed as a property reference expression.
  673. // Just return "unknown" as a fall-through for now.
  674. Result.suppressDiagnostics();
  675. return NameClassification::Unknown();
  676. }
  677. QualType T = Context.getObjCInterfaceType(Class);
  678. return ParsedType::make(T);
  679. }
  680. if (!Result.empty() && (*Result.begin())->isCXXClassMember())
  681. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
  682. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  683. return BuildDeclarationNameExpr(SS, Result, ADL);
  684. }
  685. // Determines the context to return to after temporarily entering a
  686. // context. This depends in an unnecessarily complicated way on the
  687. // exact ordering of callbacks from the parser.
  688. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  689. // Functions defined inline within classes aren't parsed until we've
  690. // finished parsing the top-level class, so the top-level class is
  691. // the context we'll need to return to.
  692. if (isa<FunctionDecl>(DC)) {
  693. DC = DC->getLexicalParent();
  694. // A function not defined within a class will always return to its
  695. // lexical context.
  696. if (!isa<CXXRecordDecl>(DC))
  697. return DC;
  698. // A C++ inline method/friend is parsed *after* the topmost class
  699. // it was declared in is fully parsed ("complete"); the topmost
  700. // class is the context we need to return to.
  701. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  702. DC = RD;
  703. // Return the declaration context of the topmost class the inline method is
  704. // declared in.
  705. return DC;
  706. }
  707. return DC->getLexicalParent();
  708. }
  709. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  710. assert(getContainingDC(DC) == CurContext &&
  711. "The next DeclContext should be lexically contained in the current one.");
  712. CurContext = DC;
  713. S->setEntity(DC);
  714. }
  715. void Sema::PopDeclContext() {
  716. assert(CurContext && "DeclContext imbalance!");
  717. CurContext = getContainingDC(CurContext);
  718. assert(CurContext && "Popped translation unit!");
  719. }
  720. /// EnterDeclaratorContext - Used when we must lookup names in the context
  721. /// of a declarator's nested name specifier.
  722. ///
  723. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  724. // C++0x [basic.lookup.unqual]p13:
  725. // A name used in the definition of a static data member of class
  726. // X (after the qualified-id of the static member) is looked up as
  727. // if the name was used in a member function of X.
  728. // C++0x [basic.lookup.unqual]p14:
  729. // If a variable member of a namespace is defined outside of the
  730. // scope of its namespace then any name used in the definition of
  731. // the variable member (after the declarator-id) is looked up as
  732. // if the definition of the variable member occurred in its
  733. // namespace.
  734. // Both of these imply that we should push a scope whose context
  735. // is the semantic context of the declaration. We can't use
  736. // PushDeclContext here because that context is not necessarily
  737. // lexically contained in the current context. Fortunately,
  738. // the containing scope should have the appropriate information.
  739. assert(!S->getEntity() && "scope already has entity");
  740. #ifndef NDEBUG
  741. Scope *Ancestor = S->getParent();
  742. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  743. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  744. #endif
  745. CurContext = DC;
  746. S->setEntity(DC);
  747. }
  748. void Sema::ExitDeclaratorContext(Scope *S) {
  749. assert(S->getEntity() == CurContext && "Context imbalance!");
  750. // Switch back to the lexical context. The safety of this is
  751. // enforced by an assert in EnterDeclaratorContext.
  752. Scope *Ancestor = S->getParent();
  753. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  754. CurContext = (DeclContext*) Ancestor->getEntity();
  755. // We don't need to do anything with the scope, which is going to
  756. // disappear.
  757. }
  758. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  759. FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  760. if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
  761. // We assume that the caller has already called
  762. // ActOnReenterTemplateScope
  763. FD = TFD->getTemplatedDecl();
  764. }
  765. if (!FD)
  766. return;
  767. PushDeclContext(S, FD);
  768. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  769. ParmVarDecl *Param = FD->getParamDecl(P);
  770. // If the parameter has an identifier, then add it to the scope
  771. if (Param->getIdentifier()) {
  772. S->AddDecl(Param);
  773. IdResolver.AddDecl(Param);
  774. }
  775. }
  776. }
  777. /// \brief Determine whether we allow overloading of the function
  778. /// PrevDecl with another declaration.
  779. ///
  780. /// This routine determines whether overloading is possible, not
  781. /// whether some new function is actually an overload. It will return
  782. /// true in C++ (where we can always provide overloads) or, as an
  783. /// extension, in C when the previous function is already an
  784. /// overloaded function declaration or has the "overloadable"
  785. /// attribute.
  786. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  787. ASTContext &Context) {
  788. if (Context.getLangOptions().CPlusPlus)
  789. return true;
  790. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  791. return true;
  792. return (Previous.getResultKind() == LookupResult::Found
  793. && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
  794. }
  795. /// Add this decl to the scope shadowed decl chains.
  796. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  797. // Move up the scope chain until we find the nearest enclosing
  798. // non-transparent context. The declaration will be introduced into this
  799. // scope.
  800. while (S->getEntity() &&
  801. ((DeclContext *)S->getEntity())->isTransparentContext())
  802. S = S->getParent();
  803. // Add scoped declarations into their context, so that they can be
  804. // found later. Declarations without a context won't be inserted
  805. // into any context.
  806. if (AddToContext)
  807. CurContext->addDecl(D);
  808. // Out-of-line definitions shouldn't be pushed into scope in C++.
  809. // Out-of-line variable and function definitions shouldn't even in C.
  810. if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
  811. D->isOutOfLine() &&
  812. !D->getDeclContext()->getRedeclContext()->Equals(
  813. D->getLexicalDeclContext()->getRedeclContext()))
  814. return;
  815. // Template instantiations should also not be pushed into scope.
  816. if (isa<FunctionDecl>(D) &&
  817. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  818. return;
  819. // If this replaces anything in the current scope,
  820. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  821. IEnd = IdResolver.end();
  822. for (; I != IEnd; ++I) {
  823. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  824. S->RemoveDecl(*I);
  825. IdResolver.RemoveDecl(*I);
  826. // Should only need to replace one decl.
  827. break;
  828. }
  829. }
  830. S->AddDecl(D);
  831. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  832. // Implicitly-generated labels may end up getting generated in an order that
  833. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  834. // the label at the appropriate place in the identifier chain.
  835. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  836. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  837. if (IDC == CurContext) {
  838. if (!S->isDeclScope(*I))
  839. continue;
  840. } else if (IDC->Encloses(CurContext))
  841. break;
  842. }
  843. IdResolver.InsertDeclAfter(I, D);
  844. } else {
  845. IdResolver.AddDecl(D);
  846. }
  847. }
  848. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  849. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  850. TUScope->AddDecl(D);
  851. }
  852. bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
  853. bool ExplicitInstantiationOrSpecialization) {
  854. return IdResolver.isDeclInScope(D, Ctx, Context, S,
  855. ExplicitInstantiationOrSpecialization);
  856. }
  857. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  858. DeclContext *TargetDC = DC->getPrimaryContext();
  859. do {
  860. if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
  861. if (ScopeDC->getPrimaryContext() == TargetDC)
  862. return S;
  863. } while ((S = S->getParent()));
  864. return 0;
  865. }
  866. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  867. DeclContext*,
  868. ASTContext&);
  869. /// Filters out lookup results that don't fall within the given scope
  870. /// as determined by isDeclInScope.
  871. void Sema::FilterLookupForScope(LookupResult &R,
  872. DeclContext *Ctx, Scope *S,
  873. bool ConsiderLinkage,
  874. bool ExplicitInstantiationOrSpecialization) {
  875. LookupResult::Filter F = R.makeFilter();
  876. while (F.hasNext()) {
  877. NamedDecl *D = F.next();
  878. if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
  879. continue;
  880. if (ConsiderLinkage &&
  881. isOutOfScopePreviousDeclaration(D, Ctx, Context))
  882. continue;
  883. F.erase();
  884. }
  885. F.done();
  886. }
  887. static bool isUsingDecl(NamedDecl *D) {
  888. return isa<UsingShadowDecl>(D) ||
  889. isa<UnresolvedUsingTypenameDecl>(D) ||
  890. isa<UnresolvedUsingValueDecl>(D);
  891. }
  892. /// Removes using shadow declarations from the lookup results.
  893. static void RemoveUsingDecls(LookupResult &R) {
  894. LookupResult::Filter F = R.makeFilter();
  895. while (F.hasNext())
  896. if (isUsingDecl(F.next()))
  897. F.erase();
  898. F.done();
  899. }
  900. /// \brief Check for this common pattern:
  901. /// @code
  902. /// class S {
  903. /// S(const S&); // DO NOT IMPLEMENT
  904. /// void operator=(const S&); // DO NOT IMPLEMENT
  905. /// };
  906. /// @endcode
  907. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  908. // FIXME: Should check for private access too but access is set after we get
  909. // the decl here.
  910. if (D->doesThisDeclarationHaveABody())
  911. return false;
  912. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  913. return CD->isCopyConstructor();
  914. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  915. return Method->isCopyAssignmentOperator();
  916. return false;
  917. }
  918. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  919. assert(D);
  920. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  921. return false;
  922. // Ignore class templates.
  923. if (D->getDeclContext()->isDependentContext() ||
  924. D->getLexicalDeclContext()->isDependentContext())
  925. return false;
  926. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  927. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  928. return false;
  929. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  930. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  931. return false;
  932. } else {
  933. // 'static inline' functions are used in headers; don't warn.
  934. if (FD->getStorageClass() == SC_Static &&
  935. FD->isInlineSpecified())
  936. return false;
  937. }
  938. if (FD->doesThisDeclarationHaveABody() &&
  939. Context.DeclMustBeEmitted(FD))
  940. return false;
  941. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  942. if (!VD->isFileVarDecl() ||
  943. VD->getType().isConstant(Context) ||
  944. Context.DeclMustBeEmitted(VD))
  945. return false;
  946. if (VD->isStaticDataMember() &&
  947. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  948. return false;
  949. } else {
  950. return false;
  951. }
  952. // Only warn for unused decls internal to the translation unit.
  953. if (D->getLinkage() == ExternalLinkage)
  954. return false;
  955. return true;
  956. }
  957. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  958. if (!D)
  959. return;
  960. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  961. const FunctionDecl *First = FD->getFirstDeclaration();
  962. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  963. return; // First should already be in the vector.
  964. }
  965. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  966. const VarDecl *First = VD->getFirstDeclaration();
  967. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  968. return; // First should already be in the vector.
  969. }
  970. if (ShouldWarnIfUnusedFileScopedDecl(D))
  971. UnusedFileScopedDecls.push_back(D);
  972. }
  973. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  974. if (D->isInvalidDecl())
  975. return false;
  976. if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
  977. return false;
  978. if (isa<LabelDecl>(D))
  979. return true;
  980. // White-list anything that isn't a local variable.
  981. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
  982. !D->getDeclContext()->isFunctionOrMethod())
  983. return false;
  984. // Types of valid local variables should be complete, so this should succeed.
  985. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  986. // White-list anything with an __attribute__((unused)) type.
  987. QualType Ty = VD->getType();
  988. // Only look at the outermost level of typedef.
  989. if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
  990. if (TT->getDecl()->hasAttr<UnusedAttr>())
  991. return false;
  992. }
  993. // If we failed to complete the type for some reason, or if the type is
  994. // dependent, don't diagnose the variable.
  995. if (Ty->isIncompleteType() || Ty->isDependentType())
  996. return false;
  997. if (const TagType *TT = Ty->getAs<TagType>()) {
  998. const TagDecl *Tag = TT->getDecl();
  999. if (Tag->hasAttr<UnusedAttr>())
  1000. return false;
  1001. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1002. if (!RD->hasTrivialDestructor())
  1003. return false;
  1004. if (const Expr *Init = VD->getInit()) {
  1005. const CXXConstructExpr *Construct =
  1006. dyn_cast<CXXConstructExpr>(Init);
  1007. if (Construct && !Construct->isElidable()) {
  1008. CXXConstructorDecl *CD = Construct->getConstructor();
  1009. if (!CD->isTrivial())
  1010. return false;
  1011. }
  1012. }
  1013. }
  1014. }
  1015. // TODO: __attribute__((unused)) templates?
  1016. }
  1017. return true;
  1018. }
  1019. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1020. FixItHint &Hint) {
  1021. if (isa<LabelDecl>(D)) {
  1022. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1023. tok::colon, Ctx.getSourceManager(), Ctx.getLangOptions(), true);
  1024. if (AfterColon.isInvalid())
  1025. return;
  1026. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1027. getCharRange(D->getLocStart(), AfterColon));
  1028. }
  1029. return;
  1030. }
  1031. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1032. /// unless they are marked attr(unused).
  1033. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1034. FixItHint Hint;
  1035. if (!ShouldDiagnoseUnusedDecl(D))
  1036. return;
  1037. GenerateFixForUnusedDecl(D, Context, Hint);
  1038. unsigned DiagID;
  1039. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1040. DiagID = diag::warn_unused_exception_param;
  1041. else if (isa<LabelDecl>(D))
  1042. DiagID = diag::warn_unused_label;
  1043. else
  1044. DiagID = diag::warn_unused_variable;
  1045. Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
  1046. }
  1047. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1048. // Verify that we have no forward references left. If so, there was a goto
  1049. // or address of a label taken, but no definition of it. Label fwd
  1050. // definitions are indicated with a null substmt.
  1051. if (L->getStmt() == 0)
  1052. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1053. }
  1054. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1055. if (S->decl_empty()) return;
  1056. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1057. "Scope shouldn't contain decls!");
  1058. for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
  1059. I != E; ++I) {
  1060. Decl *TmpD = (*I);
  1061. assert(TmpD && "This decl didn't get pushed??");
  1062. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1063. NamedDecl *D = cast<NamedDecl>(TmpD);
  1064. if (!D->getDeclName()) continue;
  1065. // Diagnose unused variables in this scope.
  1066. if (!S->hasErrorOccurred())
  1067. DiagnoseUnusedDecl(D);
  1068. // If this was a forward reference to a label, verify it was defined.
  1069. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1070. CheckPoppedLabel(LD, *this);
  1071. // Remove this name from our lexical scope.
  1072. IdResolver.RemoveDecl(D);
  1073. }
  1074. }
  1075. /// \brief Look for an Objective-C class in the translation unit.
  1076. ///
  1077. /// \param Id The name of the Objective-C class we're looking for. If
  1078. /// typo-correction fixes this name, the Id will be updated
  1079. /// to the fixed name.
  1080. ///
  1081. /// \param IdLoc The location of the name in the translation unit.
  1082. ///
  1083. /// \param TypoCorrection If true, this routine will attempt typo correction
  1084. /// if there is no class with the given name.
  1085. ///
  1086. /// \returns The declaration of the named Objective-C class, or NULL if the
  1087. /// class could not be found.
  1088. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1089. SourceLocation IdLoc,
  1090. bool DoTypoCorrection) {
  1091. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1092. // creation from this context.
  1093. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1094. if (!IDecl && DoTypoCorrection) {
  1095. // Perform typo correction at the given location, but only if we
  1096. // find an Objective-C class name.
  1097. DeclFilterCCC<ObjCInterfaceDecl> Validator;
  1098. if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
  1099. LookupOrdinaryName, TUScope, NULL,
  1100. Validator)) {
  1101. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1102. Diag(IdLoc, diag::err_undef_interface_suggest)
  1103. << Id << IDecl->getDeclName()
  1104. << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
  1105. Diag(IDecl->getLocation(), diag::note_previous_decl)
  1106. << IDecl->getDeclName();
  1107. Id = IDecl->getIdentifier();
  1108. }
  1109. }
  1110. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1111. // This routine must always return a class definition, if any.
  1112. if (Def && Def->getDefinition())
  1113. Def = Def->getDefinition();
  1114. return Def;
  1115. }
  1116. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1117. /// from S, where a non-field would be declared. This routine copes
  1118. /// with the difference between C and C++ scoping rules in structs and
  1119. /// unions. For example, the following code is well-formed in C but
  1120. /// ill-formed in C++:
  1121. /// @code
  1122. /// struct S6 {
  1123. /// enum { BAR } e;
  1124. /// };
  1125. ///
  1126. /// void test_S6() {
  1127. /// struct S6 a;
  1128. /// a.e = BAR;
  1129. /// }
  1130. /// @endcode
  1131. /// For the declaration of BAR, this routine will return a different
  1132. /// scope. The scope S will be the scope of the unnamed enumeration
  1133. /// within S6. In C++, this routine will return the scope associated
  1134. /// with S6, because the enumeration's scope is a transparent
  1135. /// context but structures can contain non-field names. In C, this
  1136. /// routine will return the translation unit scope, since the
  1137. /// enumeration's scope is a transparent context and structures cannot
  1138. /// contain non-field names.
  1139. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1140. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1141. (S->getEntity() &&
  1142. ((DeclContext *)S->getEntity())->isTransparentContext()) ||
  1143. (S->isClassScope() && !getLangOptions().CPlusPlus))
  1144. S = S->getParent();
  1145. return S;
  1146. }
  1147. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1148. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1149. /// if we're creating this built-in in anticipation of redeclaring the
  1150. /// built-in.
  1151. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
  1152. Scope *S, bool ForRedeclaration,
  1153. SourceLocation Loc) {
  1154. Builtin::ID BID = (Builtin::ID)bid;
  1155. ASTContext::GetBuiltinTypeError Error;
  1156. QualType R = Context.GetBuiltinType(BID, Error);
  1157. switch (Error) {
  1158. case ASTContext::GE_None:
  1159. // Okay
  1160. break;
  1161. case ASTContext::GE_Missing_stdio:
  1162. if (ForRedeclaration)
  1163. Diag(Loc, diag::warn_implicit_decl_requires_stdio)
  1164. << Context.BuiltinInfo.GetName(BID);
  1165. return 0;
  1166. case ASTContext::GE_Missing_setjmp:
  1167. if (ForRedeclaration)
  1168. Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
  1169. << Context.BuiltinInfo.GetName(BID);
  1170. return 0;
  1171. case ASTContext::GE_Missing_ucontext:
  1172. if (ForRedeclaration)
  1173. Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
  1174. << Context.BuiltinInfo.GetName(BID);
  1175. return 0;
  1176. }
  1177. if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  1178. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1179. << Context.BuiltinInfo.GetName(BID)
  1180. << R;
  1181. if (Context.BuiltinInfo.getHeaderName(BID) &&
  1182. Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
  1183. != DiagnosticsEngine::Ignored)
  1184. Diag(Loc, diag::note_please_include_header)
  1185. << Context.BuiltinInfo.getHeaderName(BID)
  1186. << Context.BuiltinInfo.GetName(BID);
  1187. }
  1188. FunctionDecl *New = FunctionDecl::Create(Context,
  1189. Context.getTranslationUnitDecl(),
  1190. Loc, Loc, II, R, /*TInfo=*/0,
  1191. SC_Extern,
  1192. SC_None, false,
  1193. /*hasPrototype=*/true);
  1194. New->setImplicit();
  1195. // Create Decl objects for each parameter, adding them to the
  1196. // FunctionDecl.
  1197. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1198. SmallVector<ParmVarDecl*, 16> Params;
  1199. for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
  1200. ParmVarDecl *parm =
  1201. ParmVarDecl::Create(Context, New, SourceLocation(),
  1202. SourceLocation(), 0,
  1203. FT->getArgType(i), /*TInfo=*/0,
  1204. SC_None, SC_None, 0);
  1205. parm->setScopeInfo(0, i);
  1206. Params.push_back(parm);
  1207. }
  1208. New->setParams(Params);
  1209. }
  1210. AddKnownFunctionAttributes(New);
  1211. // TUScope is the translation-unit scope to insert this function into.
  1212. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1213. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1214. // entirely, but we're not there yet.
  1215. DeclContext *SavedContext = CurContext;
  1216. CurContext = Context.getTranslationUnitDecl();
  1217. PushOnScopeChains(New, TUScope);
  1218. CurContext = SavedContext;
  1219. return New;
  1220. }
  1221. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1222. QualType OldType;
  1223. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1224. OldType = OldTypedef->getUnderlyingType();
  1225. else
  1226. OldType = Context.getTypeDeclType(Old);
  1227. QualType NewType = New->getUnderlyingType();
  1228. if (NewType->isVariablyModifiedType()) {
  1229. // Must not redefine a typedef with a variably-modified type.
  1230. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1231. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1232. << Kind << NewType;
  1233. if (Old->getLocation().isValid())
  1234. Diag(Old->getLocation(), diag::note_previous_definition);
  1235. New->setInvalidDecl();
  1236. return true;
  1237. }
  1238. if (OldType != NewType &&
  1239. !OldType->isDependentType() &&
  1240. !NewType->isDependentType() &&
  1241. !Context.hasSameType(OldType, NewType)) {
  1242. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1243. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1244. << Kind << NewType << OldType;
  1245. if (Old->getLocation().isValid())
  1246. Diag(Old->getLocation(), diag::note_previous_definition);
  1247. New->setInvalidDecl();
  1248. return true;
  1249. }
  1250. return false;
  1251. }
  1252. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1253. /// same name and scope as a previous declaration 'Old'. Figure out
  1254. /// how to resolve this situation, merging decls or emitting
  1255. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1256. ///
  1257. void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
  1258. // If the new decl is known invalid already, don't bother doing any
  1259. // merging checks.
  1260. if (New->isInvalidDecl()) return;
  1261. // Allow multiple definitions for ObjC built-in typedefs.
  1262. // FIXME: Verify the underlying types are equivalent!
  1263. if (getLangOptions().ObjC1) {
  1264. const IdentifierInfo *TypeID = New->getIdentifier();
  1265. switch (TypeID->getLength()) {
  1266. default: break;
  1267. case 2:
  1268. if (!TypeID->isStr("id"))
  1269. break;
  1270. Context.setObjCIdRedefinitionType(New->getUnderlyingType());
  1271. // Install the built-in type for 'id', ignoring the current definition.
  1272. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1273. return;
  1274. case 5:
  1275. if (!TypeID->isStr("Class"))
  1276. break;
  1277. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1278. // Install the built-in type for 'Class', ignoring the current definition.
  1279. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1280. return;
  1281. case 3:
  1282. if (!TypeID->isStr("SEL"))
  1283. break;
  1284. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1285. // Install the built-in type for 'SEL', ignoring the current definition.
  1286. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1287. return;
  1288. }
  1289. // Fall through - the typedef name was not a builtin type.
  1290. }
  1291. // Verify the old decl was also a type.
  1292. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1293. if (!Old) {
  1294. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1295. << New->getDeclName();
  1296. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1297. if (OldD->getLocation().isValid())
  1298. Diag(OldD->getLocation(), diag::note_previous_definition);
  1299. return New->setInvalidDecl();
  1300. }
  1301. // If the old declaration is invalid, just give up here.
  1302. if (Old->isInvalidDecl())
  1303. return New->setInvalidDecl();
  1304. // If the typedef types are not identical, reject them in all languages and
  1305. // with any extensions enabled.
  1306. if (isIncompatibleTypedef(Old, New))
  1307. return;
  1308. // The types match. Link up the redeclaration chain if the old
  1309. // declaration was a typedef.
  1310. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
  1311. New->setPreviousDeclaration(Typedef);
  1312. if (getLangOptions().MicrosoftExt)
  1313. return;
  1314. if (getLangOptions().CPlusPlus) {
  1315. // C++ [dcl.typedef]p2:
  1316. // In a given non-class scope, a typedef specifier can be used to
  1317. // redefine the name of any type declared in that scope to refer
  1318. // to the type to which it already refers.
  1319. if (!isa<CXXRecordDecl>(CurContext))
  1320. return;
  1321. // C++0x [dcl.typedef]p4:
  1322. // In a given class scope, a typedef specifier can be used to redefine
  1323. // any class-name declared in that scope that is not also a typedef-name
  1324. // to refer to the type to which it already refers.
  1325. //
  1326. // This wording came in via DR424, which was a correction to the
  1327. // wording in DR56, which accidentally banned code like:
  1328. //
  1329. // struct S {
  1330. // typedef struct A { } A;
  1331. // };
  1332. //
  1333. // in the C++03 standard. We implement the C++0x semantics, which
  1334. // allow the above but disallow
  1335. //
  1336. // struct S {
  1337. // typedef int I;
  1338. // typedef int I;
  1339. // };
  1340. //
  1341. // since that was the intent of DR56.
  1342. if (!isa<TypedefNameDecl>(Old))
  1343. return;
  1344. Diag(New->getLocation(), diag::err_redefinition)
  1345. << New->getDeclName();
  1346. Diag(Old->getLocation(), diag::note_previous_definition);
  1347. return New->setInvalidDecl();
  1348. }
  1349. // Modules always permit redefinition of typedefs, as does C11.
  1350. if (getLangOptions().Modules || getLangOptions().C11)
  1351. return;
  1352. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1353. // is normally mapped to an error, but can be controlled with
  1354. // -Wtypedef-redefinition. If either the original or the redefinition is
  1355. // in a system header, don't emit this for compatibility with GCC.
  1356. if (getDiagnostics().getSuppressSystemWarnings() &&
  1357. (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1358. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1359. return;
  1360. Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
  1361. << New->getDeclName();
  1362. Diag(Old->getLocation(), diag::note_previous_definition);
  1363. return;
  1364. }
  1365. /// DeclhasAttr - returns true if decl Declaration already has the target
  1366. /// attribute.
  1367. static bool
  1368. DeclHasAttr(const Decl *D, const Attr *A) {
  1369. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  1370. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  1371. for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
  1372. if ((*i)->getKind() == A->getKind()) {
  1373. if (Ann) {
  1374. if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
  1375. return true;
  1376. continue;
  1377. }
  1378. // FIXME: Don't hardcode this check
  1379. if (OA && isa<OwnershipAttr>(*i))
  1380. return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
  1381. return true;
  1382. }
  1383. return false;
  1384. }
  1385. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  1386. void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
  1387. bool MergeDeprecation) {
  1388. if (!Old->hasAttrs())
  1389. return;
  1390. bool foundAny = New->hasAttrs();
  1391. // Ensure that any moving of objects within the allocated map is done before
  1392. // we process them.
  1393. if (!foundAny) New->setAttrs(AttrVec());
  1394. for (specific_attr_iterator<InheritableAttr>
  1395. i = Old->specific_attr_begin<InheritableAttr>(),
  1396. e = Old->specific_attr_end<InheritableAttr>();
  1397. i != e; ++i) {
  1398. // Ignore deprecated/unavailable/availability attributes if requested.
  1399. if (!MergeDeprecation &&
  1400. (isa<DeprecatedAttr>(*i) ||
  1401. isa<UnavailableAttr>(*i) ||
  1402. isa<AvailabilityAttr>(*i)))
  1403. continue;
  1404. if (!DeclHasAttr(New, *i)) {
  1405. InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(Context));
  1406. newAttr->setInherited(true);
  1407. New->addAttr(newAttr);
  1408. foundAny = true;
  1409. }
  1410. }
  1411. if (!foundAny) New->dropAttrs();
  1412. }
  1413. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  1414. /// to the new one.
  1415. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  1416. const ParmVarDecl *oldDecl,
  1417. ASTContext &C) {
  1418. if (!oldDecl->hasAttrs())
  1419. return;
  1420. bool foundAny = newDecl->hasAttrs();
  1421. // Ensure that any moving of objects within the allocated map is
  1422. // done before we process them.
  1423. if (!foundAny) newDecl->setAttrs(AttrVec());
  1424. for (specific_attr_iterator<InheritableParamAttr>
  1425. i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
  1426. e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
  1427. if (!DeclHasAttr(newDecl, *i)) {
  1428. InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
  1429. newAttr->setInherited(true);
  1430. newDecl->addAttr(newAttr);
  1431. foundAny = true;
  1432. }
  1433. }
  1434. if (!foundAny) newDecl->dropAttrs();
  1435. }
  1436. namespace {
  1437. /// Used in MergeFunctionDecl to keep track of function parameters in
  1438. /// C.
  1439. struct GNUCompatibleParamWarning {
  1440. ParmVarDecl *OldParm;
  1441. ParmVarDecl *NewParm;
  1442. QualType PromotedType;
  1443. };
  1444. }
  1445. /// getSpecialMember - get the special member enum for a method.
  1446. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  1447. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  1448. if (Ctor->isDefaultConstructor())
  1449. return Sema::CXXDefaultConstructor;
  1450. if (Ctor->isCopyConstructor())
  1451. return Sema::CXXCopyConstructor;
  1452. if (Ctor->isMoveConstructor())
  1453. return Sema::CXXMoveConstructor;
  1454. } else if (isa<CXXDestructorDecl>(MD)) {
  1455. return Sema::CXXDestructor;
  1456. } else if (MD->isCopyAssignmentOperator()) {
  1457. return Sema::CXXCopyAssignment;
  1458. } else if (MD->isMoveAssignmentOperator()) {
  1459. return Sema::CXXMoveAssignment;
  1460. }
  1461. return Sema::CXXInvalid;
  1462. }
  1463. /// canRedefineFunction - checks if a function can be redefined. Currently,
  1464. /// only extern inline functions can be redefined, and even then only in
  1465. /// GNU89 mode.
  1466. static bool canRedefineFunction(const FunctionDecl *FD,
  1467. const LangOptions& LangOpts) {
  1468. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  1469. !LangOpts.CPlusPlus &&
  1470. FD->isInlineSpecified() &&
  1471. FD->getStorageClass() == SC_Extern);
  1472. }
  1473. /// MergeFunctionDecl - We just parsed a function 'New' from
  1474. /// declarator D which has the same name and scope as a previous
  1475. /// declaration 'Old'. Figure out how to resolve this situation,
  1476. /// merging decls or emitting diagnostics as appropriate.
  1477. ///
  1478. /// In C++, New and Old must be declarations that are not
  1479. /// overloaded. Use IsOverload to determine whether New and Old are
  1480. /// overloaded, and to select the Old declaration that New should be
  1481. /// merged with.
  1482. ///
  1483. /// Returns true if there was an error, false otherwise.
  1484. bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
  1485. // Verify the old decl was also a function.
  1486. FunctionDecl *Old = 0;
  1487. if (FunctionTemplateDecl *OldFunctionTemplate
  1488. = dyn_cast<FunctionTemplateDecl>(OldD))
  1489. Old = OldFunctionTemplate->getTemplatedDecl();
  1490. else
  1491. Old = dyn_cast<FunctionDecl>(OldD);
  1492. if (!Old) {
  1493. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  1494. Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  1495. Diag(Shadow->getTargetDecl()->getLocation(),
  1496. diag::note_using_decl_target);
  1497. Diag(Shadow->getUsingDecl()->getLocation(),
  1498. diag::note_using_decl) << 0;
  1499. return true;
  1500. }
  1501. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1502. << New->getDeclName();
  1503. Diag(OldD->getLocation(), diag::note_previous_definition);
  1504. return true;
  1505. }
  1506. // Determine whether the previous declaration was a definition,
  1507. // implicit declaration, or a declaration.
  1508. diag::kind PrevDiag;
  1509. if (Old->isThisDeclarationADefinition())
  1510. PrevDiag = diag::note_previous_definition;
  1511. else if (Old->isImplicit())
  1512. PrevDiag = diag::note_previous_implicit_declaration;
  1513. else
  1514. PrevDiag = diag::note_previous_declaration;
  1515. QualType OldQType = Context.getCanonicalType(Old->getType());
  1516. QualType NewQType = Context.getCanonicalType(New->getType());
  1517. // Don't complain about this if we're in GNU89 mode and the old function
  1518. // is an extern inline function.
  1519. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  1520. New->getStorageClass() == SC_Static &&
  1521. Old->getStorageClass() != SC_Static &&
  1522. !canRedefineFunction(Old, getLangOptions())) {
  1523. if (getLangOptions().MicrosoftExt) {
  1524. Diag(New->getLocation(), diag::warn_static_non_static) << New;
  1525. Diag(Old->getLocation(), PrevDiag);
  1526. } else {
  1527. Diag(New->getLocation(), diag::err_static_non_static) << New;
  1528. Diag(Old->getLocation(), PrevDiag);
  1529. return true;
  1530. }
  1531. }
  1532. // If a function is first declared with a calling convention, but is
  1533. // later declared or defined without one, the second decl assumes the
  1534. // calling convention of the first.
  1535. //
  1536. // For the new decl, we have to look at the NON-canonical type to tell the
  1537. // difference between a function that really doesn't have a calling
  1538. // convention and one that is declared cdecl. That's because in
  1539. // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
  1540. // because it is the default calling convention.
  1541. //
  1542. // Note also that we DO NOT return at this point, because we still have
  1543. // other tests to run.
  1544. const FunctionType *OldType = cast<FunctionType>(OldQType);
  1545. const FunctionType *NewType = New->getType()->getAs<FunctionType>();
  1546. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  1547. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  1548. bool RequiresAdjustment = false;
  1549. if (OldTypeInfo.getCC() != CC_Default &&
  1550. NewTypeInfo.getCC() == CC_Default) {
  1551. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  1552. RequiresAdjustment = true;
  1553. } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
  1554. NewTypeInfo.getCC())) {
  1555. // Calling conventions really aren't compatible, so complain.
  1556. Diag(New->getLocation(), diag::err_cconv_change)
  1557. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  1558. << (OldTypeInfo.getCC() == CC_Default)
  1559. << (OldTypeInfo.getCC() == CC_Default ? "" :
  1560. FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
  1561. Diag(Old->getLocation(), diag::note_previous_declaration);
  1562. return true;
  1563. }
  1564. // FIXME: diagnose the other way around?
  1565. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  1566. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  1567. RequiresAdjustment = true;
  1568. }
  1569. // Merge regparm attribute.
  1570. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  1571. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  1572. if (NewTypeInfo.getHasRegParm()) {
  1573. Diag(New->getLocation(), diag::err_regparm_mismatch)
  1574. << NewType->getRegParmType()
  1575. << OldType->getRegParmType();
  1576. Diag(Old->getLocation(), diag::note_previous_declaration);
  1577. return true;
  1578. }
  1579. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  1580. RequiresAdjustment = true;
  1581. }
  1582. // Merge ns_returns_retained attribute.
  1583. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  1584. if (NewTypeInfo.getProducesResult()) {
  1585. Diag(New->getLocation(), diag::err_returns_retained_mismatch);
  1586. Diag(Old->getLocation(), diag::note_previous_declaration);
  1587. return true;
  1588. }
  1589. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  1590. RequiresAdjustment = true;
  1591. }
  1592. if (RequiresAdjustment) {
  1593. NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
  1594. New->setType(QualType(NewType, 0));
  1595. NewQType = Context.getCanonicalType(New->getType());
  1596. }
  1597. if (getLangOptions().CPlusPlus) {
  1598. // (C++98 13.1p2):
  1599. // Certain function declarations cannot be overloaded:
  1600. // -- Function declarations that differ only in the return type
  1601. // cannot be overloaded.
  1602. QualType OldReturnType = OldType->getResultType();
  1603. QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
  1604. QualType ResQT;
  1605. if (OldReturnType != NewReturnType) {
  1606. if (NewReturnType->isObjCObjectPointerType()
  1607. && OldReturnType->isObjCObjectPointerType())
  1608. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  1609. if (ResQT.isNull()) {
  1610. if (New->isCXXClassMember() && New->isOutOfLine())
  1611. Diag(New->getLocation(),
  1612. diag::err_member_def_does_not_match_ret_type) << New;
  1613. else
  1614. Diag(New->getLocation(), diag::err_ovl_diff_return_type);
  1615. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1616. return true;
  1617. }
  1618. else
  1619. NewQType = ResQT;
  1620. }
  1621. const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
  1622. CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
  1623. if (OldMethod && NewMethod) {
  1624. // Preserve triviality.
  1625. NewMethod->setTrivial(OldMethod->isTrivial());
  1626. // MSVC allows explicit template specialization at class scope:
  1627. // 2 CXMethodDecls referring to the same function will be injected.
  1628. // We don't want a redeclartion error.
  1629. bool IsClassScopeExplicitSpecialization =
  1630. OldMethod->isFunctionTemplateSpecialization() &&
  1631. NewMethod->isFunctionTemplateSpecialization();
  1632. bool isFriend = NewMethod->getFriendObjectKind();
  1633. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  1634. !IsClassScopeExplicitSpecialization) {
  1635. // -- Member function declarations with the same name and the
  1636. // same parameter types cannot be overloaded if any of them
  1637. // is a static member function declaration.
  1638. if (OldMethod->isStatic() || NewMethod->isStatic()) {
  1639. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  1640. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1641. return true;
  1642. }
  1643. // C++ [class.mem]p1:
  1644. // [...] A member shall not be declared twice in the
  1645. // member-specification, except that a nested class or member
  1646. // class template can be declared and then later defined.
  1647. unsigned NewDiag;
  1648. if (isa<CXXConstructorDecl>(OldMethod))
  1649. NewDiag = diag::err_constructor_redeclared;
  1650. else if (isa<CXXDestructorDecl>(NewMethod))
  1651. NewDiag = diag::err_destructor_redeclared;
  1652. else if (isa<CXXConversionDecl>(NewMethod))
  1653. NewDiag = diag::err_conv_function_redeclared;
  1654. else
  1655. NewDiag = diag::err_member_redeclared;
  1656. Diag(New->getLocation(), NewDiag);
  1657. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1658. // Complain if this is an explicit declaration of a special
  1659. // member that was initially declared implicitly.
  1660. //
  1661. // As an exception, it's okay to befriend such methods in order
  1662. // to permit the implicit constructor/destructor/operator calls.
  1663. } else if (OldMethod->isImplicit()) {
  1664. if (isFriend) {
  1665. NewMethod->setImplicit();
  1666. } else {
  1667. Diag(NewMethod->getLocation(),
  1668. diag::err_definition_of_implicitly_declared_member)
  1669. << New << getSpecialMember(OldMethod);
  1670. return true;
  1671. }
  1672. } else if (OldMethod->isExplicitlyDefaulted()) {
  1673. Diag(NewMethod->getLocation(),
  1674. diag::err_definition_of_explicitly_defaulted_member)
  1675. << getSpecialMember(OldMethod);
  1676. return true;
  1677. }
  1678. }
  1679. // (C++98 8.3.5p3):
  1680. // All declarations for a function shall agree exactly in both the
  1681. // return type and the parameter-type-list.
  1682. // We also want to respect all the extended bits except noreturn.
  1683. // noreturn should now match unless the old type info didn't have it.
  1684. QualType OldQTypeForComparison = OldQType;
  1685. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  1686. assert(OldQType == QualType(OldType, 0));
  1687. const FunctionType *OldTypeForComparison
  1688. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  1689. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  1690. assert(OldQTypeForComparison.isCanonical());
  1691. }
  1692. if (OldQTypeForComparison == NewQType)
  1693. return MergeCompatibleFunctionDecls(New, Old);
  1694. // Fall through for conflicting redeclarations and redefinitions.
  1695. }
  1696. // C: Function types need to be compatible, not identical. This handles
  1697. // duplicate function decls like "void f(int); void f(enum X);" properly.
  1698. if (!getLangOptions().CPlusPlus &&
  1699. Context.typesAreCompatible(OldQType, NewQType)) {
  1700. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  1701. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  1702. const FunctionProtoType *OldProto = 0;
  1703. if (isa<FunctionNoProtoType>(NewFuncType) &&
  1704. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  1705. // The old declaration provided a function prototype, but the
  1706. // new declaration does not. Merge in the prototype.
  1707. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  1708. SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
  1709. OldProto->arg_type_end());
  1710. NewQType = Context.getFunctionType(NewFuncType->getResultType(),
  1711. ParamTypes.data(), ParamTypes.size(),
  1712. OldProto->getExtProtoInfo());
  1713. New->setType(NewQType);
  1714. New->setHasInheritedPrototype();
  1715. // Synthesize a parameter for each argument type.
  1716. SmallVector<ParmVarDecl*, 16> Params;
  1717. for (FunctionProtoType::arg_type_iterator
  1718. ParamType = OldProto->arg_type_begin(),
  1719. ParamEnd = OldProto->arg_type_end();
  1720. ParamType != ParamEnd; ++ParamType) {
  1721. ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
  1722. SourceLocation(),
  1723. SourceLocation(), 0,
  1724. *ParamType, /*TInfo=*/0,
  1725. SC_None, SC_None,
  1726. 0);
  1727. Param->setScopeInfo(0, Params.size());
  1728. Param->setImplicit();
  1729. Params.push_back(Param);
  1730. }
  1731. New->setParams(Params);
  1732. }
  1733. return MergeCompatibleFunctionDecls(New, Old);
  1734. }
  1735. // GNU C permits a K&R definition to follow a prototype declaration
  1736. // if the declared types of the parameters in the K&R definition
  1737. // match the types in the prototype declaration, even when the
  1738. // promoted types of the parameters from the K&R definition differ
  1739. // from the types in the prototype. GCC then keeps the types from
  1740. // the prototype.
  1741. //
  1742. // If a variadic prototype is followed by a non-variadic K&R definition,
  1743. // the K&R definition becomes variadic. This is sort of an edge case, but
  1744. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  1745. // C99 6.9.1p8.
  1746. if (!getLangOptions().CPlusPlus &&
  1747. Old->hasPrototype() && !New->hasPrototype() &&
  1748. New->getType()->getAs<FunctionProtoType>() &&
  1749. Old->getNumParams() == New->getNumParams()) {
  1750. SmallVector<QualType, 16> ArgTypes;
  1751. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  1752. const FunctionProtoType *OldProto
  1753. = Old->getType()->getAs<FunctionProtoType>();
  1754. const FunctionProtoType *NewProto
  1755. = New->getType()->getAs<FunctionProtoType>();
  1756. // Determine whether this is the GNU C extension.
  1757. QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
  1758. NewProto->getResultType());
  1759. bool LooseCompatible = !MergedReturn.isNull();
  1760. for (unsigned Idx = 0, End = Old->getNumParams();
  1761. LooseCompatible && Idx != End; ++Idx) {
  1762. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  1763. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  1764. if (Context.typesAreCompatible(OldParm->getType(),
  1765. NewProto->getArgType(Idx))) {
  1766. ArgTypes.push_back(NewParm->getType());
  1767. } else if (Context.typesAreCompatible(OldParm->getType(),
  1768. NewParm->getType(),
  1769. /*CompareUnqualified=*/true)) {
  1770. GNUCompatibleParamWarning Warn
  1771. = { OldParm, NewParm, NewProto->getArgType(Idx) };
  1772. Warnings.push_back(Warn);
  1773. ArgTypes.push_back(NewParm->getType());
  1774. } else
  1775. LooseCompatible = false;
  1776. }
  1777. if (LooseCompatible) {
  1778. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  1779. Diag(Warnings[Warn].NewParm->getLocation(),
  1780. diag::ext_param_promoted_not_compatible_with_prototype)
  1781. << Warnings[Warn].PromotedType
  1782. << Warnings[Warn].OldParm->getType();
  1783. if (Warnings[Warn].OldParm->getLocation().isValid())
  1784. Diag(Warnings[Warn].OldParm->getLocation(),
  1785. diag::note_previous_declaration);
  1786. }
  1787. New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
  1788. ArgTypes.size(),
  1789. OldProto->getExtProtoInfo()));
  1790. return MergeCompatibleFunctionDecls(New, Old);
  1791. }
  1792. // Fall through to diagnose conflicting types.
  1793. }
  1794. // A function that has already been declared has been redeclared or defined
  1795. // with a different type- show appropriate diagnostic
  1796. if (unsigned BuiltinID = Old->getBuiltinID()) {
  1797. // The user has declared a builtin function with an incompatible
  1798. // signature.
  1799. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  1800. // The function the user is redeclaring is a library-defined
  1801. // function like 'malloc' or 'printf'. Warn about the
  1802. // redeclaration, then pretend that we don't know about this
  1803. // library built-in.
  1804. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  1805. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  1806. << Old << Old->getType();
  1807. New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
  1808. Old->setInvalidDecl();
  1809. return false;
  1810. }
  1811. PrevDiag = diag::note_previous_builtin_declaration;
  1812. }
  1813. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  1814. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1815. return true;
  1816. }
  1817. /// \brief Completes the merge of two function declarations that are
  1818. /// known to be compatible.
  1819. ///
  1820. /// This routine handles the merging of attributes and other
  1821. /// properties of function declarations form the old declaration to
  1822. /// the new declaration, once we know that New is in fact a
  1823. /// redeclaration of Old.
  1824. ///
  1825. /// \returns false
  1826. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
  1827. // Merge the attributes
  1828. mergeDeclAttributes(New, Old);
  1829. // Merge the storage class.
  1830. if (Old->getStorageClass() != SC_Extern &&
  1831. Old->getStorageClass() != SC_None)
  1832. New->setStorageClass(Old->getStorageClass());
  1833. // Merge "pure" flag.
  1834. if (Old->isPure())
  1835. New->setPure();
  1836. // Merge attributes from the parameters. These can mismatch with K&R
  1837. // declarations.
  1838. if (New->getNumParams() == Old->getNumParams())
  1839. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
  1840. mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
  1841. Context);
  1842. if (getLangOptions().CPlusPlus)
  1843. return MergeCXXFunctionDecl(New, Old);
  1844. return false;
  1845. }
  1846. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  1847. ObjCMethodDecl *oldMethod) {
  1848. // We don't want to merge unavailable and deprecated attributes
  1849. // except from interface to implementation.
  1850. bool mergeDeprecation = isa<ObjCImplDecl>(newMethod->getDeclContext());
  1851. // Merge the attributes.
  1852. mergeDeclAttributes(newMethod, oldMethod, mergeDeprecation);
  1853. // Merge attributes from the parameters.
  1854. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin();
  1855. for (ObjCMethodDecl::param_iterator
  1856. ni = newMethod->param_begin(), ne = newMethod->param_end();
  1857. ni != ne; ++ni, ++oi)
  1858. mergeParamDeclAttributes(*ni, *oi, Context);
  1859. CheckObjCMethodOverride(newMethod, oldMethod, true);
  1860. }
  1861. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  1862. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  1863. /// emitting diagnostics as appropriate.
  1864. ///
  1865. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  1866. /// to here in AddInitializerToDecl and AddCXXDirectInitializerToDecl. We can't
  1867. /// check them before the initializer is attached.
  1868. ///
  1869. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
  1870. if (New->isInvalidDecl() || Old->isInvalidDecl())
  1871. return;
  1872. QualType MergedT;
  1873. if (getLangOptions().CPlusPlus) {
  1874. AutoType *AT = New->getType()->getContainedAutoType();
  1875. if (AT && !AT->isDeduced()) {
  1876. // We don't know what the new type is until the initializer is attached.
  1877. return;
  1878. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  1879. // These could still be something that needs exception specs checked.
  1880. return MergeVarDeclExceptionSpecs(New, Old);
  1881. }
  1882. // C++ [basic.link]p10:
  1883. // [...] the types specified by all declarations referring to a given
  1884. // object or function shall be identical, except that declarations for an
  1885. // array object can specify array types that differ by the presence or
  1886. // absence of a major array bound (8.3.4).
  1887. else if (Old->getType()->isIncompleteArrayType() &&
  1888. New->getType()->isArrayType()) {
  1889. CanQual<ArrayType> OldArray
  1890. = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
  1891. CanQual<ArrayType> NewArray
  1892. = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
  1893. if (OldArray->getElementType() == NewArray->getElementType())
  1894. MergedT = New->getType();
  1895. } else if (Old->getType()->isArrayType() &&
  1896. New->getType()->isIncompleteArrayType()) {
  1897. CanQual<ArrayType> OldArray
  1898. = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
  1899. CanQual<ArrayType> NewArray
  1900. = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
  1901. if (OldArray->getElementType() == NewArray->getElementType())
  1902. MergedT = Old->getType();
  1903. } else if (New->getType()->isObjCObjectPointerType()
  1904. && Old->getType()->isObjCObjectPointerType()) {
  1905. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  1906. Old->getType());
  1907. }
  1908. } else {
  1909. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  1910. }
  1911. if (MergedT.isNull()) {
  1912. Diag(New->getLocation(), diag::err_redefinition_different_type)
  1913. << New->getDeclName();
  1914. Diag(Old->getLocation(), diag::note_previous_definition);
  1915. return New->setInvalidDecl();
  1916. }
  1917. New->setType(MergedT);
  1918. }
  1919. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  1920. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  1921. /// situation, merging decls or emitting diagnostics as appropriate.
  1922. ///
  1923. /// Tentative definition rules (C99 6.9.2p2) are checked by
  1924. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  1925. /// definitions here, since the initializer hasn't been attached.
  1926. ///
  1927. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  1928. // If the new decl is already invalid, don't do any other checking.
  1929. if (New->isInvalidDecl())
  1930. return;
  1931. // Verify the old decl was also a variable.
  1932. VarDecl *Old = 0;
  1933. if (!Previous.isSingleResult() ||
  1934. !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
  1935. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1936. << New->getDeclName();
  1937. Diag(Previous.getRepresentativeDecl()->getLocation(),
  1938. diag::note_previous_definition);
  1939. return New->setInvalidDecl();
  1940. }
  1941. // C++ [class.mem]p1:
  1942. // A member shall not be declared twice in the member-specification [...]
  1943. //
  1944. // Here, we need only consider static data members.
  1945. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  1946. Diag(New->getLocation(), diag::err_duplicate_member)
  1947. << New->getIdentifier();
  1948. Diag(Old->getLocation(), diag::note_previous_declaration);
  1949. New->setInvalidDecl();
  1950. }
  1951. mergeDeclAttributes(New, Old);
  1952. // Warn if an already-declared variable is made a weak_import in a subsequent
  1953. // declaration
  1954. if (New->getAttr<WeakImportAttr>() &&
  1955. Old->getStorageClass() == SC_None &&
  1956. !Old->getAttr<WeakImportAttr>()) {
  1957. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  1958. Diag(Old->getLocation(), diag::note_previous_definition);
  1959. // Remove weak_import attribute on new declaration.
  1960. New->dropAttr<WeakImportAttr>();
  1961. }
  1962. // Merge the types.
  1963. MergeVarDeclTypes(New, Old);
  1964. if (New->isInvalidDecl())
  1965. return;
  1966. // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
  1967. if (New->getStorageClass() == SC_Static &&
  1968. (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
  1969. Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
  1970. Diag(Old->getLocation(), diag::note_previous_definition);
  1971. return New->setInvalidDecl();
  1972. }
  1973. // C99 6.2.2p4:
  1974. // For an identifier declared with the storage-class specifier
  1975. // extern in a scope in which a prior declaration of that
  1976. // identifier is visible,23) if the prior declaration specifies
  1977. // internal or external linkage, the linkage of the identifier at
  1978. // the later declaration is the same as the linkage specified at
  1979. // the prior declaration. If no prior declaration is visible, or
  1980. // if the prior declaration specifies no linkage, then the
  1981. // identifier has external linkage.
  1982. if (New->hasExternalStorage() && Old->hasLinkage())
  1983. /* Okay */;
  1984. else if (New->getStorageClass() != SC_Static &&
  1985. Old->getStorageClass() == SC_Static) {
  1986. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  1987. Diag(Old->getLocation(), diag::note_previous_definition);
  1988. return New->setInvalidDecl();
  1989. }
  1990. // Check if extern is followed by non-extern and vice-versa.
  1991. if (New->hasExternalStorage() &&
  1992. !Old->hasLinkage() && Old->isLocalVarDecl()) {
  1993. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  1994. Diag(Old->getLocation(), diag::note_previous_definition);
  1995. return New->setInvalidDecl();
  1996. }
  1997. if (Old->hasExternalStorage() &&
  1998. !New->hasLinkage() && New->isLocalVarDecl()) {
  1999. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  2000. Diag(Old->getLocation(), diag::note_previous_definition);
  2001. return New->setInvalidDecl();
  2002. }
  2003. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  2004. // FIXME: The test for external storage here seems wrong? We still
  2005. // need to check for mismatches.
  2006. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  2007. // Don't complain about out-of-line definitions of static members.
  2008. !(Old->getLexicalDeclContext()->isRecord() &&
  2009. !New->getLexicalDeclContext()->isRecord())) {
  2010. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  2011. Diag(Old->getLocation(), diag::note_previous_definition);
  2012. return New->setInvalidDecl();
  2013. }
  2014. if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
  2015. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  2016. Diag(Old->getLocation(), diag::note_previous_definition);
  2017. } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
  2018. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  2019. Diag(Old->getLocation(), diag::note_previous_definition);
  2020. }
  2021. // C++ doesn't have tentative definitions, so go right ahead and check here.
  2022. const VarDecl *Def;
  2023. if (getLangOptions().CPlusPlus &&
  2024. New->isThisDeclarationADefinition() == VarDecl::Definition &&
  2025. (Def = Old->getDefinition())) {
  2026. Diag(New->getLocation(), diag::err_redefinition)
  2027. << New->getDeclName();
  2028. Diag(Def->getLocation(), diag::note_previous_definition);
  2029. New->setInvalidDecl();
  2030. return;
  2031. }
  2032. // c99 6.2.2 P4.
  2033. // For an identifier declared with the storage-class specifier extern in a
  2034. // scope in which a prior declaration of that identifier is visible, if
  2035. // the prior declaration specifies internal or external linkage, the linkage
  2036. // of the identifier at the later declaration is the same as the linkage
  2037. // specified at the prior declaration.
  2038. // FIXME. revisit this code.
  2039. if (New->hasExternalStorage() &&
  2040. Old->getLinkage() == InternalLinkage &&
  2041. New->getDeclContext() == Old->getDeclContext())
  2042. New->setStorageClass(Old->getStorageClass());
  2043. // Keep a chain of previous declarations.
  2044. New->setPreviousDeclaration(Old);
  2045. // Inherit access appropriately.
  2046. New->setAccess(Old->getAccess());
  2047. }
  2048. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  2049. /// no declarator (e.g. "struct foo;") is parsed.
  2050. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  2051. DeclSpec &DS) {
  2052. return ParsedFreeStandingDeclSpec(S, AS, DS,
  2053. MultiTemplateParamsArg(*this, 0, 0));
  2054. }
  2055. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  2056. /// no declarator (e.g. "struct foo;") is parsed. It also accopts template
  2057. /// parameters to cope with template friend declarations.
  2058. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  2059. DeclSpec &DS,
  2060. MultiTemplateParamsArg TemplateParams) {
  2061. Decl *TagD = 0;
  2062. TagDecl *Tag = 0;
  2063. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  2064. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  2065. DS.getTypeSpecType() == DeclSpec::TST_union ||
  2066. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  2067. TagD = DS.getRepAsDecl();
  2068. if (!TagD) // We probably had an error
  2069. return 0;
  2070. // Note that the above type specs guarantee that the
  2071. // type rep is a Decl, whereas in many of the others
  2072. // it's a Type.
  2073. if (isa<TagDecl>(TagD))
  2074. Tag = cast<TagDecl>(TagD);
  2075. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  2076. Tag = CTD->getTemplatedDecl();
  2077. }
  2078. if (Tag)
  2079. Tag->setFreeStanding();
  2080. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  2081. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  2082. // or incomplete types shall not be restrict-qualified."
  2083. if (TypeQuals & DeclSpec::TQ_restrict)
  2084. Diag(DS.getRestrictSpecLoc(),
  2085. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  2086. << DS.getSourceRange();
  2087. }
  2088. if (DS.isConstexprSpecified()) {
  2089. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  2090. // and definitions of functions and variables.
  2091. if (Tag)
  2092. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  2093. << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
  2094. DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
  2095. DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3);
  2096. else
  2097. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  2098. // Don't emit warnings after this error.
  2099. return TagD;
  2100. }
  2101. if (DS.isFriendSpecified()) {
  2102. // If we're dealing with a decl but not a TagDecl, assume that
  2103. // whatever routines created it handled the friendship aspect.
  2104. if (TagD && !Tag)
  2105. return 0;
  2106. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  2107. }
  2108. // Track whether we warned about the fact that there aren't any
  2109. // declarators.
  2110. bool emittedWarning = false;
  2111. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  2112. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  2113. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  2114. if (getLangOptions().CPlusPlus ||
  2115. Record->getDeclContext()->isRecord())
  2116. return BuildAnonymousStructOrUnion(S, DS, AS, Record);
  2117. Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
  2118. << DS.getSourceRange();
  2119. emittedWarning = true;
  2120. }
  2121. }
  2122. // Check for Microsoft C extension: anonymous struct.
  2123. if (getLangOptions().MicrosoftExt && !getLangOptions().CPlusPlus &&
  2124. CurContext->isRecord() &&
  2125. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  2126. // Handle 2 kinds of anonymous struct:
  2127. // struct STRUCT;
  2128. // and
  2129. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  2130. RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
  2131. if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
  2132. (DS.getTypeSpecType() == DeclSpec::TST_typename &&
  2133. DS.getRepAsType().get()->isStructureType())) {
  2134. Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct)
  2135. << DS.getSourceRange();
  2136. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  2137. }
  2138. }
  2139. if (getLangOptions().CPlusPlus &&
  2140. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  2141. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  2142. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  2143. !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
  2144. Diag(Enum->getLocation(), diag::ext_no_declarators)
  2145. << DS.getSourceRange();
  2146. emittedWarning = true;
  2147. }
  2148. // Skip all the checks below if we have a type error.
  2149. if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
  2150. if (!DS.isMissingDeclaratorOk()) {
  2151. // Warn about typedefs of enums without names, since this is an
  2152. // extension in both Microsoft and GNU.
  2153. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
  2154. Tag && isa<EnumDecl>(Tag)) {
  2155. Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
  2156. << DS.getSourceRange();
  2157. return Tag;
  2158. }
  2159. Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
  2160. << DS.getSourceRange();
  2161. emittedWarning = true;
  2162. }
  2163. // We're going to complain about a bunch of spurious specifiers;
  2164. // only do this if we're declaring a tag, because otherwise we
  2165. // should be getting diag::ext_no_declarators.
  2166. if (emittedWarning || (TagD && TagD->isInvalidDecl()))
  2167. return TagD;
  2168. // Note that a linkage-specification sets a storage class, but
  2169. // 'extern "C" struct foo;' is actually valid and not theoretically
  2170. // useless.
  2171. if (DeclSpec::SCS scs = DS.getStorageClassSpec())
  2172. if (!DS.isExternInLinkageSpec())
  2173. Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
  2174. << DeclSpec::getSpecifierName(scs);
  2175. if (DS.isThreadSpecified())
  2176. Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
  2177. if (DS.getTypeQualifiers()) {
  2178. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  2179. Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
  2180. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  2181. Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
  2182. // Restrict is covered above.
  2183. }
  2184. if (DS.isInlineSpecified())
  2185. Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
  2186. if (DS.isVirtualSpecified())
  2187. Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
  2188. if (DS.isExplicitSpecified())
  2189. Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
  2190. if (DS.isModulePrivateSpecified() &&
  2191. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  2192. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  2193. << Tag->getTagKind()
  2194. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  2195. // Warn about ignored type attributes, for example:
  2196. // __attribute__((aligned)) struct A;
  2197. // Attributes should be placed after tag to apply to type declaration.
  2198. if (!DS.getAttributes().empty()) {
  2199. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  2200. if (TypeSpecType == DeclSpec::TST_class ||
  2201. TypeSpecType == DeclSpec::TST_struct ||
  2202. TypeSpecType == DeclSpec::TST_union ||
  2203. TypeSpecType == DeclSpec::TST_enum) {
  2204. AttributeList* attrs = DS.getAttributes().getList();
  2205. while (attrs) {
  2206. Diag(attrs->getScopeLoc(),
  2207. diag::warn_declspec_attribute_ignored)
  2208. << attrs->getName()
  2209. << (TypeSpecType == DeclSpec::TST_class ? 0 :
  2210. TypeSpecType == DeclSpec::TST_struct ? 1 :
  2211. TypeSpecType == DeclSpec::TST_union ? 2 : 3);
  2212. attrs = attrs->getNext();
  2213. }
  2214. }
  2215. }
  2216. return TagD;
  2217. }
  2218. /// We are trying to inject an anonymous member into the given scope;
  2219. /// check if there's an existing declaration that can't be overloaded.
  2220. ///
  2221. /// \return true if this is a forbidden redeclaration
  2222. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  2223. Scope *S,
  2224. DeclContext *Owner,
  2225. DeclarationName Name,
  2226. SourceLocation NameLoc,
  2227. unsigned diagnostic) {
  2228. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  2229. Sema::ForRedeclaration);
  2230. if (!SemaRef.LookupName(R, S)) return false;
  2231. if (R.getAsSingle<TagDecl>())
  2232. return false;
  2233. // Pick a representative declaration.
  2234. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  2235. assert(PrevDecl && "Expected a non-null Decl");
  2236. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  2237. return false;
  2238. SemaRef.Diag(NameLoc, diagnostic) << Name;
  2239. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  2240. return true;
  2241. }
  2242. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  2243. /// anonymous struct or union AnonRecord into the owning context Owner
  2244. /// and scope S. This routine will be invoked just after we realize
  2245. /// that an unnamed union or struct is actually an anonymous union or
  2246. /// struct, e.g.,
  2247. ///
  2248. /// @code
  2249. /// union {
  2250. /// int i;
  2251. /// float f;
  2252. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  2253. /// // f into the surrounding scope.x
  2254. /// @endcode
  2255. ///
  2256. /// This routine is recursive, injecting the names of nested anonymous
  2257. /// structs/unions into the owning context and scope as well.
  2258. static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
  2259. DeclContext *Owner,
  2260. RecordDecl *AnonRecord,
  2261. AccessSpecifier AS,
  2262. SmallVector<NamedDecl*, 2> &Chaining,
  2263. bool MSAnonStruct) {
  2264. unsigned diagKind
  2265. = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
  2266. : diag::err_anonymous_struct_member_redecl;
  2267. bool Invalid = false;
  2268. // Look every FieldDecl and IndirectFieldDecl with a name.
  2269. for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
  2270. DEnd = AnonRecord->decls_end();
  2271. D != DEnd; ++D) {
  2272. if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
  2273. cast<NamedDecl>(*D)->getDeclName()) {
  2274. ValueDecl *VD = cast<ValueDecl>(*D);
  2275. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  2276. VD->getLocation(), diagKind)) {
  2277. // C++ [class.union]p2:
  2278. // The names of the members of an anonymous union shall be
  2279. // distinct from the names of any other entity in the
  2280. // scope in which the anonymous union is declared.
  2281. Invalid = true;
  2282. } else {
  2283. // C++ [class.union]p2:
  2284. // For the purpose of name lookup, after the anonymous union
  2285. // definition, the members of the anonymous union are
  2286. // considered to have been defined in the scope in which the
  2287. // anonymous union is declared.
  2288. unsigned OldChainingSize = Chaining.size();
  2289. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  2290. for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
  2291. PE = IF->chain_end(); PI != PE; ++PI)
  2292. Chaining.push_back(*PI);
  2293. else
  2294. Chaining.push_back(VD);
  2295. assert(Chaining.size() >= 2);
  2296. NamedDecl **NamedChain =
  2297. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  2298. for (unsigned i = 0; i < Chaining.size(); i++)
  2299. NamedChain[i] = Chaining[i];
  2300. IndirectFieldDecl* IndirectField =
  2301. IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
  2302. VD->getIdentifier(), VD->getType(),
  2303. NamedChain, Chaining.size());
  2304. IndirectField->setAccess(AS);
  2305. IndirectField->setImplicit();
  2306. SemaRef.PushOnScopeChains(IndirectField, S);
  2307. // That includes picking up the appropriate access specifier.
  2308. if (AS != AS_none) IndirectField->setAccess(AS);
  2309. Chaining.resize(OldChainingSize);
  2310. }
  2311. }
  2312. }
  2313. return Invalid;
  2314. }
  2315. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  2316. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  2317. /// illegal input values are mapped to SC_None.
  2318. static StorageClass
  2319. StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
  2320. switch (StorageClassSpec) {
  2321. case DeclSpec::SCS_unspecified: return SC_None;
  2322. case DeclSpec::SCS_extern: return SC_Extern;
  2323. case DeclSpec::SCS_static: return SC_Static;
  2324. case DeclSpec::SCS_auto: return SC_Auto;
  2325. case DeclSpec::SCS_register: return SC_Register;
  2326. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  2327. // Illegal SCSs map to None: error reporting is up to the caller.
  2328. case DeclSpec::SCS_mutable: // Fall through.
  2329. case DeclSpec::SCS_typedef: return SC_None;
  2330. }
  2331. llvm_unreachable("unknown storage class specifier");
  2332. }
  2333. /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
  2334. /// a StorageClass. Any error reporting is up to the caller:
  2335. /// illegal input values are mapped to SC_None.
  2336. static StorageClass
  2337. StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
  2338. switch (StorageClassSpec) {
  2339. case DeclSpec::SCS_unspecified: return SC_None;
  2340. case DeclSpec::SCS_extern: return SC_Extern;
  2341. case DeclSpec::SCS_static: return SC_Static;
  2342. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  2343. // Illegal SCSs map to None: error reporting is up to the caller.
  2344. case DeclSpec::SCS_auto: // Fall through.
  2345. case DeclSpec::SCS_mutable: // Fall through.
  2346. case DeclSpec::SCS_register: // Fall through.
  2347. case DeclSpec::SCS_typedef: return SC_None;
  2348. }
  2349. llvm_unreachable("unknown storage class specifier");
  2350. }
  2351. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  2352. /// anonymous structure or union. Anonymous unions are a C++ feature
  2353. /// (C++ [class.union]) and a C11 feature; anonymous structures
  2354. /// are a C11 feature and GNU C++ extension.
  2355. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  2356. AccessSpecifier AS,
  2357. RecordDecl *Record) {
  2358. DeclContext *Owner = Record->getDeclContext();
  2359. // Diagnose whether this anonymous struct/union is an extension.
  2360. if (Record->isUnion() && !getLangOptions().CPlusPlus && !getLangOptions().C11)
  2361. Diag(Record->getLocation(), diag::ext_anonymous_union);
  2362. else if (!Record->isUnion() && getLangOptions().CPlusPlus)
  2363. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  2364. else if (!Record->isUnion() && !getLangOptions().C11)
  2365. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  2366. // C and C++ require different kinds of checks for anonymous
  2367. // structs/unions.
  2368. bool Invalid = false;
  2369. if (getLangOptions().CPlusPlus) {
  2370. const char* PrevSpec = 0;
  2371. unsigned DiagID;
  2372. if (Record->isUnion()) {
  2373. // C++ [class.union]p6:
  2374. // Anonymous unions declared in a named namespace or in the
  2375. // global namespace shall be declared static.
  2376. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  2377. (isa<TranslationUnitDecl>(Owner) ||
  2378. (isa<NamespaceDecl>(Owner) &&
  2379. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  2380. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  2381. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  2382. // Recover by adding 'static'.
  2383. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  2384. PrevSpec, DiagID);
  2385. }
  2386. // C++ [class.union]p6:
  2387. // A storage class is not allowed in a declaration of an
  2388. // anonymous union in a class scope.
  2389. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  2390. isa<RecordDecl>(Owner)) {
  2391. Diag(DS.getStorageClassSpecLoc(),
  2392. diag::err_anonymous_union_with_storage_spec)
  2393. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  2394. // Recover by removing the storage specifier.
  2395. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  2396. SourceLocation(),
  2397. PrevSpec, DiagID);
  2398. }
  2399. }
  2400. // Ignore const/volatile/restrict qualifiers.
  2401. if (DS.getTypeQualifiers()) {
  2402. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  2403. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  2404. << Record->isUnion() << 0
  2405. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  2406. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  2407. Diag(DS.getVolatileSpecLoc(),
  2408. diag::ext_anonymous_struct_union_qualified)
  2409. << Record->isUnion() << 1
  2410. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  2411. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  2412. Diag(DS.getRestrictSpecLoc(),
  2413. diag::ext_anonymous_struct_union_qualified)
  2414. << Record->isUnion() << 2
  2415. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  2416. DS.ClearTypeQualifiers();
  2417. }
  2418. // C++ [class.union]p2:
  2419. // The member-specification of an anonymous union shall only
  2420. // define non-static data members. [Note: nested types and
  2421. // functions cannot be declared within an anonymous union. ]
  2422. for (DeclContext::decl_iterator Mem = Record->decls_begin(),
  2423. MemEnd = Record->decls_end();
  2424. Mem != MemEnd; ++Mem) {
  2425. if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
  2426. // C++ [class.union]p3:
  2427. // An anonymous union shall not have private or protected
  2428. // members (clause 11).
  2429. assert(FD->getAccess() != AS_none);
  2430. if (FD->getAccess() != AS_public) {
  2431. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  2432. << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
  2433. Invalid = true;
  2434. }
  2435. // C++ [class.union]p1
  2436. // An object of a class with a non-trivial constructor, a non-trivial
  2437. // copy constructor, a non-trivial destructor, or a non-trivial copy
  2438. // assignment operator cannot be a member of a union, nor can an
  2439. // array of such objects.
  2440. if (CheckNontrivialField(FD))
  2441. Invalid = true;
  2442. } else if ((*Mem)->isImplicit()) {
  2443. // Any implicit members are fine.
  2444. } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
  2445. // This is a type that showed up in an
  2446. // elaborated-type-specifier inside the anonymous struct or
  2447. // union, but which actually declares a type outside of the
  2448. // anonymous struct or union. It's okay.
  2449. } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
  2450. if (!MemRecord->isAnonymousStructOrUnion() &&
  2451. MemRecord->getDeclName()) {
  2452. // Visual C++ allows type definition in anonymous struct or union.
  2453. if (getLangOptions().MicrosoftExt)
  2454. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  2455. << (int)Record->isUnion();
  2456. else {
  2457. // This is a nested type declaration.
  2458. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  2459. << (int)Record->isUnion();
  2460. Invalid = true;
  2461. }
  2462. }
  2463. } else if (isa<AccessSpecDecl>(*Mem)) {
  2464. // Any access specifier is fine.
  2465. } else {
  2466. // We have something that isn't a non-static data
  2467. // member. Complain about it.
  2468. unsigned DK = diag::err_anonymous_record_bad_member;
  2469. if (isa<TypeDecl>(*Mem))
  2470. DK = diag::err_anonymous_record_with_type;
  2471. else if (isa<FunctionDecl>(*Mem))
  2472. DK = diag::err_anonymous_record_with_function;
  2473. else if (isa<VarDecl>(*Mem))
  2474. DK = diag::err_anonymous_record_with_static;
  2475. // Visual C++ allows type definition in anonymous struct or union.
  2476. if (getLangOptions().MicrosoftExt &&
  2477. DK == diag::err_anonymous_record_with_type)
  2478. Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
  2479. << (int)Record->isUnion();
  2480. else {
  2481. Diag((*Mem)->getLocation(), DK)
  2482. << (int)Record->isUnion();
  2483. Invalid = true;
  2484. }
  2485. }
  2486. }
  2487. }
  2488. if (!Record->isUnion() && !Owner->isRecord()) {
  2489. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  2490. << (int)getLangOptions().CPlusPlus;
  2491. Invalid = true;
  2492. }
  2493. // Mock up a declarator.
  2494. Declarator Dc(DS, Declarator::MemberContext);
  2495. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  2496. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  2497. // Create a declaration for this anonymous struct/union.
  2498. NamedDecl *Anon = 0;
  2499. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  2500. Anon = FieldDecl::Create(Context, OwningClass,
  2501. DS.getSourceRange().getBegin(),
  2502. Record->getLocation(),
  2503. /*IdentifierInfo=*/0,
  2504. Context.getTypeDeclType(Record),
  2505. TInfo,
  2506. /*BitWidth=*/0, /*Mutable=*/false,
  2507. /*HasInit=*/false);
  2508. Anon->setAccess(AS);
  2509. if (getLangOptions().CPlusPlus)
  2510. FieldCollector->Add(cast<FieldDecl>(Anon));
  2511. } else {
  2512. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  2513. assert(SCSpec != DeclSpec::SCS_typedef &&
  2514. "Parser allowed 'typedef' as storage class VarDecl.");
  2515. VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
  2516. if (SCSpec == DeclSpec::SCS_mutable) {
  2517. // mutable can only appear on non-static class members, so it's always
  2518. // an error here
  2519. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  2520. Invalid = true;
  2521. SC = SC_None;
  2522. }
  2523. SCSpec = DS.getStorageClassSpecAsWritten();
  2524. VarDecl::StorageClass SCAsWritten
  2525. = StorageClassSpecToVarDeclStorageClass(SCSpec);
  2526. Anon = VarDecl::Create(Context, Owner,
  2527. DS.getSourceRange().getBegin(),
  2528. Record->getLocation(), /*IdentifierInfo=*/0,
  2529. Context.getTypeDeclType(Record),
  2530. TInfo, SC, SCAsWritten);
  2531. // Default-initialize the implicit variable. This initialization will be
  2532. // trivial in almost all cases, except if a union member has an in-class
  2533. // initializer:
  2534. // union { int n = 0; };
  2535. ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
  2536. }
  2537. Anon->setImplicit();
  2538. // Add the anonymous struct/union object to the current
  2539. // context. We'll be referencing this object when we refer to one of
  2540. // its members.
  2541. Owner->addDecl(Anon);
  2542. // Inject the members of the anonymous struct/union into the owning
  2543. // context and into the identifier resolver chain for name lookup
  2544. // purposes.
  2545. SmallVector<NamedDecl*, 2> Chain;
  2546. Chain.push_back(Anon);
  2547. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
  2548. Chain, false))
  2549. Invalid = true;
  2550. // Mark this as an anonymous struct/union type. Note that we do not
  2551. // do this until after we have already checked and injected the
  2552. // members of this anonymous struct/union type, because otherwise
  2553. // the members could be injected twice: once by DeclContext when it
  2554. // builds its lookup table, and once by
  2555. // InjectAnonymousStructOrUnionMembers.
  2556. Record->setAnonymousStructOrUnion(true);
  2557. if (Invalid)
  2558. Anon->setInvalidDecl();
  2559. return Anon;
  2560. }
  2561. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  2562. /// Microsoft C anonymous structure.
  2563. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  2564. /// Example:
  2565. ///
  2566. /// struct A { int a; };
  2567. /// struct B { struct A; int b; };
  2568. ///
  2569. /// void foo() {
  2570. /// B var;
  2571. /// var.a = 3;
  2572. /// }
  2573. ///
  2574. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  2575. RecordDecl *Record) {
  2576. // If there is no Record, get the record via the typedef.
  2577. if (!Record)
  2578. Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
  2579. // Mock up a declarator.
  2580. Declarator Dc(DS, Declarator::TypeNameContext);
  2581. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  2582. assert(TInfo && "couldn't build declarator info for anonymous struct");
  2583. // Create a declaration for this anonymous struct.
  2584. NamedDecl* Anon = FieldDecl::Create(Context,
  2585. cast<RecordDecl>(CurContext),
  2586. DS.getSourceRange().getBegin(),
  2587. DS.getSourceRange().getBegin(),
  2588. /*IdentifierInfo=*/0,
  2589. Context.getTypeDeclType(Record),
  2590. TInfo,
  2591. /*BitWidth=*/0, /*Mutable=*/false,
  2592. /*HasInit=*/false);
  2593. Anon->setImplicit();
  2594. // Add the anonymous struct object to the current context.
  2595. CurContext->addDecl(Anon);
  2596. // Inject the members of the anonymous struct into the current
  2597. // context and into the identifier resolver chain for name lookup
  2598. // purposes.
  2599. SmallVector<NamedDecl*, 2> Chain;
  2600. Chain.push_back(Anon);
  2601. RecordDecl *RecordDef = Record->getDefinition();
  2602. if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
  2603. RecordDef, AS_none,
  2604. Chain, true))
  2605. Anon->setInvalidDecl();
  2606. return Anon;
  2607. }
  2608. /// GetNameForDeclarator - Determine the full declaration name for the
  2609. /// given Declarator.
  2610. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  2611. return GetNameFromUnqualifiedId(D.getName());
  2612. }
  2613. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  2614. DeclarationNameInfo
  2615. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  2616. DeclarationNameInfo NameInfo;
  2617. NameInfo.setLoc(Name.StartLocation);
  2618. switch (Name.getKind()) {
  2619. case UnqualifiedId::IK_ImplicitSelfParam:
  2620. case UnqualifiedId::IK_Identifier:
  2621. NameInfo.setName(Name.Identifier);
  2622. NameInfo.setLoc(Name.StartLocation);
  2623. return NameInfo;
  2624. case UnqualifiedId::IK_OperatorFunctionId:
  2625. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  2626. Name.OperatorFunctionId.Operator));
  2627. NameInfo.setLoc(Name.StartLocation);
  2628. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  2629. = Name.OperatorFunctionId.SymbolLocations[0];
  2630. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  2631. = Name.EndLocation.getRawEncoding();
  2632. return NameInfo;
  2633. case UnqualifiedId::IK_LiteralOperatorId:
  2634. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  2635. Name.Identifier));
  2636. NameInfo.setLoc(Name.StartLocation);
  2637. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  2638. return NameInfo;
  2639. case UnqualifiedId::IK_ConversionFunctionId: {
  2640. TypeSourceInfo *TInfo;
  2641. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  2642. if (Ty.isNull())
  2643. return DeclarationNameInfo();
  2644. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  2645. Context.getCanonicalType(Ty)));
  2646. NameInfo.setLoc(Name.StartLocation);
  2647. NameInfo.setNamedTypeInfo(TInfo);
  2648. return NameInfo;
  2649. }
  2650. case UnqualifiedId::IK_ConstructorName: {
  2651. TypeSourceInfo *TInfo;
  2652. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  2653. if (Ty.isNull())
  2654. return DeclarationNameInfo();
  2655. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  2656. Context.getCanonicalType(Ty)));
  2657. NameInfo.setLoc(Name.StartLocation);
  2658. NameInfo.setNamedTypeInfo(TInfo);
  2659. return NameInfo;
  2660. }
  2661. case UnqualifiedId::IK_ConstructorTemplateId: {
  2662. // In well-formed code, we can only have a constructor
  2663. // template-id that refers to the current context, so go there
  2664. // to find the actual type being constructed.
  2665. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  2666. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  2667. return DeclarationNameInfo();
  2668. // Determine the type of the class being constructed.
  2669. QualType CurClassType = Context.getTypeDeclType(CurClass);
  2670. // FIXME: Check two things: that the template-id names the same type as
  2671. // CurClassType, and that the template-id does not occur when the name
  2672. // was qualified.
  2673. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  2674. Context.getCanonicalType(CurClassType)));
  2675. NameInfo.setLoc(Name.StartLocation);
  2676. // FIXME: should we retrieve TypeSourceInfo?
  2677. NameInfo.setNamedTypeInfo(0);
  2678. return NameInfo;
  2679. }
  2680. case UnqualifiedId::IK_DestructorName: {
  2681. TypeSourceInfo *TInfo;
  2682. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  2683. if (Ty.isNull())
  2684. return DeclarationNameInfo();
  2685. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  2686. Context.getCanonicalType(Ty)));
  2687. NameInfo.setLoc(Name.StartLocation);
  2688. NameInfo.setNamedTypeInfo(TInfo);
  2689. return NameInfo;
  2690. }
  2691. case UnqualifiedId::IK_TemplateId: {
  2692. TemplateName TName = Name.TemplateId->Template.get();
  2693. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  2694. return Context.getNameForTemplate(TName, TNameLoc);
  2695. }
  2696. } // switch (Name.getKind())
  2697. llvm_unreachable("Unknown name kind");
  2698. }
  2699. static QualType getCoreType(QualType Ty) {
  2700. do {
  2701. if (Ty->isPointerType() || Ty->isReferenceType())
  2702. Ty = Ty->getPointeeType();
  2703. else if (Ty->isArrayType())
  2704. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  2705. else
  2706. return Ty.withoutLocalFastQualifiers();
  2707. } while (true);
  2708. }
  2709. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  2710. /// and Definition have "nearly" matching parameters. This heuristic is
  2711. /// used to improve diagnostics in the case where an out-of-line function
  2712. /// definition doesn't match any declaration within the class or namespace.
  2713. /// Also sets Params to the list of indices to the parameters that differ
  2714. /// between the declaration and the definition. If hasSimilarParameters
  2715. /// returns true and Params is empty, then all of the parameters match.
  2716. static bool hasSimilarParameters(ASTContext &Context,
  2717. FunctionDecl *Declaration,
  2718. FunctionDecl *Definition,
  2719. llvm::SmallVectorImpl<unsigned> &Params) {
  2720. Params.clear();
  2721. if (Declaration->param_size() != Definition->param_size())
  2722. return false;
  2723. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  2724. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  2725. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  2726. // The parameter types are identical
  2727. if (Context.hasSameType(DefParamTy, DeclParamTy))
  2728. continue;
  2729. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  2730. QualType DefParamBaseTy = getCoreType(DefParamTy);
  2731. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  2732. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  2733. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  2734. (DeclTyName && DeclTyName == DefTyName))
  2735. Params.push_back(Idx);
  2736. else // The two parameters aren't even close
  2737. return false;
  2738. }
  2739. return true;
  2740. }
  2741. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  2742. /// declarator needs to be rebuilt in the current instantiation.
  2743. /// Any bits of declarator which appear before the name are valid for
  2744. /// consideration here. That's specifically the type in the decl spec
  2745. /// and the base type in any member-pointer chunks.
  2746. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  2747. DeclarationName Name) {
  2748. // The types we specifically need to rebuild are:
  2749. // - typenames, typeofs, and decltypes
  2750. // - types which will become injected class names
  2751. // Of course, we also need to rebuild any type referencing such a
  2752. // type. It's safest to just say "dependent", but we call out a
  2753. // few cases here.
  2754. DeclSpec &DS = D.getMutableDeclSpec();
  2755. switch (DS.getTypeSpecType()) {
  2756. case DeclSpec::TST_typename:
  2757. case DeclSpec::TST_typeofType:
  2758. case DeclSpec::TST_decltype:
  2759. case DeclSpec::TST_underlyingType:
  2760. case DeclSpec::TST_atomic: {
  2761. // Grab the type from the parser.
  2762. TypeSourceInfo *TSI = 0;
  2763. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  2764. if (T.isNull() || !T->isDependentType()) break;
  2765. // Make sure there's a type source info. This isn't really much
  2766. // of a waste; most dependent types should have type source info
  2767. // attached already.
  2768. if (!TSI)
  2769. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  2770. // Rebuild the type in the current instantiation.
  2771. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  2772. if (!TSI) return true;
  2773. // Store the new type back in the decl spec.
  2774. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  2775. DS.UpdateTypeRep(LocType);
  2776. break;
  2777. }
  2778. case DeclSpec::TST_typeofExpr: {
  2779. Expr *E = DS.getRepAsExpr();
  2780. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  2781. if (Result.isInvalid()) return true;
  2782. DS.UpdateExprRep(Result.get());
  2783. break;
  2784. }
  2785. default:
  2786. // Nothing to do for these decl specs.
  2787. break;
  2788. }
  2789. // It doesn't matter what order we do this in.
  2790. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  2791. DeclaratorChunk &Chunk = D.getTypeObject(I);
  2792. // The only type information in the declarator which can come
  2793. // before the declaration name is the base type of a member
  2794. // pointer.
  2795. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  2796. continue;
  2797. // Rebuild the scope specifier in-place.
  2798. CXXScopeSpec &SS = Chunk.Mem.Scope();
  2799. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  2800. return true;
  2801. }
  2802. return false;
  2803. }
  2804. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  2805. D.setFunctionDefinitionKind(FDK_Declaration);
  2806. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg(*this));
  2807. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  2808. Dcl->getDeclContext()->isFileContext())
  2809. Dcl->setTopLevelDeclInObjCContainer();
  2810. return Dcl;
  2811. }
  2812. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  2813. /// If T is the name of a class, then each of the following shall have a
  2814. /// name different from T:
  2815. /// - every static data member of class T;
  2816. /// - every member function of class T
  2817. /// - every member of class T that is itself a type;
  2818. /// \returns true if the declaration name violates these rules.
  2819. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  2820. DeclarationNameInfo NameInfo) {
  2821. DeclarationName Name = NameInfo.getName();
  2822. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  2823. if (Record->getIdentifier() && Record->getDeclName() == Name) {
  2824. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  2825. return true;
  2826. }
  2827. return false;
  2828. }
  2829. Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  2830. MultiTemplateParamsArg TemplateParamLists) {
  2831. // TODO: consider using NameInfo for diagnostic.
  2832. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  2833. DeclarationName Name = NameInfo.getName();
  2834. // All of these full declarators require an identifier. If it doesn't have
  2835. // one, the ParsedFreeStandingDeclSpec action should be used.
  2836. if (!Name) {
  2837. if (!D.isInvalidType()) // Reject this if we think it is valid.
  2838. Diag(D.getDeclSpec().getSourceRange().getBegin(),
  2839. diag::err_declarator_need_ident)
  2840. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  2841. return 0;
  2842. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  2843. return 0;
  2844. // The scope passed in may not be a decl scope. Zip up the scope tree until
  2845. // we find one that is.
  2846. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  2847. (S->getFlags() & Scope::TemplateParamScope) != 0)
  2848. S = S->getParent();
  2849. DeclContext *DC = CurContext;
  2850. if (D.getCXXScopeSpec().isInvalid())
  2851. D.setInvalidType();
  2852. else if (D.getCXXScopeSpec().isSet()) {
  2853. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  2854. UPPC_DeclarationQualifier))
  2855. return 0;
  2856. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  2857. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  2858. if (!DC) {
  2859. // If we could not compute the declaration context, it's because the
  2860. // declaration context is dependent but does not refer to a class,
  2861. // class template, or class template partial specialization. Complain
  2862. // and return early, to avoid the coming semantic disaster.
  2863. Diag(D.getIdentifierLoc(),
  2864. diag::err_template_qualified_declarator_no_match)
  2865. << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
  2866. << D.getCXXScopeSpec().getRange();
  2867. return 0;
  2868. }
  2869. bool IsDependentContext = DC->isDependentContext();
  2870. if (!IsDependentContext &&
  2871. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  2872. return 0;
  2873. if (isa<CXXRecordDecl>(DC)) {
  2874. if (!cast<CXXRecordDecl>(DC)->hasDefinition()) {
  2875. Diag(D.getIdentifierLoc(),
  2876. diag::err_member_def_undefined_record)
  2877. << Name << DC << D.getCXXScopeSpec().getRange();
  2878. D.setInvalidType();
  2879. } else if (isa<CXXRecordDecl>(CurContext) &&
  2880. !D.getDeclSpec().isFriendSpecified()) {
  2881. // The user provided a superfluous scope specifier inside a class
  2882. // definition:
  2883. //
  2884. // class X {
  2885. // void X::f();
  2886. // };
  2887. if (CurContext->Equals(DC)) {
  2888. Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
  2889. << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange());
  2890. } else {
  2891. Diag(D.getIdentifierLoc(), diag::err_member_qualification)
  2892. << Name << D.getCXXScopeSpec().getRange();
  2893. // C++ constructors and destructors with incorrect scopes can break
  2894. // our AST invariants by having the wrong underlying types. If
  2895. // that's the case, then drop this declaration entirely.
  2896. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  2897. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  2898. !Context.hasSameType(Name.getCXXNameType(),
  2899. Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))))
  2900. return 0;
  2901. }
  2902. // Pretend that this qualifier was not here.
  2903. D.getCXXScopeSpec().clear();
  2904. }
  2905. }
  2906. // Check whether we need to rebuild the type of the given
  2907. // declaration in the current instantiation.
  2908. if (EnteringContext && IsDependentContext &&
  2909. TemplateParamLists.size() != 0) {
  2910. ContextRAII SavedContext(*this, DC);
  2911. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  2912. D.setInvalidType();
  2913. }
  2914. }
  2915. if (DiagnoseClassNameShadow(DC, NameInfo))
  2916. // If this is a typedef, we'll end up spewing multiple diagnostics.
  2917. // Just return early; it's safer.
  2918. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  2919. return 0;
  2920. NamedDecl *New;
  2921. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  2922. QualType R = TInfo->getType();
  2923. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  2924. UPPC_DeclarationType))
  2925. D.setInvalidType();
  2926. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  2927. ForRedeclaration);
  2928. // See if this is a redefinition of a variable in the same scope.
  2929. if (!D.getCXXScopeSpec().isSet()) {
  2930. bool IsLinkageLookup = false;
  2931. // If the declaration we're planning to build will be a function
  2932. // or object with linkage, then look for another declaration with
  2933. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  2934. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  2935. /* Do nothing*/;
  2936. else if (R->isFunctionType()) {
  2937. if (CurContext->isFunctionOrMethod() ||
  2938. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  2939. IsLinkageLookup = true;
  2940. } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
  2941. IsLinkageLookup = true;
  2942. else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  2943. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  2944. IsLinkageLookup = true;
  2945. if (IsLinkageLookup)
  2946. Previous.clear(LookupRedeclarationWithLinkage);
  2947. LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
  2948. } else { // Something like "int foo::x;"
  2949. LookupQualifiedName(Previous, DC);
  2950. // Don't consider using declarations as previous declarations for
  2951. // out-of-line members.
  2952. RemoveUsingDecls(Previous);
  2953. // C++ 7.3.1.2p2:
  2954. // Members (including explicit specializations of templates) of a named
  2955. // namespace can also be defined outside that namespace by explicit
  2956. // qualification of the name being defined, provided that the entity being
  2957. // defined was already declared in the namespace and the definition appears
  2958. // after the point of declaration in a namespace that encloses the
  2959. // declarations namespace.
  2960. //
  2961. // Note that we only check the context at this point. We don't yet
  2962. // have enough information to make sure that PrevDecl is actually
  2963. // the declaration we want to match. For example, given:
  2964. //
  2965. // class X {
  2966. // void f();
  2967. // void f(float);
  2968. // };
  2969. //
  2970. // void X::f(int) { } // ill-formed
  2971. //
  2972. // In this case, PrevDecl will point to the overload set
  2973. // containing the two f's declared in X, but neither of them
  2974. // matches.
  2975. // First check whether we named the global scope.
  2976. if (isa<TranslationUnitDecl>(DC)) {
  2977. Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
  2978. << Name << D.getCXXScopeSpec().getRange();
  2979. } else {
  2980. DeclContext *Cur = CurContext;
  2981. while (isa<LinkageSpecDecl>(Cur))
  2982. Cur = Cur->getParent();
  2983. if (!Cur->Encloses(DC)) {
  2984. // The qualifying scope doesn't enclose the original declaration.
  2985. // Emit diagnostic based on current scope.
  2986. SourceLocation L = D.getIdentifierLoc();
  2987. SourceRange R = D.getCXXScopeSpec().getRange();
  2988. if (isa<FunctionDecl>(Cur))
  2989. Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
  2990. else
  2991. Diag(L, diag::err_invalid_declarator_scope)
  2992. << Name << cast<NamedDecl>(DC) << R;
  2993. D.setInvalidType();
  2994. }
  2995. // C++11 8.3p1:
  2996. // ... "The nested-name-specifier of the qualified declarator-id shall
  2997. // not begin with a decltype-specifer"
  2998. NestedNameSpecifierLoc SpecLoc =
  2999. D.getCXXScopeSpec().getWithLocInContext(Context);
  3000. assert(SpecLoc && "A non-empty CXXScopeSpec should have a non-empty "
  3001. "NestedNameSpecifierLoc");
  3002. while (SpecLoc.getPrefix())
  3003. SpecLoc = SpecLoc.getPrefix();
  3004. if (dyn_cast_or_null<DecltypeType>(
  3005. SpecLoc.getNestedNameSpecifier()->getAsType()))
  3006. Diag(SpecLoc.getBeginLoc(), diag::err_decltype_in_declarator)
  3007. << SpecLoc.getTypeLoc().getSourceRange();
  3008. }
  3009. }
  3010. if (Previous.isSingleResult() &&
  3011. Previous.getFoundDecl()->isTemplateParameter()) {
  3012. // Maybe we will complain about the shadowed template parameter.
  3013. if (!D.isInvalidType())
  3014. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  3015. Previous.getFoundDecl());
  3016. // Just pretend that we didn't see the previous declaration.
  3017. Previous.clear();
  3018. }
  3019. // In C++, the previous declaration we find might be a tag type
  3020. // (class or enum). In this case, the new declaration will hide the
  3021. // tag type. Note that this does does not apply if we're declaring a
  3022. // typedef (C++ [dcl.typedef]p4).
  3023. if (Previous.isSingleTagDecl() &&
  3024. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
  3025. Previous.clear();
  3026. bool AddToScope = true;
  3027. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  3028. if (TemplateParamLists.size()) {
  3029. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  3030. return 0;
  3031. }
  3032. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  3033. } else if (R->isFunctionType()) {
  3034. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  3035. move(TemplateParamLists),
  3036. AddToScope);
  3037. } else {
  3038. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
  3039. move(TemplateParamLists));
  3040. }
  3041. if (New == 0)
  3042. return 0;
  3043. // If this has an identifier and is not an invalid redeclaration or
  3044. // function template specialization, add it to the scope stack.
  3045. if (New->getDeclName() && AddToScope &&
  3046. !(D.isRedeclaration() && New->isInvalidDecl()))
  3047. PushOnScopeChains(New, S);
  3048. return New;
  3049. }
  3050. /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
  3051. /// types into constant array types in certain situations which would otherwise
  3052. /// be errors (for GCC compatibility).
  3053. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  3054. ASTContext &Context,
  3055. bool &SizeIsNegative,
  3056. llvm::APSInt &Oversized) {
  3057. // This method tries to turn a variable array into a constant
  3058. // array even when the size isn't an ICE. This is necessary
  3059. // for compatibility with code that depends on gcc's buggy
  3060. // constant expression folding, like struct {char x[(int)(char*)2];}
  3061. SizeIsNegative = false;
  3062. Oversized = 0;
  3063. if (T->isDependentType())
  3064. return QualType();
  3065. QualifierCollector Qs;
  3066. const Type *Ty = Qs.strip(T);
  3067. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  3068. QualType Pointee = PTy->getPointeeType();
  3069. QualType FixedType =
  3070. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  3071. Oversized);
  3072. if (FixedType.isNull()) return FixedType;
  3073. FixedType = Context.getPointerType(FixedType);
  3074. return Qs.apply(Context, FixedType);
  3075. }
  3076. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  3077. QualType Inner = PTy->getInnerType();
  3078. QualType FixedType =
  3079. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  3080. Oversized);
  3081. if (FixedType.isNull()) return FixedType;
  3082. FixedType = Context.getParenType(FixedType);
  3083. return Qs.apply(Context, FixedType);
  3084. }
  3085. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  3086. if (!VLATy)
  3087. return QualType();
  3088. // FIXME: We should probably handle this case
  3089. if (VLATy->getElementType()->isVariablyModifiedType())
  3090. return QualType();
  3091. llvm::APSInt Res;
  3092. if (!VLATy->getSizeExpr() ||
  3093. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  3094. return QualType();
  3095. // Check whether the array size is negative.
  3096. if (Res.isSigned() && Res.isNegative()) {
  3097. SizeIsNegative = true;
  3098. return QualType();
  3099. }
  3100. // Check whether the array is too large to be addressed.
  3101. unsigned ActiveSizeBits
  3102. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  3103. Res);
  3104. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  3105. Oversized = Res;
  3106. return QualType();
  3107. }
  3108. return Context.getConstantArrayType(VLATy->getElementType(),
  3109. Res, ArrayType::Normal, 0);
  3110. }
  3111. /// \brief Register the given locally-scoped external C declaration so
  3112. /// that it can be found later for redeclarations
  3113. void
  3114. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
  3115. const LookupResult &Previous,
  3116. Scope *S) {
  3117. assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
  3118. "Decl is not a locally-scoped decl!");
  3119. // Note that we have a locally-scoped external with this name.
  3120. LocallyScopedExternalDecls[ND->getDeclName()] = ND;
  3121. if (!Previous.isSingleResult())
  3122. return;
  3123. NamedDecl *PrevDecl = Previous.getFoundDecl();
  3124. // If there was a previous declaration of this variable, it may be
  3125. // in our identifier chain. Update the identifier chain with the new
  3126. // declaration.
  3127. if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
  3128. // The previous declaration was found on the identifer resolver
  3129. // chain, so remove it from its scope.
  3130. if (S->isDeclScope(PrevDecl)) {
  3131. // Special case for redeclarations in the SAME scope.
  3132. // Because this declaration is going to be added to the identifier chain
  3133. // later, we should temporarily take it OFF the chain.
  3134. IdResolver.RemoveDecl(ND);
  3135. } else {
  3136. // Find the scope for the original declaration.
  3137. while (S && !S->isDeclScope(PrevDecl))
  3138. S = S->getParent();
  3139. }
  3140. if (S)
  3141. S->RemoveDecl(PrevDecl);
  3142. }
  3143. }
  3144. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
  3145. Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
  3146. if (ExternalSource) {
  3147. // Load locally-scoped external decls from the external source.
  3148. SmallVector<NamedDecl *, 4> Decls;
  3149. ExternalSource->ReadLocallyScopedExternalDecls(Decls);
  3150. for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
  3151. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  3152. = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
  3153. if (Pos == LocallyScopedExternalDecls.end())
  3154. LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
  3155. }
  3156. }
  3157. return LocallyScopedExternalDecls.find(Name);
  3158. }
  3159. /// \brief Diagnose function specifiers on a declaration of an identifier that
  3160. /// does not identify a function.
  3161. void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
  3162. // FIXME: We should probably indicate the identifier in question to avoid
  3163. // confusion for constructs like "inline int a(), b;"
  3164. if (D.getDeclSpec().isInlineSpecified())
  3165. Diag(D.getDeclSpec().getInlineSpecLoc(),
  3166. diag::err_inline_non_function);
  3167. if (D.getDeclSpec().isVirtualSpecified())
  3168. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  3169. diag::err_virtual_non_function);
  3170. if (D.getDeclSpec().isExplicitSpecified())
  3171. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  3172. diag::err_explicit_non_function);
  3173. }
  3174. NamedDecl*
  3175. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  3176. TypeSourceInfo *TInfo, LookupResult &Previous) {
  3177. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  3178. if (D.getCXXScopeSpec().isSet()) {
  3179. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  3180. << D.getCXXScopeSpec().getRange();
  3181. D.setInvalidType();
  3182. // Pretend we didn't see the scope specifier.
  3183. DC = CurContext;
  3184. Previous.clear();
  3185. }
  3186. if (getLangOptions().CPlusPlus) {
  3187. // Check that there are no default arguments (C++ only).
  3188. CheckExtraCXXDefaultArguments(D);
  3189. }
  3190. DiagnoseFunctionSpecifiers(D);
  3191. if (D.getDeclSpec().isThreadSpecified())
  3192. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  3193. if (D.getDeclSpec().isConstexprSpecified())
  3194. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  3195. << 1;
  3196. if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
  3197. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  3198. << D.getName().getSourceRange();
  3199. return 0;
  3200. }
  3201. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  3202. if (!NewTD) return 0;
  3203. // Handle attributes prior to checking for duplicates in MergeVarDecl
  3204. ProcessDeclAttributes(S, NewTD, D);
  3205. CheckTypedefForVariablyModifiedType(S, NewTD);
  3206. bool Redeclaration = D.isRedeclaration();
  3207. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  3208. D.setRedeclaration(Redeclaration);
  3209. return ND;
  3210. }
  3211. void
  3212. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  3213. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  3214. // then it shall have block scope.
  3215. // Note that variably modified types must be fixed before merging the decl so
  3216. // that redeclarations will match.
  3217. QualType T = NewTD->getUnderlyingType();
  3218. if (T->isVariablyModifiedType()) {
  3219. getCurFunction()->setHasBranchProtectedScope();
  3220. if (S->getFnParent() == 0) {
  3221. bool SizeIsNegative;
  3222. llvm::APSInt Oversized;
  3223. QualType FixedTy =
  3224. TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  3225. Oversized);
  3226. if (!FixedTy.isNull()) {
  3227. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  3228. NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
  3229. } else {
  3230. if (SizeIsNegative)
  3231. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  3232. else if (T->isVariableArrayType())
  3233. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  3234. else if (Oversized.getBoolValue())
  3235. Diag(NewTD->getLocation(), diag::err_array_too_large)
  3236. << Oversized.toString(10);
  3237. else
  3238. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  3239. NewTD->setInvalidDecl();
  3240. }
  3241. }
  3242. }
  3243. }
  3244. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  3245. /// declares a typedef-name, either using the 'typedef' type specifier or via
  3246. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  3247. NamedDecl*
  3248. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  3249. LookupResult &Previous, bool &Redeclaration) {
  3250. // Merge the decl with the existing one if appropriate. If the decl is
  3251. // in an outer scope, it isn't the same thing.
  3252. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
  3253. /*ExplicitInstantiationOrSpecialization=*/false);
  3254. if (!Previous.empty()) {
  3255. Redeclaration = true;
  3256. MergeTypedefNameDecl(NewTD, Previous);
  3257. }
  3258. // If this is the C FILE type, notify the AST context.
  3259. if (IdentifierInfo *II = NewTD->getIdentifier())
  3260. if (!NewTD->isInvalidDecl() &&
  3261. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  3262. if (II->isStr("FILE"))
  3263. Context.setFILEDecl(NewTD);
  3264. else if (II->isStr("jmp_buf"))
  3265. Context.setjmp_bufDecl(NewTD);
  3266. else if (II->isStr("sigjmp_buf"))
  3267. Context.setsigjmp_bufDecl(NewTD);
  3268. else if (II->isStr("ucontext_t"))
  3269. Context.setucontext_tDecl(NewTD);
  3270. else if (II->isStr("__builtin_va_list"))
  3271. Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
  3272. }
  3273. return NewTD;
  3274. }
  3275. /// \brief Determines whether the given declaration is an out-of-scope
  3276. /// previous declaration.
  3277. ///
  3278. /// This routine should be invoked when name lookup has found a
  3279. /// previous declaration (PrevDecl) that is not in the scope where a
  3280. /// new declaration by the same name is being introduced. If the new
  3281. /// declaration occurs in a local scope, previous declarations with
  3282. /// linkage may still be considered previous declarations (C99
  3283. /// 6.2.2p4-5, C++ [basic.link]p6).
  3284. ///
  3285. /// \param PrevDecl the previous declaration found by name
  3286. /// lookup
  3287. ///
  3288. /// \param DC the context in which the new declaration is being
  3289. /// declared.
  3290. ///
  3291. /// \returns true if PrevDecl is an out-of-scope previous declaration
  3292. /// for a new delcaration with the same name.
  3293. static bool
  3294. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  3295. ASTContext &Context) {
  3296. if (!PrevDecl)
  3297. return false;
  3298. if (!PrevDecl->hasLinkage())
  3299. return false;
  3300. if (Context.getLangOptions().CPlusPlus) {
  3301. // C++ [basic.link]p6:
  3302. // If there is a visible declaration of an entity with linkage
  3303. // having the same name and type, ignoring entities declared
  3304. // outside the innermost enclosing namespace scope, the block
  3305. // scope declaration declares that same entity and receives the
  3306. // linkage of the previous declaration.
  3307. DeclContext *OuterContext = DC->getRedeclContext();
  3308. if (!OuterContext->isFunctionOrMethod())
  3309. // This rule only applies to block-scope declarations.
  3310. return false;
  3311. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  3312. if (PrevOuterContext->isRecord())
  3313. // We found a member function: ignore it.
  3314. return false;
  3315. // Find the innermost enclosing namespace for the new and
  3316. // previous declarations.
  3317. OuterContext = OuterContext->getEnclosingNamespaceContext();
  3318. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  3319. // The previous declaration is in a different namespace, so it
  3320. // isn't the same function.
  3321. if (!OuterContext->Equals(PrevOuterContext))
  3322. return false;
  3323. }
  3324. return true;
  3325. }
  3326. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  3327. CXXScopeSpec &SS = D.getCXXScopeSpec();
  3328. if (!SS.isSet()) return;
  3329. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  3330. }
  3331. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  3332. QualType type = decl->getType();
  3333. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  3334. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  3335. // Various kinds of declaration aren't allowed to be __autoreleasing.
  3336. unsigned kind = -1U;
  3337. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  3338. if (var->hasAttr<BlocksAttr>())
  3339. kind = 0; // __block
  3340. else if (!var->hasLocalStorage())
  3341. kind = 1; // global
  3342. } else if (isa<ObjCIvarDecl>(decl)) {
  3343. kind = 3; // ivar
  3344. } else if (isa<FieldDecl>(decl)) {
  3345. kind = 2; // field
  3346. }
  3347. if (kind != -1U) {
  3348. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  3349. << kind;
  3350. }
  3351. } else if (lifetime == Qualifiers::OCL_None) {
  3352. // Try to infer lifetime.
  3353. if (!type->isObjCLifetimeType())
  3354. return false;
  3355. lifetime = type->getObjCARCImplicitLifetime();
  3356. type = Context.getLifetimeQualifiedType(type, lifetime);
  3357. decl->setType(type);
  3358. }
  3359. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  3360. // Thread-local variables cannot have lifetime.
  3361. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  3362. var->isThreadSpecified()) {
  3363. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  3364. << var->getType();
  3365. return true;
  3366. }
  3367. }
  3368. return false;
  3369. }
  3370. NamedDecl*
  3371. Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  3372. TypeSourceInfo *TInfo, LookupResult &Previous,
  3373. MultiTemplateParamsArg TemplateParamLists) {
  3374. QualType R = TInfo->getType();
  3375. DeclarationName Name = GetNameForDeclarator(D).getName();
  3376. // Check that there are no default arguments (C++ only).
  3377. if (getLangOptions().CPlusPlus)
  3378. CheckExtraCXXDefaultArguments(D);
  3379. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  3380. assert(SCSpec != DeclSpec::SCS_typedef &&
  3381. "Parser allowed 'typedef' as storage class VarDecl.");
  3382. VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
  3383. if (SCSpec == DeclSpec::SCS_mutable) {
  3384. // mutable can only appear on non-static class members, so it's always
  3385. // an error here
  3386. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  3387. D.setInvalidType();
  3388. SC = SC_None;
  3389. }
  3390. SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
  3391. VarDecl::StorageClass SCAsWritten
  3392. = StorageClassSpecToVarDeclStorageClass(SCSpec);
  3393. IdentifierInfo *II = Name.getAsIdentifierInfo();
  3394. if (!II) {
  3395. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
  3396. << Name;
  3397. return 0;
  3398. }
  3399. DiagnoseFunctionSpecifiers(D);
  3400. if (!DC->isRecord() && S->getFnParent() == 0) {
  3401. // C99 6.9p2: The storage-class specifiers auto and register shall not
  3402. // appear in the declaration specifiers in an external declaration.
  3403. if (SC == SC_Auto || SC == SC_Register) {
  3404. // If this is a register variable with an asm label specified, then this
  3405. // is a GNU extension.
  3406. if (SC == SC_Register && D.getAsmLabel())
  3407. Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
  3408. else
  3409. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  3410. D.setInvalidType();
  3411. }
  3412. }
  3413. if (getLangOptions().OpenCL) {
  3414. // Set up the special work-group-local storage class for variables in the
  3415. // OpenCL __local address space.
  3416. if (R.getAddressSpace() == LangAS::opencl_local)
  3417. SC = SC_OpenCLWorkGroupLocal;
  3418. }
  3419. bool isExplicitSpecialization = false;
  3420. VarDecl *NewVD;
  3421. if (!getLangOptions().CPlusPlus) {
  3422. NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
  3423. D.getIdentifierLoc(), II,
  3424. R, TInfo, SC, SCAsWritten);
  3425. if (D.isInvalidType())
  3426. NewVD->setInvalidDecl();
  3427. } else {
  3428. if (DC->isRecord() && !CurContext->isRecord()) {
  3429. // This is an out-of-line definition of a static data member.
  3430. if (SC == SC_Static) {
  3431. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  3432. diag::err_static_out_of_line)
  3433. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  3434. } else if (SC == SC_None)
  3435. SC = SC_Static;
  3436. }
  3437. if (SC == SC_Static) {
  3438. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  3439. if (RD->isLocalClass())
  3440. Diag(D.getIdentifierLoc(),
  3441. diag::err_static_data_member_not_allowed_in_local_class)
  3442. << Name << RD->getDeclName();
  3443. // C++ [class.union]p1: If a union contains a static data member,
  3444. // the program is ill-formed.
  3445. //
  3446. // We also disallow static data members in anonymous structs.
  3447. if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName()))
  3448. Diag(D.getIdentifierLoc(),
  3449. diag::err_static_data_member_not_allowed_in_union_or_anon_struct)
  3450. << Name << RD->isUnion();
  3451. }
  3452. }
  3453. // Match up the template parameter lists with the scope specifier, then
  3454. // determine whether we have a template or a template specialization.
  3455. isExplicitSpecialization = false;
  3456. bool Invalid = false;
  3457. if (TemplateParameterList *TemplateParams
  3458. = MatchTemplateParametersToScopeSpecifier(
  3459. D.getDeclSpec().getSourceRange().getBegin(),
  3460. D.getIdentifierLoc(),
  3461. D.getCXXScopeSpec(),
  3462. TemplateParamLists.get(),
  3463. TemplateParamLists.size(),
  3464. /*never a friend*/ false,
  3465. isExplicitSpecialization,
  3466. Invalid)) {
  3467. if (TemplateParams->size() > 0) {
  3468. // There is no such thing as a variable template.
  3469. Diag(D.getIdentifierLoc(), diag::err_template_variable)
  3470. << II
  3471. << SourceRange(TemplateParams->getTemplateLoc(),
  3472. TemplateParams->getRAngleLoc());
  3473. return 0;
  3474. } else {
  3475. // There is an extraneous 'template<>' for this variable. Complain
  3476. // about it, but allow the declaration of the variable.
  3477. Diag(TemplateParams->getTemplateLoc(),
  3478. diag::err_template_variable_noparams)
  3479. << II
  3480. << SourceRange(TemplateParams->getTemplateLoc(),
  3481. TemplateParams->getRAngleLoc());
  3482. }
  3483. }
  3484. NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
  3485. D.getIdentifierLoc(), II,
  3486. R, TInfo, SC, SCAsWritten);
  3487. // If this decl has an auto type in need of deduction, make a note of the
  3488. // Decl so we can diagnose uses of it in its own initializer.
  3489. if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
  3490. R->getContainedAutoType())
  3491. ParsingInitForAutoVars.insert(NewVD);
  3492. if (D.isInvalidType() || Invalid)
  3493. NewVD->setInvalidDecl();
  3494. SetNestedNameSpecifier(NewVD, D);
  3495. if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
  3496. NewVD->setTemplateParameterListsInfo(Context,
  3497. TemplateParamLists.size(),
  3498. TemplateParamLists.release());
  3499. }
  3500. if (D.getDeclSpec().isConstexprSpecified())
  3501. NewVD->setConstexpr(true);
  3502. }
  3503. // Set the lexical context. If the declarator has a C++ scope specifier, the
  3504. // lexical context will be different from the semantic context.
  3505. NewVD->setLexicalDeclContext(CurContext);
  3506. if (D.getDeclSpec().isThreadSpecified()) {
  3507. if (NewVD->hasLocalStorage())
  3508. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
  3509. else if (!Context.getTargetInfo().isTLSSupported())
  3510. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
  3511. else
  3512. NewVD->setThreadSpecified(true);
  3513. }
  3514. if (D.getDeclSpec().isModulePrivateSpecified()) {
  3515. if (isExplicitSpecialization)
  3516. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  3517. << 2
  3518. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  3519. else if (NewVD->hasLocalStorage())
  3520. Diag(NewVD->getLocation(), diag::err_module_private_local)
  3521. << 0 << NewVD->getDeclName()
  3522. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  3523. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  3524. else
  3525. NewVD->setModulePrivate();
  3526. }
  3527. // Handle attributes prior to checking for duplicates in MergeVarDecl
  3528. ProcessDeclAttributes(S, NewVD, D);
  3529. // In auto-retain/release, infer strong retension for variables of
  3530. // retainable type.
  3531. if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  3532. NewVD->setInvalidDecl();
  3533. // Handle GNU asm-label extension (encoded as an attribute).
  3534. if (Expr *E = (Expr*)D.getAsmLabel()) {
  3535. // The parser guarantees this is a string.
  3536. StringLiteral *SE = cast<StringLiteral>(E);
  3537. StringRef Label = SE->getString();
  3538. if (S->getFnParent() != 0) {
  3539. switch (SC) {
  3540. case SC_None:
  3541. case SC_Auto:
  3542. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  3543. break;
  3544. case SC_Register:
  3545. if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
  3546. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  3547. break;
  3548. case SC_Static:
  3549. case SC_Extern:
  3550. case SC_PrivateExtern:
  3551. case SC_OpenCLWorkGroupLocal:
  3552. break;
  3553. }
  3554. }
  3555. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  3556. Context, Label));
  3557. }
  3558. // Diagnose shadowed variables before filtering for scope.
  3559. if (!D.getCXXScopeSpec().isSet())
  3560. CheckShadow(S, NewVD, Previous);
  3561. // Don't consider existing declarations that are in a different
  3562. // scope and are out-of-semantic-context declarations (if the new
  3563. // declaration has linkage).
  3564. FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
  3565. isExplicitSpecialization);
  3566. if (!getLangOptions().CPlusPlus) {
  3567. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  3568. } else {
  3569. // Merge the decl with the existing one if appropriate.
  3570. if (!Previous.empty()) {
  3571. if (Previous.isSingleResult() &&
  3572. isa<FieldDecl>(Previous.getFoundDecl()) &&
  3573. D.getCXXScopeSpec().isSet()) {
  3574. // The user tried to define a non-static data member
  3575. // out-of-line (C++ [dcl.meaning]p1).
  3576. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  3577. << D.getCXXScopeSpec().getRange();
  3578. Previous.clear();
  3579. NewVD->setInvalidDecl();
  3580. }
  3581. } else if (D.getCXXScopeSpec().isSet()) {
  3582. // No previous declaration in the qualifying scope.
  3583. Diag(D.getIdentifierLoc(), diag::err_no_member)
  3584. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  3585. << D.getCXXScopeSpec().getRange();
  3586. NewVD->setInvalidDecl();
  3587. }
  3588. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  3589. // This is an explicit specialization of a static data member. Check it.
  3590. if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
  3591. CheckMemberSpecialization(NewVD, Previous))
  3592. NewVD->setInvalidDecl();
  3593. }
  3594. // attributes declared post-definition are currently ignored
  3595. // FIXME: This should be handled in attribute merging, not
  3596. // here.
  3597. if (Previous.isSingleResult()) {
  3598. VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3599. if (Def && (Def = Def->getDefinition()) &&
  3600. Def != NewVD && D.hasAttributes()) {
  3601. Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
  3602. Diag(Def->getLocation(), diag::note_previous_definition);
  3603. }
  3604. }
  3605. // If this is a locally-scoped extern C variable, update the map of
  3606. // such variables.
  3607. if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
  3608. !NewVD->isInvalidDecl())
  3609. RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
  3610. // If there's a #pragma GCC visibility in scope, and this isn't a class
  3611. // member, set the visibility of this variable.
  3612. if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
  3613. AddPushedVisibilityAttribute(NewVD);
  3614. MarkUnusedFileScopedDecl(NewVD);
  3615. return NewVD;
  3616. }
  3617. /// \brief Diagnose variable or built-in function shadowing. Implements
  3618. /// -Wshadow.
  3619. ///
  3620. /// This method is called whenever a VarDecl is added to a "useful"
  3621. /// scope.
  3622. ///
  3623. /// \param S the scope in which the shadowing name is being declared
  3624. /// \param R the lookup of the name
  3625. ///
  3626. void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
  3627. // Return if warning is ignored.
  3628. if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
  3629. DiagnosticsEngine::Ignored)
  3630. return;
  3631. // Don't diagnose declarations at file scope.
  3632. if (D->hasGlobalStorage())
  3633. return;
  3634. DeclContext *NewDC = D->getDeclContext();
  3635. // Only diagnose if we're shadowing an unambiguous field or variable.
  3636. if (R.getResultKind() != LookupResult::Found)
  3637. return;
  3638. NamedDecl* ShadowedDecl = R.getFoundDecl();
  3639. if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
  3640. return;
  3641. // Fields are not shadowed by variables in C++ static methods.
  3642. if (isa<FieldDecl>(ShadowedDecl))
  3643. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  3644. if (MD->isStatic())
  3645. return;
  3646. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  3647. if (shadowedVar->isExternC()) {
  3648. // For shadowing external vars, make sure that we point to the global
  3649. // declaration, not a locally scoped extern declaration.
  3650. for (VarDecl::redecl_iterator
  3651. I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
  3652. I != E; ++I)
  3653. if (I->isFileVarDecl()) {
  3654. ShadowedDecl = *I;
  3655. break;
  3656. }
  3657. }
  3658. DeclContext *OldDC = ShadowedDecl->getDeclContext();
  3659. // Only warn about certain kinds of shadowing for class members.
  3660. if (NewDC && NewDC->isRecord()) {
  3661. // In particular, don't warn about shadowing non-class members.
  3662. if (!OldDC->isRecord())
  3663. return;
  3664. // TODO: should we warn about static data members shadowing
  3665. // static data members from base classes?
  3666. // TODO: don't diagnose for inaccessible shadowed members.
  3667. // This is hard to do perfectly because we might friend the
  3668. // shadowing context, but that's just a false negative.
  3669. }
  3670. // Determine what kind of declaration we're shadowing.
  3671. unsigned Kind;
  3672. if (isa<RecordDecl>(OldDC)) {
  3673. if (isa<FieldDecl>(ShadowedDecl))
  3674. Kind = 3; // field
  3675. else
  3676. Kind = 2; // static data member
  3677. } else if (OldDC->isFileContext())
  3678. Kind = 1; // global
  3679. else
  3680. Kind = 0; // local
  3681. DeclarationName Name = R.getLookupName();
  3682. // Emit warning and note.
  3683. Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
  3684. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  3685. }
  3686. /// \brief Check -Wshadow without the advantage of a previous lookup.
  3687. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  3688. if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
  3689. DiagnosticsEngine::Ignored)
  3690. return;
  3691. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  3692. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  3693. LookupName(R, S);
  3694. CheckShadow(S, D, R);
  3695. }
  3696. /// \brief Perform semantic checking on a newly-created variable
  3697. /// declaration.
  3698. ///
  3699. /// This routine performs all of the type-checking required for a
  3700. /// variable declaration once it has been built. It is used both to
  3701. /// check variables after they have been parsed and their declarators
  3702. /// have been translated into a declaration, and to check variables
  3703. /// that have been instantiated from a template.
  3704. ///
  3705. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  3706. ///
  3707. /// Returns true if the variable declaration is a redeclaration.
  3708. bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
  3709. LookupResult &Previous) {
  3710. // If the decl is already known invalid, don't check it.
  3711. if (NewVD->isInvalidDecl())
  3712. return false;
  3713. QualType T = NewVD->getType();
  3714. if (T->isObjCObjectType()) {
  3715. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  3716. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  3717. T = Context.getObjCObjectPointerType(T);
  3718. NewVD->setType(T);
  3719. }
  3720. // Emit an error if an address space was applied to decl with local storage.
  3721. // This includes arrays of objects with address space qualifiers, but not
  3722. // automatic variables that point to other address spaces.
  3723. // ISO/IEC TR 18037 S5.1.2
  3724. if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
  3725. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
  3726. NewVD->setInvalidDecl();
  3727. return false;
  3728. }
  3729. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  3730. && !NewVD->hasAttr<BlocksAttr>()) {
  3731. if (getLangOptions().getGC() != LangOptions::NonGC)
  3732. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  3733. else
  3734. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  3735. }
  3736. bool isVM = T->isVariablyModifiedType();
  3737. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  3738. NewVD->hasAttr<BlocksAttr>())
  3739. getCurFunction()->setHasBranchProtectedScope();
  3740. if ((isVM && NewVD->hasLinkage()) ||
  3741. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  3742. bool SizeIsNegative;
  3743. llvm::APSInt Oversized;
  3744. QualType FixedTy =
  3745. TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  3746. Oversized);
  3747. if (FixedTy.isNull() && T->isVariableArrayType()) {
  3748. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  3749. // FIXME: This won't give the correct result for
  3750. // int a[10][n];
  3751. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  3752. if (NewVD->isFileVarDecl())
  3753. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  3754. << SizeRange;
  3755. else if (NewVD->getStorageClass() == SC_Static)
  3756. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  3757. << SizeRange;
  3758. else
  3759. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  3760. << SizeRange;
  3761. NewVD->setInvalidDecl();
  3762. return false;
  3763. }
  3764. if (FixedTy.isNull()) {
  3765. if (NewVD->isFileVarDecl())
  3766. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  3767. else
  3768. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  3769. NewVD->setInvalidDecl();
  3770. return false;
  3771. }
  3772. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  3773. NewVD->setType(FixedTy);
  3774. }
  3775. if (Previous.empty() && NewVD->isExternC()) {
  3776. // Since we did not find anything by this name and we're declaring
  3777. // an extern "C" variable, look for a non-visible extern "C"
  3778. // declaration with the same name.
  3779. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  3780. = findLocallyScopedExternalDecl(NewVD->getDeclName());
  3781. if (Pos != LocallyScopedExternalDecls.end())
  3782. Previous.addDecl(Pos->second);
  3783. }
  3784. if (T->isVoidType() && !NewVD->hasExternalStorage()) {
  3785. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  3786. << T;
  3787. NewVD->setInvalidDecl();
  3788. return false;
  3789. }
  3790. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  3791. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  3792. NewVD->setInvalidDecl();
  3793. return false;
  3794. }
  3795. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  3796. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  3797. NewVD->setInvalidDecl();
  3798. return false;
  3799. }
  3800. // Function pointers and references cannot have qualified function type, only
  3801. // function pointer-to-members can do that.
  3802. QualType Pointee;
  3803. unsigned PtrOrRef = 0;
  3804. if (const PointerType *Ptr = T->getAs<PointerType>())
  3805. Pointee = Ptr->getPointeeType();
  3806. else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
  3807. Pointee = Ref->getPointeeType();
  3808. PtrOrRef = 1;
  3809. }
  3810. if (!Pointee.isNull() && Pointee->isFunctionProtoType() &&
  3811. Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) {
  3812. Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer)
  3813. << PtrOrRef;
  3814. NewVD->setInvalidDecl();
  3815. return false;
  3816. }
  3817. if (!Previous.empty()) {
  3818. MergeVarDecl(NewVD, Previous);
  3819. return true;
  3820. }
  3821. return false;
  3822. }
  3823. /// \brief Data used with FindOverriddenMethod
  3824. struct FindOverriddenMethodData {
  3825. Sema *S;
  3826. CXXMethodDecl *Method;
  3827. };
  3828. /// \brief Member lookup function that determines whether a given C++
  3829. /// method overrides a method in a base class, to be used with
  3830. /// CXXRecordDecl::lookupInBases().
  3831. static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
  3832. CXXBasePath &Path,
  3833. void *UserData) {
  3834. RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
  3835. FindOverriddenMethodData *Data
  3836. = reinterpret_cast<FindOverriddenMethodData*>(UserData);
  3837. DeclarationName Name = Data->Method->getDeclName();
  3838. // FIXME: Do we care about other names here too?
  3839. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  3840. // We really want to find the base class destructor here.
  3841. QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
  3842. CanQualType CT = Data->S->Context.getCanonicalType(T);
  3843. Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
  3844. }
  3845. for (Path.Decls = BaseRecord->lookup(Name);
  3846. Path.Decls.first != Path.Decls.second;
  3847. ++Path.Decls.first) {
  3848. NamedDecl *D = *Path.Decls.first;
  3849. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  3850. if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
  3851. return true;
  3852. }
  3853. }
  3854. return false;
  3855. }
  3856. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  3857. /// and if so, check that it's a valid override and remember it.
  3858. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  3859. // Look for virtual methods in base classes that this method might override.
  3860. CXXBasePaths Paths;
  3861. FindOverriddenMethodData Data;
  3862. Data.Method = MD;
  3863. Data.S = this;
  3864. bool AddedAny = false;
  3865. if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
  3866. for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
  3867. E = Paths.found_decls_end(); I != E; ++I) {
  3868. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
  3869. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  3870. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  3871. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  3872. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  3873. AddedAny = true;
  3874. }
  3875. }
  3876. }
  3877. }
  3878. return AddedAny;
  3879. }
  3880. namespace {
  3881. // Struct for holding all of the extra arguments needed by
  3882. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  3883. struct ActOnFDArgs {
  3884. Scope *S;
  3885. Declarator &D;
  3886. MultiTemplateParamsArg TemplateParamLists;
  3887. bool AddToScope;
  3888. };
  3889. }
  3890. namespace {
  3891. // Callback to only accept typo corrections that have a non-zero edit distance.
  3892. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  3893. public:
  3894. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  3895. return candidate.getEditDistance() > 0;
  3896. }
  3897. };
  3898. }
  3899. /// \brief Generate diagnostics for an invalid function redeclaration.
  3900. ///
  3901. /// This routine handles generating the diagnostic messages for an invalid
  3902. /// function redeclaration, including finding possible similar declarations
  3903. /// or performing typo correction if there are no previous declarations with
  3904. /// the same name.
  3905. ///
  3906. /// Returns a NamedDecl iff typo correction was performed and substituting in
  3907. /// the new declaration name does not cause new errors.
  3908. static NamedDecl* DiagnoseInvalidRedeclaration(
  3909. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  3910. ActOnFDArgs &ExtraArgs) {
  3911. NamedDecl *Result = NULL;
  3912. DeclarationName Name = NewFD->getDeclName();
  3913. DeclContext *NewDC = NewFD->getDeclContext();
  3914. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  3915. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  3916. llvm::SmallVector<unsigned, 1> MismatchedParams;
  3917. llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
  3918. TypoCorrection Correction;
  3919. bool isFriendDecl = (SemaRef.getLangOptions().CPlusPlus &&
  3920. ExtraArgs.D.getDeclSpec().isFriendSpecified());
  3921. unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
  3922. : diag::err_member_def_does_not_match;
  3923. NewFD->setInvalidDecl();
  3924. SemaRef.LookupQualifiedName(Prev, NewDC);
  3925. assert(!Prev.isAmbiguous() &&
  3926. "Cannot have an ambiguity in previous-declaration lookup");
  3927. DifferentNameValidatorCCC Validator;
  3928. if (!Prev.empty()) {
  3929. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  3930. Func != FuncEnd; ++Func) {
  3931. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  3932. if (FD &&
  3933. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  3934. // Add 1 to the index so that 0 can mean the mismatch didn't
  3935. // involve a parameter
  3936. unsigned ParamNum =
  3937. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  3938. NearMatches.push_back(std::make_pair(FD, ParamNum));
  3939. }
  3940. }
  3941. // If the qualified name lookup yielded nothing, try typo correction
  3942. } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
  3943. Prev.getLookupKind(), 0, 0,
  3944. Validator, NewDC))) {
  3945. // Trap errors.
  3946. Sema::SFINAETrap Trap(SemaRef);
  3947. // Set up everything for the call to ActOnFunctionDeclarator
  3948. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  3949. ExtraArgs.D.getIdentifierLoc());
  3950. Previous.clear();
  3951. Previous.setLookupName(Correction.getCorrection());
  3952. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  3953. CDeclEnd = Correction.end();
  3954. CDecl != CDeclEnd; ++CDecl) {
  3955. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  3956. if (FD && hasSimilarParameters(SemaRef.Context, FD, NewFD,
  3957. MismatchedParams)) {
  3958. Previous.addDecl(FD);
  3959. }
  3960. }
  3961. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  3962. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  3963. // pieces need to verify the typo-corrected C++ declaraction and hopefully
  3964. // eliminate the need for the parameter pack ExtraArgs.
  3965. Result = SemaRef.ActOnFunctionDeclarator(ExtraArgs.S, ExtraArgs.D,
  3966. NewFD->getDeclContext(),
  3967. NewFD->getTypeSourceInfo(),
  3968. Previous,
  3969. ExtraArgs.TemplateParamLists,
  3970. ExtraArgs.AddToScope);
  3971. if (Trap.hasErrorOccurred()) {
  3972. // Pretend the typo correction never occurred
  3973. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  3974. ExtraArgs.D.getIdentifierLoc());
  3975. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  3976. Previous.clear();
  3977. Previous.setLookupName(Name);
  3978. Result = NULL;
  3979. } else {
  3980. for (LookupResult::iterator Func = Previous.begin(),
  3981. FuncEnd = Previous.end();
  3982. Func != FuncEnd; ++Func) {
  3983. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
  3984. NearMatches.push_back(std::make_pair(FD, 0));
  3985. }
  3986. }
  3987. if (NearMatches.empty()) {
  3988. // Ignore the correction if it didn't yield any close FunctionDecl matches
  3989. Correction = TypoCorrection();
  3990. } else {
  3991. DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
  3992. : diag::err_member_def_does_not_match_suggest;
  3993. }
  3994. }
  3995. if (Correction)
  3996. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  3997. << Name << NewDC << Correction.getQuoted(SemaRef.getLangOptions())
  3998. << FixItHint::CreateReplacement(
  3999. NewFD->getLocation(),
  4000. Correction.getAsString(SemaRef.getLangOptions()));
  4001. else
  4002. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  4003. << Name << NewDC << NewFD->getLocation();
  4004. bool NewFDisConst = false;
  4005. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  4006. NewFDisConst = NewMD->getTypeQualifiers() & Qualifiers::Const;
  4007. for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
  4008. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  4009. NearMatch != NearMatchEnd; ++NearMatch) {
  4010. FunctionDecl *FD = NearMatch->first;
  4011. bool FDisConst = false;
  4012. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  4013. FDisConst = MD->getTypeQualifiers() & Qualifiers::Const;
  4014. if (unsigned Idx = NearMatch->second) {
  4015. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  4016. SemaRef.Diag(FDParam->getTypeSpecStartLoc(),
  4017. diag::note_member_def_close_param_match)
  4018. << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
  4019. } else if (Correction) {
  4020. SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
  4021. << Correction.getQuoted(SemaRef.getLangOptions());
  4022. } else if (FDisConst != NewFDisConst) {
  4023. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  4024. << NewFDisConst << FD->getSourceRange().getEnd();
  4025. } else
  4026. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
  4027. }
  4028. return Result;
  4029. }
  4030. static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
  4031. Declarator &D) {
  4032. switch (D.getDeclSpec().getStorageClassSpec()) {
  4033. default: llvm_unreachable("Unknown storage class!");
  4034. case DeclSpec::SCS_auto:
  4035. case DeclSpec::SCS_register:
  4036. case DeclSpec::SCS_mutable:
  4037. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4038. diag::err_typecheck_sclass_func);
  4039. D.setInvalidType();
  4040. break;
  4041. case DeclSpec::SCS_unspecified: break;
  4042. case DeclSpec::SCS_extern: return SC_Extern;
  4043. case DeclSpec::SCS_static: {
  4044. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  4045. // C99 6.7.1p5:
  4046. // The declaration of an identifier for a function that has
  4047. // block scope shall have no explicit storage-class specifier
  4048. // other than extern
  4049. // See also (C++ [dcl.stc]p4).
  4050. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4051. diag::err_static_block_func);
  4052. break;
  4053. } else
  4054. return SC_Static;
  4055. }
  4056. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4057. }
  4058. // No explicit storage class has already been returned
  4059. return SC_None;
  4060. }
  4061. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  4062. DeclContext *DC, QualType &R,
  4063. TypeSourceInfo *TInfo,
  4064. FunctionDecl::StorageClass SC,
  4065. bool &IsVirtualOkay) {
  4066. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  4067. DeclarationName Name = NameInfo.getName();
  4068. FunctionDecl *NewFD = 0;
  4069. bool isInline = D.getDeclSpec().isInlineSpecified();
  4070. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
  4071. FunctionDecl::StorageClass SCAsWritten
  4072. = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
  4073. if (!SemaRef.getLangOptions().CPlusPlus) {
  4074. // Determine whether the function was written with a
  4075. // prototype. This true when:
  4076. // - there is a prototype in the declarator, or
  4077. // - the type R of the function is some kind of typedef or other reference
  4078. // to a type name (which eventually refers to a function type).
  4079. bool HasPrototype =
  4080. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  4081. (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
  4082. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  4083. D.getSourceRange().getBegin(), NameInfo, R,
  4084. TInfo, SC, SCAsWritten, isInline,
  4085. HasPrototype);
  4086. if (D.isInvalidType())
  4087. NewFD->setInvalidDecl();
  4088. // Set the lexical context.
  4089. NewFD->setLexicalDeclContext(SemaRef.CurContext);
  4090. return NewFD;
  4091. }
  4092. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  4093. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  4094. // Check that the return type is not an abstract class type.
  4095. // For record types, this is done by the AbstractClassUsageDiagnoser once
  4096. // the class has been completely parsed.
  4097. if (!DC->isRecord() &&
  4098. SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
  4099. R->getAs<FunctionType>()->getResultType(),
  4100. diag::err_abstract_type_in_decl,
  4101. SemaRef.AbstractReturnType))
  4102. D.setInvalidType();
  4103. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  4104. // This is a C++ constructor declaration.
  4105. assert(DC->isRecord() &&
  4106. "Constructors can only be declared in a member context");
  4107. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  4108. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4109. D.getSourceRange().getBegin(), NameInfo,
  4110. R, TInfo, isExplicit, isInline,
  4111. /*isImplicitlyDeclared=*/false,
  4112. isConstexpr);
  4113. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  4114. // This is a C++ destructor declaration.
  4115. if (DC->isRecord()) {
  4116. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  4117. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  4118. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  4119. SemaRef.Context, Record,
  4120. D.getSourceRange().getBegin(),
  4121. NameInfo, R, TInfo, isInline,
  4122. /*isImplicitlyDeclared=*/false);
  4123. // If the class is complete, then we now create the implicit exception
  4124. // specification. If the class is incomplete or dependent, we can't do
  4125. // it yet.
  4126. if (SemaRef.getLangOptions().CPlusPlus0x && !Record->isDependentType() &&
  4127. Record->getDefinition() && !Record->isBeingDefined() &&
  4128. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  4129. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  4130. }
  4131. IsVirtualOkay = true;
  4132. return NewDD;
  4133. } else {
  4134. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  4135. D.setInvalidType();
  4136. // Create a FunctionDecl to satisfy the function definition parsing
  4137. // code path.
  4138. return FunctionDecl::Create(SemaRef.Context, DC,
  4139. D.getSourceRange().getBegin(),
  4140. D.getIdentifierLoc(), Name, R, TInfo,
  4141. SC, SCAsWritten, isInline,
  4142. /*hasPrototype=*/true, isConstexpr);
  4143. }
  4144. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  4145. if (!DC->isRecord()) {
  4146. SemaRef.Diag(D.getIdentifierLoc(),
  4147. diag::err_conv_function_not_member);
  4148. return 0;
  4149. }
  4150. SemaRef.CheckConversionDeclarator(D, R, SC);
  4151. IsVirtualOkay = true;
  4152. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4153. D.getSourceRange().getBegin(), NameInfo,
  4154. R, TInfo, isInline, isExplicit,
  4155. isConstexpr, SourceLocation());
  4156. } else if (DC->isRecord()) {
  4157. // If the name of the function is the same as the name of the record,
  4158. // then this must be an invalid constructor that has a return type.
  4159. // (The parser checks for a return type and makes the declarator a
  4160. // constructor if it has no return type).
  4161. if (Name.getAsIdentifierInfo() &&
  4162. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  4163. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  4164. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  4165. << SourceRange(D.getIdentifierLoc());
  4166. return 0;
  4167. }
  4168. bool isStatic = SC == SC_Static;
  4169. // [class.free]p1:
  4170. // Any allocation function for a class T is a static member
  4171. // (even if not explicitly declared static).
  4172. if (Name.getCXXOverloadedOperator() == OO_New ||
  4173. Name.getCXXOverloadedOperator() == OO_Array_New)
  4174. isStatic = true;
  4175. // [class.free]p6 Any deallocation function for a class X is a static member
  4176. // (even if not explicitly declared static).
  4177. if (Name.getCXXOverloadedOperator() == OO_Delete ||
  4178. Name.getCXXOverloadedOperator() == OO_Array_Delete)
  4179. isStatic = true;
  4180. IsVirtualOkay = !isStatic;
  4181. // This is a C++ method declaration.
  4182. return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4183. D.getSourceRange().getBegin(), NameInfo, R,
  4184. TInfo, isStatic, SCAsWritten, isInline,
  4185. isConstexpr, SourceLocation());
  4186. } else {
  4187. // Determine whether the function was written with a
  4188. // prototype. This true when:
  4189. // - we're in C++ (where every function has a prototype),
  4190. return FunctionDecl::Create(SemaRef.Context, DC,
  4191. D.getSourceRange().getBegin(),
  4192. NameInfo, R, TInfo, SC, SCAsWritten, isInline,
  4193. true/*HasPrototype*/, isConstexpr);
  4194. }
  4195. }
  4196. NamedDecl*
  4197. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  4198. TypeSourceInfo *TInfo, LookupResult &Previous,
  4199. MultiTemplateParamsArg TemplateParamLists,
  4200. bool &AddToScope) {
  4201. QualType R = TInfo->getType();
  4202. assert(R.getTypePtr()->isFunctionType());
  4203. // TODO: consider using NameInfo for diagnostic.
  4204. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4205. DeclarationName Name = NameInfo.getName();
  4206. FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
  4207. if (D.getDeclSpec().isThreadSpecified())
  4208. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  4209. // Do not allow returning a objc interface by-value.
  4210. if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
  4211. Diag(D.getIdentifierLoc(),
  4212. diag::err_object_cannot_be_passed_returned_by_value) << 0
  4213. << R->getAs<FunctionType>()->getResultType()
  4214. << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
  4215. QualType T = R->getAs<FunctionType>()->getResultType();
  4216. T = Context.getObjCObjectPointerType(T);
  4217. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
  4218. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  4219. R = Context.getFunctionType(T, FPT->arg_type_begin(),
  4220. FPT->getNumArgs(), EPI);
  4221. }
  4222. else if (isa<FunctionNoProtoType>(R))
  4223. R = Context.getFunctionNoProtoType(T);
  4224. }
  4225. bool isFriend = false;
  4226. FunctionTemplateDecl *FunctionTemplate = 0;
  4227. bool isExplicitSpecialization = false;
  4228. bool isFunctionTemplateSpecialization = false;
  4229. bool isDependentClassScopeExplicitSpecialization = false;
  4230. bool isVirtualOkay = false;
  4231. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  4232. isVirtualOkay);
  4233. if (!NewFD) return 0;
  4234. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  4235. NewFD->setTopLevelDeclInObjCContainer();
  4236. if (getLangOptions().CPlusPlus) {
  4237. bool isInline = D.getDeclSpec().isInlineSpecified();
  4238. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  4239. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  4240. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  4241. isFriend = D.getDeclSpec().isFriendSpecified();
  4242. if (isFriend && !isInline && D.isFunctionDefinition()) {
  4243. // C++ [class.friend]p5
  4244. // A function can be defined in a friend declaration of a
  4245. // class . . . . Such a function is implicitly inline.
  4246. NewFD->setImplicitlyInline();
  4247. }
  4248. SetNestedNameSpecifier(NewFD, D);
  4249. isExplicitSpecialization = false;
  4250. isFunctionTemplateSpecialization = false;
  4251. if (D.isInvalidType())
  4252. NewFD->setInvalidDecl();
  4253. // Set the lexical context. If the declarator has a C++
  4254. // scope specifier, or is the object of a friend declaration, the
  4255. // lexical context will be different from the semantic context.
  4256. NewFD->setLexicalDeclContext(CurContext);
  4257. // Match up the template parameter lists with the scope specifier, then
  4258. // determine whether we have a template or a template specialization.
  4259. bool Invalid = false;
  4260. if (TemplateParameterList *TemplateParams
  4261. = MatchTemplateParametersToScopeSpecifier(
  4262. D.getDeclSpec().getSourceRange().getBegin(),
  4263. D.getIdentifierLoc(),
  4264. D.getCXXScopeSpec(),
  4265. TemplateParamLists.get(),
  4266. TemplateParamLists.size(),
  4267. isFriend,
  4268. isExplicitSpecialization,
  4269. Invalid)) {
  4270. if (TemplateParams->size() > 0) {
  4271. // This is a function template
  4272. // Check that we can declare a template here.
  4273. if (CheckTemplateDeclScope(S, TemplateParams))
  4274. return 0;
  4275. // A destructor cannot be a template.
  4276. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  4277. Diag(NewFD->getLocation(), diag::err_destructor_template);
  4278. return 0;
  4279. }
  4280. // If we're adding a template to a dependent context, we may need to
  4281. // rebuilding some of the types used within the template parameter list,
  4282. // now that we know what the current instantiation is.
  4283. if (DC->isDependentContext()) {
  4284. ContextRAII SavedContext(*this, DC);
  4285. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  4286. Invalid = true;
  4287. }
  4288. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  4289. NewFD->getLocation(),
  4290. Name, TemplateParams,
  4291. NewFD);
  4292. FunctionTemplate->setLexicalDeclContext(CurContext);
  4293. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  4294. // For source fidelity, store the other template param lists.
  4295. if (TemplateParamLists.size() > 1) {
  4296. NewFD->setTemplateParameterListsInfo(Context,
  4297. TemplateParamLists.size() - 1,
  4298. TemplateParamLists.release());
  4299. }
  4300. } else {
  4301. // This is a function template specialization.
  4302. isFunctionTemplateSpecialization = true;
  4303. // For source fidelity, store all the template param lists.
  4304. NewFD->setTemplateParameterListsInfo(Context,
  4305. TemplateParamLists.size(),
  4306. TemplateParamLists.release());
  4307. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  4308. if (isFriend) {
  4309. // We want to remove the "template<>", found here.
  4310. SourceRange RemoveRange = TemplateParams->getSourceRange();
  4311. // If we remove the template<> and the name is not a
  4312. // template-id, we're actually silently creating a problem:
  4313. // the friend declaration will refer to an untemplated decl,
  4314. // and clearly the user wants a template specialization. So
  4315. // we need to insert '<>' after the name.
  4316. SourceLocation InsertLoc;
  4317. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  4318. InsertLoc = D.getName().getSourceRange().getEnd();
  4319. InsertLoc = PP.getLocForEndOfToken(InsertLoc);
  4320. }
  4321. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  4322. << Name << RemoveRange
  4323. << FixItHint::CreateRemoval(RemoveRange)
  4324. << FixItHint::CreateInsertion(InsertLoc, "<>");
  4325. }
  4326. }
  4327. }
  4328. else {
  4329. // All template param lists were matched against the scope specifier:
  4330. // this is NOT (an explicit specialization of) a template.
  4331. if (TemplateParamLists.size() > 0)
  4332. // For source fidelity, store all the template param lists.
  4333. NewFD->setTemplateParameterListsInfo(Context,
  4334. TemplateParamLists.size(),
  4335. TemplateParamLists.release());
  4336. }
  4337. if (Invalid) {
  4338. NewFD->setInvalidDecl();
  4339. if (FunctionTemplate)
  4340. FunctionTemplate->setInvalidDecl();
  4341. }
  4342. // If we see "T var();" at block scope, where T is a class type, it is
  4343. // probably an attempt to initialize a variable, not a function declaration.
  4344. // We don't catch this case earlier, since there is no ambiguity here.
  4345. if (!FunctionTemplate && D.getFunctionDefinitionKind() == FDK_Declaration &&
  4346. CurContext->isFunctionOrMethod() &&
  4347. D.getNumTypeObjects() == 1 && D.isFunctionDeclarator() &&
  4348. D.getDeclSpec().getStorageClassSpecAsWritten()
  4349. == DeclSpec::SCS_unspecified) {
  4350. QualType T = R->getAs<FunctionType>()->getResultType();
  4351. DeclaratorChunk &C = D.getTypeObject(0);
  4352. if (!T->isVoidType() && C.Fun.NumArgs == 0 && !C.Fun.isVariadic &&
  4353. !C.Fun.TrailingReturnType &&
  4354. C.Fun.getExceptionSpecType() == EST_None) {
  4355. SourceRange ParenRange(C.Loc, C.EndLoc);
  4356. Diag(C.Loc, diag::warn_empty_parens_are_function_decl) << ParenRange;
  4357. // If the declaration looks like:
  4358. // T var1,
  4359. // f();
  4360. // and name lookup finds a function named 'f', then the ',' was
  4361. // probably intended to be a ';'.
  4362. if (!D.isFirstDeclarator() && D.getIdentifier()) {
  4363. FullSourceLoc Comma(D.getCommaLoc(), SourceMgr);
  4364. FullSourceLoc Name(D.getIdentifierLoc(), SourceMgr);
  4365. if (Comma.getFileID() != Name.getFileID() ||
  4366. Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
  4367. LookupResult Result(*this, D.getIdentifier(), SourceLocation(),
  4368. LookupOrdinaryName);
  4369. if (LookupName(Result, S))
  4370. Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
  4371. << FixItHint::CreateReplacement(D.getCommaLoc(), ";") << NewFD;
  4372. }
  4373. }
  4374. const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  4375. // Empty parens mean value-initialization, and no parens mean default
  4376. // initialization. These are equivalent if the default constructor is
  4377. // user-provided, or if zero-initialization is a no-op.
  4378. if (RD && RD->hasDefinition() &&
  4379. (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
  4380. Diag(C.Loc, diag::note_empty_parens_default_ctor)
  4381. << FixItHint::CreateRemoval(ParenRange);
  4382. else if (const char *Init = getFixItZeroInitializerForType(T))
  4383. Diag(C.Loc, diag::note_empty_parens_zero_initialize)
  4384. << FixItHint::CreateReplacement(ParenRange, Init);
  4385. else if (LangOpts.CPlusPlus0x)
  4386. Diag(C.Loc, diag::note_empty_parens_zero_initialize)
  4387. << FixItHint::CreateReplacement(ParenRange, "{}");
  4388. }
  4389. }
  4390. // C++ [dcl.fct.spec]p5:
  4391. // The virtual specifier shall only be used in declarations of
  4392. // nonstatic class member functions that appear within a
  4393. // member-specification of a class declaration; see 10.3.
  4394. //
  4395. if (isVirtual && !NewFD->isInvalidDecl()) {
  4396. if (!isVirtualOkay) {
  4397. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  4398. diag::err_virtual_non_function);
  4399. } else if (!CurContext->isRecord()) {
  4400. // 'virtual' was specified outside of the class.
  4401. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  4402. diag::err_virtual_out_of_class)
  4403. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  4404. } else if (NewFD->getDescribedFunctionTemplate()) {
  4405. // C++ [temp.mem]p3:
  4406. // A member function template shall not be virtual.
  4407. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  4408. diag::err_virtual_member_function_template)
  4409. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  4410. } else {
  4411. // Okay: Add virtual to the method.
  4412. NewFD->setVirtualAsWritten(true);
  4413. }
  4414. }
  4415. // C++ [dcl.fct.spec]p3:
  4416. // The inline specifier shall not appear on a block scope function
  4417. // declaration.
  4418. if (isInline && !NewFD->isInvalidDecl()) {
  4419. if (CurContext->isFunctionOrMethod()) {
  4420. // 'inline' is not allowed on block scope function declaration.
  4421. Diag(D.getDeclSpec().getInlineSpecLoc(),
  4422. diag::err_inline_declaration_block_scope) << Name
  4423. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  4424. }
  4425. }
  4426. // C++ [dcl.fct.spec]p6:
  4427. // The explicit specifier shall be used only in the declaration of a
  4428. // constructor or conversion function within its class definition;
  4429. // see 12.3.1 and 12.3.2.
  4430. if (isExplicit && !NewFD->isInvalidDecl()) {
  4431. if (!CurContext->isRecord()) {
  4432. // 'explicit' was specified outside of the class.
  4433. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  4434. diag::err_explicit_out_of_class)
  4435. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  4436. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  4437. !isa<CXXConversionDecl>(NewFD)) {
  4438. // 'explicit' was specified on a function that wasn't a constructor
  4439. // or conversion function.
  4440. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  4441. diag::err_explicit_non_ctor_or_conv_function)
  4442. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  4443. }
  4444. }
  4445. if (isConstexpr) {
  4446. // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
  4447. // are implicitly inline.
  4448. NewFD->setImplicitlyInline();
  4449. // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
  4450. // be either constructors or to return a literal type. Therefore,
  4451. // destructors cannot be declared constexpr.
  4452. if (isa<CXXDestructorDecl>(NewFD))
  4453. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  4454. }
  4455. // If __module_private__ was specified, mark the function accordingly.
  4456. if (D.getDeclSpec().isModulePrivateSpecified()) {
  4457. if (isFunctionTemplateSpecialization) {
  4458. SourceLocation ModulePrivateLoc
  4459. = D.getDeclSpec().getModulePrivateSpecLoc();
  4460. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  4461. << 0
  4462. << FixItHint::CreateRemoval(ModulePrivateLoc);
  4463. } else {
  4464. NewFD->setModulePrivate();
  4465. if (FunctionTemplate)
  4466. FunctionTemplate->setModulePrivate();
  4467. }
  4468. }
  4469. if (isFriend) {
  4470. // For now, claim that the objects have no previous declaration.
  4471. if (FunctionTemplate) {
  4472. FunctionTemplate->setObjectOfFriendDecl(false);
  4473. FunctionTemplate->setAccess(AS_public);
  4474. }
  4475. NewFD->setObjectOfFriendDecl(false);
  4476. NewFD->setAccess(AS_public);
  4477. }
  4478. // If a function is defined as defaulted or deleted, mark it as such now.
  4479. switch (D.getFunctionDefinitionKind()) {
  4480. case FDK_Declaration:
  4481. case FDK_Definition:
  4482. break;
  4483. case FDK_Defaulted:
  4484. NewFD->setDefaulted();
  4485. break;
  4486. case FDK_Deleted:
  4487. NewFD->setDeletedAsWritten();
  4488. break;
  4489. }
  4490. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  4491. D.isFunctionDefinition()) {
  4492. // C++ [class.mfct]p2:
  4493. // A member function may be defined (8.4) in its class definition, in
  4494. // which case it is an inline member function (7.1.2)
  4495. NewFD->setImplicitlyInline();
  4496. }
  4497. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  4498. !CurContext->isRecord()) {
  4499. // C++ [class.static]p1:
  4500. // A data or function member of a class may be declared static
  4501. // in a class definition, in which case it is a static member of
  4502. // the class.
  4503. // Complain about the 'static' specifier if it's on an out-of-line
  4504. // member function definition.
  4505. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4506. diag::err_static_out_of_line)
  4507. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  4508. }
  4509. }
  4510. // Filter out previous declarations that don't match the scope.
  4511. FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
  4512. isExplicitSpecialization ||
  4513. isFunctionTemplateSpecialization);
  4514. // Handle GNU asm-label extension (encoded as an attribute).
  4515. if (Expr *E = (Expr*) D.getAsmLabel()) {
  4516. // The parser guarantees this is a string.
  4517. StringLiteral *SE = cast<StringLiteral>(E);
  4518. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  4519. SE->getString()));
  4520. }
  4521. // Copy the parameter declarations from the declarator D to the function
  4522. // declaration NewFD, if they are available. First scavenge them into Params.
  4523. SmallVector<ParmVarDecl*, 16> Params;
  4524. if (D.isFunctionDeclarator()) {
  4525. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  4526. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  4527. // function that takes no arguments, not a function that takes a
  4528. // single void argument.
  4529. // We let through "const void" here because Sema::GetTypeForDeclarator
  4530. // already checks for that case.
  4531. if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
  4532. FTI.ArgInfo[0].Param &&
  4533. cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
  4534. // Empty arg list, don't push any params.
  4535. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
  4536. // In C++, the empty parameter-type-list must be spelled "void"; a
  4537. // typedef of void is not permitted.
  4538. if (getLangOptions().CPlusPlus &&
  4539. Param->getType().getUnqualifiedType() != Context.VoidTy) {
  4540. bool IsTypeAlias = false;
  4541. if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
  4542. IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
  4543. else if (const TemplateSpecializationType *TST =
  4544. Param->getType()->getAs<TemplateSpecializationType>())
  4545. IsTypeAlias = TST->isTypeAlias();
  4546. Diag(Param->getLocation(), diag::err_param_typedef_of_void)
  4547. << IsTypeAlias;
  4548. }
  4549. } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
  4550. for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
  4551. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
  4552. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  4553. Param->setDeclContext(NewFD);
  4554. Params.push_back(Param);
  4555. if (Param->isInvalidDecl())
  4556. NewFD->setInvalidDecl();
  4557. }
  4558. }
  4559. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  4560. // When we're declaring a function with a typedef, typeof, etc as in the
  4561. // following example, we'll need to synthesize (unnamed)
  4562. // parameters for use in the declaration.
  4563. //
  4564. // @code
  4565. // typedef void fn(int);
  4566. // fn f;
  4567. // @endcode
  4568. // Synthesize a parameter for each argument type.
  4569. for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
  4570. AE = FT->arg_type_end(); AI != AE; ++AI) {
  4571. ParmVarDecl *Param =
  4572. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
  4573. Param->setScopeInfo(0, Params.size());
  4574. Params.push_back(Param);
  4575. }
  4576. } else {
  4577. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  4578. "Should not need args for typedef of non-prototype fn");
  4579. }
  4580. // Finally, we know we have the right number of parameters, install them.
  4581. NewFD->setParams(Params);
  4582. // Process the non-inheritable attributes on this declaration.
  4583. ProcessDeclAttributes(S, NewFD, D,
  4584. /*NonInheritable=*/true, /*Inheritable=*/false);
  4585. if (!getLangOptions().CPlusPlus) {
  4586. // Perform semantic checking on the function declaration.
  4587. bool isExplicitSpecialization=false;
  4588. if (!NewFD->isInvalidDecl()) {
  4589. if (NewFD->getResultType()->isVariablyModifiedType()) {
  4590. // Functions returning a variably modified type violate C99 6.7.5.2p2
  4591. // because all functions have linkage.
  4592. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  4593. NewFD->setInvalidDecl();
  4594. } else {
  4595. if (NewFD->isMain())
  4596. CheckMain(NewFD, D.getDeclSpec());
  4597. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  4598. isExplicitSpecialization));
  4599. }
  4600. }
  4601. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  4602. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  4603. "previous declaration set still overloaded");
  4604. } else {
  4605. // If the declarator is a template-id, translate the parser's template
  4606. // argument list into our AST format.
  4607. bool HasExplicitTemplateArgs = false;
  4608. TemplateArgumentListInfo TemplateArgs;
  4609. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  4610. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  4611. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  4612. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  4613. ASTTemplateArgsPtr TemplateArgsPtr(*this,
  4614. TemplateId->getTemplateArgs(),
  4615. TemplateId->NumArgs);
  4616. translateTemplateArguments(TemplateArgsPtr,
  4617. TemplateArgs);
  4618. TemplateArgsPtr.release();
  4619. HasExplicitTemplateArgs = true;
  4620. if (NewFD->isInvalidDecl()) {
  4621. HasExplicitTemplateArgs = false;
  4622. } else if (FunctionTemplate) {
  4623. // Function template with explicit template arguments.
  4624. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  4625. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  4626. HasExplicitTemplateArgs = false;
  4627. } else if (!isFunctionTemplateSpecialization &&
  4628. !D.getDeclSpec().isFriendSpecified()) {
  4629. // We have encountered something that the user meant to be a
  4630. // specialization (because it has explicitly-specified template
  4631. // arguments) but that was not introduced with a "template<>" (or had
  4632. // too few of them).
  4633. Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
  4634. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
  4635. << FixItHint::CreateInsertion(
  4636. D.getDeclSpec().getSourceRange().getBegin(),
  4637. "template<> ");
  4638. isFunctionTemplateSpecialization = true;
  4639. } else {
  4640. // "friend void foo<>(int);" is an implicit specialization decl.
  4641. isFunctionTemplateSpecialization = true;
  4642. }
  4643. } else if (isFriend && isFunctionTemplateSpecialization) {
  4644. // This combination is only possible in a recovery case; the user
  4645. // wrote something like:
  4646. // template <> friend void foo(int);
  4647. // which we're recovering from as if the user had written:
  4648. // friend void foo<>(int);
  4649. // Go ahead and fake up a template id.
  4650. HasExplicitTemplateArgs = true;
  4651. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  4652. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  4653. }
  4654. // If it's a friend (and only if it's a friend), it's possible
  4655. // that either the specialized function type or the specialized
  4656. // template is dependent, and therefore matching will fail. In
  4657. // this case, don't check the specialization yet.
  4658. bool InstantiationDependent = false;
  4659. if (isFunctionTemplateSpecialization && isFriend &&
  4660. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  4661. TemplateSpecializationType::anyDependentTemplateArguments(
  4662. TemplateArgs.getArgumentArray(), TemplateArgs.size(),
  4663. InstantiationDependent))) {
  4664. assert(HasExplicitTemplateArgs &&
  4665. "friend function specialization without template args");
  4666. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  4667. Previous))
  4668. NewFD->setInvalidDecl();
  4669. } else if (isFunctionTemplateSpecialization) {
  4670. if (CurContext->isDependentContext() && CurContext->isRecord()
  4671. && !isFriend) {
  4672. isDependentClassScopeExplicitSpecialization = true;
  4673. Diag(NewFD->getLocation(), getLangOptions().MicrosoftExt ?
  4674. diag::ext_function_specialization_in_class :
  4675. diag::err_function_specialization_in_class)
  4676. << NewFD->getDeclName();
  4677. } else if (CheckFunctionTemplateSpecialization(NewFD,
  4678. (HasExplicitTemplateArgs ? &TemplateArgs : 0),
  4679. Previous))
  4680. NewFD->setInvalidDecl();
  4681. // C++ [dcl.stc]p1:
  4682. // A storage-class-specifier shall not be specified in an explicit
  4683. // specialization (14.7.3)
  4684. if (SC != SC_None) {
  4685. if (SC != NewFD->getStorageClass())
  4686. Diag(NewFD->getLocation(),
  4687. diag::err_explicit_specialization_inconsistent_storage_class)
  4688. << SC
  4689. << FixItHint::CreateRemoval(
  4690. D.getDeclSpec().getStorageClassSpecLoc());
  4691. else
  4692. Diag(NewFD->getLocation(),
  4693. diag::ext_explicit_specialization_storage_class)
  4694. << FixItHint::CreateRemoval(
  4695. D.getDeclSpec().getStorageClassSpecLoc());
  4696. }
  4697. } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
  4698. if (CheckMemberSpecialization(NewFD, Previous))
  4699. NewFD->setInvalidDecl();
  4700. }
  4701. // Perform semantic checking on the function declaration.
  4702. if (!isDependentClassScopeExplicitSpecialization) {
  4703. if (NewFD->isInvalidDecl()) {
  4704. // If this is a class member, mark the class invalid immediately.
  4705. // This avoids some consistency errors later.
  4706. if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
  4707. methodDecl->getParent()->setInvalidDecl();
  4708. } else {
  4709. if (NewFD->isMain())
  4710. CheckMain(NewFD, D.getDeclSpec());
  4711. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  4712. isExplicitSpecialization));
  4713. }
  4714. }
  4715. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  4716. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  4717. "previous declaration set still overloaded");
  4718. if (NewFD->isConstexpr() && !NewFD->isInvalidDecl() &&
  4719. !CheckConstexprFunctionDecl(NewFD, CCK_Declaration))
  4720. NewFD->setInvalidDecl();
  4721. NamedDecl *PrincipalDecl = (FunctionTemplate
  4722. ? cast<NamedDecl>(FunctionTemplate)
  4723. : NewFD);
  4724. if (isFriend && D.isRedeclaration()) {
  4725. AccessSpecifier Access = AS_public;
  4726. if (!NewFD->isInvalidDecl())
  4727. Access = NewFD->getPreviousDecl()->getAccess();
  4728. NewFD->setAccess(Access);
  4729. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  4730. PrincipalDecl->setObjectOfFriendDecl(true);
  4731. }
  4732. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  4733. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  4734. PrincipalDecl->setNonMemberOperator();
  4735. // If we have a function template, check the template parameter
  4736. // list. This will check and merge default template arguments.
  4737. if (FunctionTemplate) {
  4738. FunctionTemplateDecl *PrevTemplate =
  4739. FunctionTemplate->getPreviousDecl();
  4740. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  4741. PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
  4742. D.getDeclSpec().isFriendSpecified()
  4743. ? (D.isFunctionDefinition()
  4744. ? TPC_FriendFunctionTemplateDefinition
  4745. : TPC_FriendFunctionTemplate)
  4746. : (D.getCXXScopeSpec().isSet() &&
  4747. DC && DC->isRecord() &&
  4748. DC->isDependentContext())
  4749. ? TPC_ClassTemplateMember
  4750. : TPC_FunctionTemplate);
  4751. }
  4752. if (NewFD->isInvalidDecl()) {
  4753. // Ignore all the rest of this.
  4754. } else if (!D.isRedeclaration()) {
  4755. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  4756. AddToScope };
  4757. // Fake up an access specifier if it's supposed to be a class member.
  4758. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  4759. NewFD->setAccess(AS_public);
  4760. // Qualified decls generally require a previous declaration.
  4761. if (D.getCXXScopeSpec().isSet()) {
  4762. // ...with the major exception of templated-scope or
  4763. // dependent-scope friend declarations.
  4764. // TODO: we currently also suppress this check in dependent
  4765. // contexts because (1) the parameter depth will be off when
  4766. // matching friend templates and (2) we might actually be
  4767. // selecting a friend based on a dependent factor. But there
  4768. // are situations where these conditions don't apply and we
  4769. // can actually do this check immediately.
  4770. if (isFriend &&
  4771. (TemplateParamLists.size() ||
  4772. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  4773. CurContext->isDependentContext())) {
  4774. // ignore these
  4775. } else {
  4776. // The user tried to provide an out-of-line definition for a
  4777. // function that is a member of a class or namespace, but there
  4778. // was no such member function declared (C++ [class.mfct]p2,
  4779. // C++ [namespace.memdef]p2). For example:
  4780. //
  4781. // class X {
  4782. // void f() const;
  4783. // };
  4784. //
  4785. // void X::f() { } // ill-formed
  4786. //
  4787. // Complain about this problem, and attempt to suggest close
  4788. // matches (e.g., those that differ only in cv-qualifiers and
  4789. // whether the parameter types are references).
  4790. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
  4791. NewFD,
  4792. ExtraArgs)) {
  4793. AddToScope = ExtraArgs.AddToScope;
  4794. return Result;
  4795. }
  4796. }
  4797. // Unqualified local friend declarations are required to resolve
  4798. // to something.
  4799. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  4800. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
  4801. NewFD,
  4802. ExtraArgs)) {
  4803. AddToScope = ExtraArgs.AddToScope;
  4804. return Result;
  4805. }
  4806. }
  4807. } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
  4808. !isFriend && !isFunctionTemplateSpecialization &&
  4809. !isExplicitSpecialization) {
  4810. // An out-of-line member function declaration must also be a
  4811. // definition (C++ [dcl.meaning]p1).
  4812. // Note that this is not the case for explicit specializations of
  4813. // function templates or member functions of class templates, per
  4814. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  4815. // extension for compatibility with old SWIG code which likes to
  4816. // generate them.
  4817. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  4818. << D.getCXXScopeSpec().getRange();
  4819. }
  4820. }
  4821. // Handle attributes. We need to have merged decls when handling attributes
  4822. // (for example to check for conflicts, etc).
  4823. // FIXME: This needs to happen before we merge declarations. Then,
  4824. // let attribute merging cope with attribute conflicts.
  4825. ProcessDeclAttributes(S, NewFD, D,
  4826. /*NonInheritable=*/false, /*Inheritable=*/true);
  4827. // attributes declared post-definition are currently ignored
  4828. // FIXME: This should happen during attribute merging
  4829. if (D.isRedeclaration() && Previous.isSingleResult()) {
  4830. const FunctionDecl *Def;
  4831. FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
  4832. if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) {
  4833. Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
  4834. Diag(Def->getLocation(), diag::note_previous_definition);
  4835. }
  4836. }
  4837. AddKnownFunctionAttributes(NewFD);
  4838. if (NewFD->hasAttr<OverloadableAttr>() &&
  4839. !NewFD->getType()->getAs<FunctionProtoType>()) {
  4840. Diag(NewFD->getLocation(),
  4841. diag::err_attribute_overloadable_no_prototype)
  4842. << NewFD;
  4843. // Turn this into a variadic function with no parameters.
  4844. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  4845. FunctionProtoType::ExtProtoInfo EPI;
  4846. EPI.Variadic = true;
  4847. EPI.ExtInfo = FT->getExtInfo();
  4848. QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
  4849. NewFD->setType(R);
  4850. }
  4851. // If there's a #pragma GCC visibility in scope, and this isn't a class
  4852. // member, set the visibility of this function.
  4853. if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
  4854. AddPushedVisibilityAttribute(NewFD);
  4855. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  4856. // marking the function.
  4857. AddCFAuditedAttribute(NewFD);
  4858. // If this is a locally-scoped extern C function, update the
  4859. // map of such names.
  4860. if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
  4861. && !NewFD->isInvalidDecl())
  4862. RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
  4863. // Set this FunctionDecl's range up to the right paren.
  4864. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  4865. if (getLangOptions().CPlusPlus) {
  4866. if (FunctionTemplate) {
  4867. if (NewFD->isInvalidDecl())
  4868. FunctionTemplate->setInvalidDecl();
  4869. return FunctionTemplate;
  4870. }
  4871. }
  4872. MarkUnusedFileScopedDecl(NewFD);
  4873. if (getLangOptions().CUDA)
  4874. if (IdentifierInfo *II = NewFD->getIdentifier())
  4875. if (!NewFD->isInvalidDecl() &&
  4876. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  4877. if (II->isStr("cudaConfigureCall")) {
  4878. if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
  4879. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  4880. Context.setcudaConfigureCallDecl(NewFD);
  4881. }
  4882. }
  4883. // Here we have an function template explicit specialization at class scope.
  4884. // The actually specialization will be postponed to template instatiation
  4885. // time via the ClassScopeFunctionSpecializationDecl node.
  4886. if (isDependentClassScopeExplicitSpecialization) {
  4887. ClassScopeFunctionSpecializationDecl *NewSpec =
  4888. ClassScopeFunctionSpecializationDecl::Create(
  4889. Context, CurContext, SourceLocation(),
  4890. cast<CXXMethodDecl>(NewFD));
  4891. CurContext->addDecl(NewSpec);
  4892. AddToScope = false;
  4893. }
  4894. return NewFD;
  4895. }
  4896. /// \brief Perform semantic checking of a new function declaration.
  4897. ///
  4898. /// Performs semantic analysis of the new function declaration
  4899. /// NewFD. This routine performs all semantic checking that does not
  4900. /// require the actual declarator involved in the declaration, and is
  4901. /// used both for the declaration of functions as they are parsed
  4902. /// (called via ActOnDeclarator) and for the declaration of functions
  4903. /// that have been instantiated via C++ template instantiation (called
  4904. /// via InstantiateDecl).
  4905. ///
  4906. /// \param IsExplicitSpecialiation whether this new function declaration is
  4907. /// an explicit specialization of the previous declaration.
  4908. ///
  4909. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  4910. ///
  4911. /// Returns true if the function declaration is a redeclaration.
  4912. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  4913. LookupResult &Previous,
  4914. bool IsExplicitSpecialization) {
  4915. assert(!NewFD->getResultType()->isVariablyModifiedType()
  4916. && "Variably modified return types are not handled here");
  4917. // Check for a previous declaration of this name.
  4918. if (Previous.empty() && NewFD->isExternC()) {
  4919. // Since we did not find anything by this name and we're declaring
  4920. // an extern "C" function, look for a non-visible extern "C"
  4921. // declaration with the same name.
  4922. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  4923. = findLocallyScopedExternalDecl(NewFD->getDeclName());
  4924. if (Pos != LocallyScopedExternalDecls.end())
  4925. Previous.addDecl(Pos->second);
  4926. }
  4927. bool Redeclaration = false;
  4928. // Merge or overload the declaration with an existing declaration of
  4929. // the same name, if appropriate.
  4930. if (!Previous.empty()) {
  4931. // Determine whether NewFD is an overload of PrevDecl or
  4932. // a declaration that requires merging. If it's an overload,
  4933. // there's no more work to do here; we'll just add the new
  4934. // function to the scope.
  4935. NamedDecl *OldDecl = 0;
  4936. if (!AllowOverloadingOfFunction(Previous, Context)) {
  4937. Redeclaration = true;
  4938. OldDecl = Previous.getFoundDecl();
  4939. } else {
  4940. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  4941. /*NewIsUsingDecl*/ false)) {
  4942. case Ovl_Match:
  4943. Redeclaration = true;
  4944. break;
  4945. case Ovl_NonFunction:
  4946. Redeclaration = true;
  4947. break;
  4948. case Ovl_Overload:
  4949. Redeclaration = false;
  4950. break;
  4951. }
  4952. if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  4953. // If a function name is overloadable in C, then every function
  4954. // with that name must be marked "overloadable".
  4955. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  4956. << Redeclaration << NewFD;
  4957. NamedDecl *OverloadedDecl = 0;
  4958. if (Redeclaration)
  4959. OverloadedDecl = OldDecl;
  4960. else if (!Previous.empty())
  4961. OverloadedDecl = Previous.getRepresentativeDecl();
  4962. if (OverloadedDecl)
  4963. Diag(OverloadedDecl->getLocation(),
  4964. diag::note_attribute_overloadable_prev_overload);
  4965. NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
  4966. Context));
  4967. }
  4968. }
  4969. if (Redeclaration) {
  4970. // NewFD and OldDecl represent declarations that need to be
  4971. // merged.
  4972. if (MergeFunctionDecl(NewFD, OldDecl)) {
  4973. NewFD->setInvalidDecl();
  4974. return Redeclaration;
  4975. }
  4976. Previous.clear();
  4977. Previous.addDecl(OldDecl);
  4978. if (FunctionTemplateDecl *OldTemplateDecl
  4979. = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  4980. NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
  4981. FunctionTemplateDecl *NewTemplateDecl
  4982. = NewFD->getDescribedFunctionTemplate();
  4983. assert(NewTemplateDecl && "Template/non-template mismatch");
  4984. if (CXXMethodDecl *Method
  4985. = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
  4986. Method->setAccess(OldTemplateDecl->getAccess());
  4987. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  4988. }
  4989. // If this is an explicit specialization of a member that is a function
  4990. // template, mark it as a member specialization.
  4991. if (IsExplicitSpecialization &&
  4992. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  4993. NewTemplateDecl->setMemberSpecialization();
  4994. assert(OldTemplateDecl->isMemberSpecialization());
  4995. }
  4996. } else {
  4997. if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
  4998. NewFD->setAccess(OldDecl->getAccess());
  4999. NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
  5000. }
  5001. }
  5002. }
  5003. // Semantic checking for this function declaration (in isolation).
  5004. if (getLangOptions().CPlusPlus) {
  5005. // C++-specific checks.
  5006. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  5007. CheckConstructor(Constructor);
  5008. } else if (CXXDestructorDecl *Destructor =
  5009. dyn_cast<CXXDestructorDecl>(NewFD)) {
  5010. CXXRecordDecl *Record = Destructor->getParent();
  5011. QualType ClassType = Context.getTypeDeclType(Record);
  5012. // FIXME: Shouldn't we be able to perform this check even when the class
  5013. // type is dependent? Both gcc and edg can handle that.
  5014. if (!ClassType->isDependentType()) {
  5015. DeclarationName Name
  5016. = Context.DeclarationNames.getCXXDestructorName(
  5017. Context.getCanonicalType(ClassType));
  5018. if (NewFD->getDeclName() != Name) {
  5019. Diag(NewFD->getLocation(), diag::err_destructor_name);
  5020. NewFD->setInvalidDecl();
  5021. return Redeclaration;
  5022. }
  5023. }
  5024. } else if (CXXConversionDecl *Conversion
  5025. = dyn_cast<CXXConversionDecl>(NewFD)) {
  5026. ActOnConversionDeclarator(Conversion);
  5027. }
  5028. // Find any virtual functions that this function overrides.
  5029. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  5030. if (!Method->isFunctionTemplateSpecialization() &&
  5031. !Method->getDescribedFunctionTemplate()) {
  5032. if (AddOverriddenMethods(Method->getParent(), Method)) {
  5033. // If the function was marked as "static", we have a problem.
  5034. if (NewFD->getStorageClass() == SC_Static) {
  5035. Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
  5036. << NewFD->getDeclName();
  5037. for (CXXMethodDecl::method_iterator
  5038. Overridden = Method->begin_overridden_methods(),
  5039. OverriddenEnd = Method->end_overridden_methods();
  5040. Overridden != OverriddenEnd;
  5041. ++Overridden) {
  5042. Diag((*Overridden)->getLocation(),
  5043. diag::note_overridden_virtual_function);
  5044. }
  5045. }
  5046. }
  5047. }
  5048. }
  5049. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  5050. if (NewFD->isOverloadedOperator() &&
  5051. CheckOverloadedOperatorDeclaration(NewFD)) {
  5052. NewFD->setInvalidDecl();
  5053. return Redeclaration;
  5054. }
  5055. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  5056. if (NewFD->getLiteralIdentifier() &&
  5057. CheckLiteralOperatorDeclaration(NewFD)) {
  5058. NewFD->setInvalidDecl();
  5059. return Redeclaration;
  5060. }
  5061. // In C++, check default arguments now that we have merged decls. Unless
  5062. // the lexical context is the class, because in this case this is done
  5063. // during delayed parsing anyway.
  5064. if (!CurContext->isRecord())
  5065. CheckCXXDefaultArguments(NewFD);
  5066. // If this function declares a builtin function, check the type of this
  5067. // declaration against the expected type for the builtin.
  5068. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  5069. ASTContext::GetBuiltinTypeError Error;
  5070. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  5071. if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
  5072. // The type of this function differs from the type of the builtin,
  5073. // so forget about the builtin entirely.
  5074. Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
  5075. }
  5076. }
  5077. }
  5078. return Redeclaration;
  5079. }
  5080. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  5081. // C++11 [basic.start.main]p3: A program that declares main to be inline,
  5082. // static or constexpr is ill-formed.
  5083. // C99 6.7.4p4: In a hosted environment, the inline function specifier
  5084. // shall not appear in a declaration of main.
  5085. // static main is not an error under C99, but we should warn about it.
  5086. if (FD->getStorageClass() == SC_Static)
  5087. Diag(DS.getStorageClassSpecLoc(), getLangOptions().CPlusPlus
  5088. ? diag::err_static_main : diag::warn_static_main)
  5089. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  5090. if (FD->isInlineSpecified())
  5091. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  5092. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  5093. if (FD->isConstexpr()) {
  5094. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  5095. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  5096. FD->setConstexpr(false);
  5097. }
  5098. QualType T = FD->getType();
  5099. assert(T->isFunctionType() && "function decl is not of function type");
  5100. const FunctionType* FT = T->getAs<FunctionType>();
  5101. if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
  5102. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
  5103. FD->setInvalidDecl(true);
  5104. }
  5105. // Treat protoless main() as nullary.
  5106. if (isa<FunctionNoProtoType>(FT)) return;
  5107. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  5108. unsigned nparams = FTP->getNumArgs();
  5109. assert(FD->getNumParams() == nparams);
  5110. bool HasExtraParameters = (nparams > 3);
  5111. // Darwin passes an undocumented fourth argument of type char**. If
  5112. // other platforms start sprouting these, the logic below will start
  5113. // getting shifty.
  5114. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  5115. HasExtraParameters = false;
  5116. if (HasExtraParameters) {
  5117. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  5118. FD->setInvalidDecl(true);
  5119. nparams = 3;
  5120. }
  5121. // FIXME: a lot of the following diagnostics would be improved
  5122. // if we had some location information about types.
  5123. QualType CharPP =
  5124. Context.getPointerType(Context.getPointerType(Context.CharTy));
  5125. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  5126. for (unsigned i = 0; i < nparams; ++i) {
  5127. QualType AT = FTP->getArgType(i);
  5128. bool mismatch = true;
  5129. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  5130. mismatch = false;
  5131. else if (Expected[i] == CharPP) {
  5132. // As an extension, the following forms are okay:
  5133. // char const **
  5134. // char const * const *
  5135. // char * const *
  5136. QualifierCollector qs;
  5137. const PointerType* PT;
  5138. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  5139. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  5140. (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
  5141. qs.removeConst();
  5142. mismatch = !qs.empty();
  5143. }
  5144. }
  5145. if (mismatch) {
  5146. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  5147. // TODO: suggest replacing given type with expected type
  5148. FD->setInvalidDecl(true);
  5149. }
  5150. }
  5151. if (nparams == 1 && !FD->isInvalidDecl()) {
  5152. Diag(FD->getLocation(), diag::warn_main_one_arg);
  5153. }
  5154. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  5155. Diag(FD->getLocation(), diag::err_main_template_decl);
  5156. FD->setInvalidDecl();
  5157. }
  5158. }
  5159. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  5160. // FIXME: Need strict checking. In C89, we need to check for
  5161. // any assignment, increment, decrement, function-calls, or
  5162. // commas outside of a sizeof. In C99, it's the same list,
  5163. // except that the aforementioned are allowed in unevaluated
  5164. // expressions. Everything else falls under the
  5165. // "may accept other forms of constant expressions" exception.
  5166. // (We never end up here for C++, so the constant expression
  5167. // rules there don't matter.)
  5168. if (Init->isConstantInitializer(Context, false))
  5169. return false;
  5170. Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
  5171. << Init->getSourceRange();
  5172. return true;
  5173. }
  5174. namespace {
  5175. // Visits an initialization expression to see if OrigDecl is evaluated in
  5176. // its own initialization and throws a warning if it does.
  5177. class SelfReferenceChecker
  5178. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  5179. Sema &S;
  5180. Decl *OrigDecl;
  5181. bool isRecordType;
  5182. bool isPODType;
  5183. public:
  5184. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  5185. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  5186. S(S), OrigDecl(OrigDecl) {
  5187. isPODType = false;
  5188. isRecordType = false;
  5189. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  5190. isPODType = VD->getType().isPODType(S.Context);
  5191. isRecordType = VD->getType()->isRecordType();
  5192. }
  5193. }
  5194. void VisitExpr(Expr *E) {
  5195. if (isa<ObjCMessageExpr>(*E)) return;
  5196. if (isRecordType) {
  5197. Expr *expr = E;
  5198. if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  5199. ValueDecl *VD = ME->getMemberDecl();
  5200. if (isa<EnumConstantDecl>(VD) || isa<VarDecl>(VD)) return;
  5201. expr = ME->getBase();
  5202. }
  5203. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(expr)) {
  5204. HandleDeclRefExpr(DRE);
  5205. return;
  5206. }
  5207. }
  5208. Inherited::VisitExpr(E);
  5209. }
  5210. void VisitMemberExpr(MemberExpr *E) {
  5211. if (E->getType()->canDecayToPointerType()) return;
  5212. if (isa<FieldDecl>(E->getMemberDecl()))
  5213. if (DeclRefExpr *DRE
  5214. = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) {
  5215. HandleDeclRefExpr(DRE);
  5216. return;
  5217. }
  5218. Inherited::VisitMemberExpr(E);
  5219. }
  5220. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  5221. if ((!isRecordType &&E->getCastKind() == CK_LValueToRValue) ||
  5222. (isRecordType && E->getCastKind() == CK_NoOp)) {
  5223. Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts();
  5224. if (MemberExpr *ME = dyn_cast<MemberExpr>(SubExpr))
  5225. SubExpr = ME->getBase()->IgnoreParenImpCasts();
  5226. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
  5227. HandleDeclRefExpr(DRE);
  5228. return;
  5229. }
  5230. }
  5231. Inherited::VisitImplicitCastExpr(E);
  5232. }
  5233. void VisitUnaryOperator(UnaryOperator *E) {
  5234. // For POD record types, addresses of its own members are well-defined.
  5235. if (isRecordType && isPODType) return;
  5236. Inherited::VisitUnaryOperator(E);
  5237. }
  5238. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  5239. Decl* ReferenceDecl = DRE->getDecl();
  5240. if (OrigDecl != ReferenceDecl) return;
  5241. LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
  5242. Sema::NotForRedeclaration);
  5243. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  5244. S.PDiag(diag::warn_uninit_self_reference_in_init)
  5245. << Result.getLookupName()
  5246. << OrigDecl->getLocation()
  5247. << DRE->getSourceRange());
  5248. }
  5249. };
  5250. }
  5251. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  5252. void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) {
  5253. SelfReferenceChecker(*this, OrigDecl).VisitExpr(E);
  5254. }
  5255. /// AddInitializerToDecl - Adds the initializer Init to the
  5256. /// declaration dcl. If DirectInit is true, this is C++ direct
  5257. /// initialization rather than copy initialization.
  5258. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
  5259. bool DirectInit, bool TypeMayContainAuto) {
  5260. // If there is no declaration, there was an error parsing it. Just ignore
  5261. // the initializer.
  5262. if (RealDecl == 0 || RealDecl->isInvalidDecl())
  5263. return;
  5264. // Check for self-references within variable initializers.
  5265. if (VarDecl *vd = dyn_cast<VarDecl>(RealDecl)) {
  5266. // Variables declared within a function/method body are handled
  5267. // by a dataflow analysis.
  5268. if (!vd->hasLocalStorage() && !vd->isStaticLocal())
  5269. CheckSelfReference(RealDecl, Init);
  5270. }
  5271. else {
  5272. CheckSelfReference(RealDecl, Init);
  5273. }
  5274. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  5275. // With declarators parsed the way they are, the parser cannot
  5276. // distinguish between a normal initializer and a pure-specifier.
  5277. // Thus this grotesque test.
  5278. IntegerLiteral *IL;
  5279. if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
  5280. Context.getCanonicalType(IL->getType()) == Context.IntTy)
  5281. CheckPureMethod(Method, Init->getSourceRange());
  5282. else {
  5283. Diag(Method->getLocation(), diag::err_member_function_initialization)
  5284. << Method->getDeclName() << Init->getSourceRange();
  5285. Method->setInvalidDecl();
  5286. }
  5287. return;
  5288. }
  5289. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  5290. if (!VDecl) {
  5291. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  5292. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  5293. RealDecl->setInvalidDecl();
  5294. return;
  5295. }
  5296. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  5297. if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
  5298. TypeSourceInfo *DeducedType = 0;
  5299. if (DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType) ==
  5300. DAR_Failed)
  5301. DiagnoseAutoDeductionFailure(VDecl, Init);
  5302. if (!DeducedType) {
  5303. RealDecl->setInvalidDecl();
  5304. return;
  5305. }
  5306. VDecl->setTypeSourceInfo(DeducedType);
  5307. VDecl->setType(DeducedType->getType());
  5308. // In ARC, infer lifetime.
  5309. if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  5310. VDecl->setInvalidDecl();
  5311. // If this is a redeclaration, check that the type we just deduced matches
  5312. // the previously declared type.
  5313. if (VarDecl *Old = VDecl->getPreviousDecl())
  5314. MergeVarDeclTypes(VDecl, Old);
  5315. }
  5316. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  5317. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  5318. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  5319. VDecl->setInvalidDecl();
  5320. return;
  5321. }
  5322. // A definition must end up with a complete type, which means it must be
  5323. // complete with the restriction that an array type might be completed by the
  5324. // initializer; note that later code assumes this restriction.
  5325. QualType BaseDeclType = VDecl->getType();
  5326. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  5327. BaseDeclType = Array->getElementType();
  5328. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  5329. diag::err_typecheck_decl_incomplete_type)) {
  5330. RealDecl->setInvalidDecl();
  5331. return;
  5332. }
  5333. // The variable can not have an abstract class type.
  5334. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  5335. diag::err_abstract_type_in_decl,
  5336. AbstractVariableType))
  5337. VDecl->setInvalidDecl();
  5338. const VarDecl *Def;
  5339. if ((Def = VDecl->getDefinition()) && Def != VDecl) {
  5340. Diag(VDecl->getLocation(), diag::err_redefinition)
  5341. << VDecl->getDeclName();
  5342. Diag(Def->getLocation(), diag::note_previous_definition);
  5343. VDecl->setInvalidDecl();
  5344. return;
  5345. }
  5346. const VarDecl* PrevInit = 0;
  5347. if (getLangOptions().CPlusPlus) {
  5348. // C++ [class.static.data]p4
  5349. // If a static data member is of const integral or const
  5350. // enumeration type, its declaration in the class definition can
  5351. // specify a constant-initializer which shall be an integral
  5352. // constant expression (5.19). In that case, the member can appear
  5353. // in integral constant expressions. The member shall still be
  5354. // defined in a namespace scope if it is used in the program and the
  5355. // namespace scope definition shall not contain an initializer.
  5356. //
  5357. // We already performed a redefinition check above, but for static
  5358. // data members we also need to check whether there was an in-class
  5359. // declaration with an initializer.
  5360. if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
  5361. Diag(VDecl->getLocation(), diag::err_redefinition)
  5362. << VDecl->getDeclName();
  5363. Diag(PrevInit->getLocation(), diag::note_previous_definition);
  5364. return;
  5365. }
  5366. if (VDecl->hasLocalStorage())
  5367. getCurFunction()->setHasBranchProtectedScope();
  5368. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  5369. VDecl->setInvalidDecl();
  5370. return;
  5371. }
  5372. }
  5373. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  5374. // a kernel function cannot be initialized."
  5375. if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
  5376. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  5377. VDecl->setInvalidDecl();
  5378. return;
  5379. }
  5380. // Get the decls type and save a reference for later, since
  5381. // CheckInitializerTypes may change it.
  5382. QualType DclT = VDecl->getType(), SavT = DclT;
  5383. // Perform the initialization.
  5384. if (!VDecl->isInvalidDecl()) {
  5385. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  5386. InitializationKind Kind
  5387. = DirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
  5388. Init->getLocStart(),
  5389. Init->getLocEnd())
  5390. : InitializationKind::CreateCopy(VDecl->getLocation(),
  5391. Init->getLocStart());
  5392. InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
  5393. ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
  5394. MultiExprArg(*this, &Init, 1),
  5395. &DclT);
  5396. if (Result.isInvalid()) {
  5397. VDecl->setInvalidDecl();
  5398. return;
  5399. }
  5400. Init = Result.takeAs<Expr>();
  5401. }
  5402. // If the type changed, it means we had an incomplete type that was
  5403. // completed by the initializer. For example:
  5404. // int ary[] = { 1, 3, 5 };
  5405. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  5406. if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
  5407. VDecl->setType(DclT);
  5408. Init->setType(DclT.getNonReferenceType());
  5409. }
  5410. // Check any implicit conversions within the expression.
  5411. CheckImplicitConversions(Init, VDecl->getLocation());
  5412. if (!VDecl->isInvalidDecl())
  5413. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  5414. Init = MaybeCreateExprWithCleanups(Init);
  5415. // Attach the initializer to the decl.
  5416. VDecl->setInit(Init);
  5417. if (VDecl->isLocalVarDecl()) {
  5418. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  5419. // static storage duration shall be constant expressions or string literals.
  5420. // C++ does not have this restriction.
  5421. if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl() &&
  5422. VDecl->getStorageClass() == SC_Static)
  5423. CheckForConstantInitializer(Init, DclT);
  5424. } else if (VDecl->isStaticDataMember() &&
  5425. VDecl->getLexicalDeclContext()->isRecord()) {
  5426. // This is an in-class initialization for a static data member, e.g.,
  5427. //
  5428. // struct S {
  5429. // static const int value = 17;
  5430. // };
  5431. // C++ [class.mem]p4:
  5432. // A member-declarator can contain a constant-initializer only
  5433. // if it declares a static member (9.4) of const integral or
  5434. // const enumeration type, see 9.4.2.
  5435. //
  5436. // C++11 [class.static.data]p3:
  5437. // If a non-volatile const static data member is of integral or
  5438. // enumeration type, its declaration in the class definition can
  5439. // specify a brace-or-equal-initializer in which every initalizer-clause
  5440. // that is an assignment-expression is a constant expression. A static
  5441. // data member of literal type can be declared in the class definition
  5442. // with the constexpr specifier; if so, its declaration shall specify a
  5443. // brace-or-equal-initializer in which every initializer-clause that is
  5444. // an assignment-expression is a constant expression.
  5445. // Do nothing on dependent types.
  5446. if (DclT->isDependentType()) {
  5447. // Allow any 'static constexpr' members, whether or not they are of literal
  5448. // type. We separately check that the initializer is a constant expression,
  5449. // which implicitly requires the member to be of literal type.
  5450. } else if (VDecl->isConstexpr()) {
  5451. // Require constness.
  5452. } else if (!DclT.isConstQualified()) {
  5453. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  5454. << Init->getSourceRange();
  5455. VDecl->setInvalidDecl();
  5456. // We allow integer constant expressions in all cases.
  5457. } else if (DclT->isIntegralOrEnumerationType()) {
  5458. // Check whether the expression is a constant expression.
  5459. SourceLocation Loc;
  5460. if (getLangOptions().CPlusPlus0x && DclT.isVolatileQualified())
  5461. // In C++11, a non-constexpr const static data member with an
  5462. // in-class initializer cannot be volatile.
  5463. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  5464. else if (Init->isValueDependent())
  5465. ; // Nothing to check.
  5466. else if (Init->isIntegerConstantExpr(Context, &Loc))
  5467. ; // Ok, it's an ICE!
  5468. else if (Init->isEvaluatable(Context)) {
  5469. // If we can constant fold the initializer through heroics, accept it,
  5470. // but report this as a use of an extension for -pedantic.
  5471. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  5472. << Init->getSourceRange();
  5473. } else {
  5474. // Otherwise, this is some crazy unknown case. Report the issue at the
  5475. // location provided by the isIntegerConstantExpr failed check.
  5476. Diag(Loc, diag::err_in_class_initializer_non_constant)
  5477. << Init->getSourceRange();
  5478. VDecl->setInvalidDecl();
  5479. }
  5480. // We allow foldable floating-point constants as an extension.
  5481. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  5482. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  5483. << DclT << Init->getSourceRange();
  5484. if (getLangOptions().CPlusPlus0x)
  5485. Diag(VDecl->getLocation(),
  5486. diag::note_in_class_initializer_float_type_constexpr)
  5487. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  5488. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  5489. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  5490. << Init->getSourceRange();
  5491. VDecl->setInvalidDecl();
  5492. }
  5493. // Suggest adding 'constexpr' in C++11 for literal types.
  5494. } else if (getLangOptions().CPlusPlus0x && DclT->isLiteralType()) {
  5495. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  5496. << DclT << Init->getSourceRange()
  5497. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  5498. VDecl->setConstexpr(true);
  5499. } else {
  5500. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  5501. << DclT << Init->getSourceRange();
  5502. VDecl->setInvalidDecl();
  5503. }
  5504. } else if (VDecl->isFileVarDecl()) {
  5505. if (VDecl->getStorageClassAsWritten() == SC_Extern &&
  5506. (!getLangOptions().CPlusPlus ||
  5507. !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
  5508. Diag(VDecl->getLocation(), diag::warn_extern_init);
  5509. // C99 6.7.8p4. All file scoped initializers need to be constant.
  5510. if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl())
  5511. CheckForConstantInitializer(Init, DclT);
  5512. }
  5513. CheckCompleteVariableDeclaration(VDecl);
  5514. }
  5515. /// ActOnInitializerError - Given that there was an error parsing an
  5516. /// initializer for the given declaration, try to return to some form
  5517. /// of sanity.
  5518. void Sema::ActOnInitializerError(Decl *D) {
  5519. // Our main concern here is re-establishing invariants like "a
  5520. // variable's type is either dependent or complete".
  5521. if (!D || D->isInvalidDecl()) return;
  5522. VarDecl *VD = dyn_cast<VarDecl>(D);
  5523. if (!VD) return;
  5524. // Auto types are meaningless if we can't make sense of the initializer.
  5525. if (ParsingInitForAutoVars.count(D)) {
  5526. D->setInvalidDecl();
  5527. return;
  5528. }
  5529. QualType Ty = VD->getType();
  5530. if (Ty->isDependentType()) return;
  5531. // Require a complete type.
  5532. if (RequireCompleteType(VD->getLocation(),
  5533. Context.getBaseElementType(Ty),
  5534. diag::err_typecheck_decl_incomplete_type)) {
  5535. VD->setInvalidDecl();
  5536. return;
  5537. }
  5538. // Require an abstract type.
  5539. if (RequireNonAbstractType(VD->getLocation(), Ty,
  5540. diag::err_abstract_type_in_decl,
  5541. AbstractVariableType)) {
  5542. VD->setInvalidDecl();
  5543. return;
  5544. }
  5545. // Don't bother complaining about constructors or destructors,
  5546. // though.
  5547. }
  5548. void Sema::ActOnUninitializedDecl(Decl *RealDecl,
  5549. bool TypeMayContainAuto) {
  5550. // If there is no declaration, there was an error parsing it. Just ignore it.
  5551. if (RealDecl == 0)
  5552. return;
  5553. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  5554. QualType Type = Var->getType();
  5555. // C++11 [dcl.spec.auto]p3
  5556. if (TypeMayContainAuto && Type->getContainedAutoType()) {
  5557. Diag(Var->getLocation(), diag::err_auto_var_requires_init)
  5558. << Var->getDeclName() << Type;
  5559. Var->setInvalidDecl();
  5560. return;
  5561. }
  5562. // C++11 [class.static.data]p3: A static data member can be declared with
  5563. // the constexpr specifier; if so, its declaration shall specify
  5564. // a brace-or-equal-initializer.
  5565. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  5566. // the definition of a variable [...] or the declaration of a static data
  5567. // member.
  5568. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
  5569. if (Var->isStaticDataMember())
  5570. Diag(Var->getLocation(),
  5571. diag::err_constexpr_static_mem_var_requires_init)
  5572. << Var->getDeclName();
  5573. else
  5574. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  5575. Var->setInvalidDecl();
  5576. return;
  5577. }
  5578. switch (Var->isThisDeclarationADefinition()) {
  5579. case VarDecl::Definition:
  5580. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  5581. break;
  5582. // We have an out-of-line definition of a static data member
  5583. // that has an in-class initializer, so we type-check this like
  5584. // a declaration.
  5585. //
  5586. // Fall through
  5587. case VarDecl::DeclarationOnly:
  5588. // It's only a declaration.
  5589. // Block scope. C99 6.7p7: If an identifier for an object is
  5590. // declared with no linkage (C99 6.2.2p6), the type for the
  5591. // object shall be complete.
  5592. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  5593. !Var->getLinkage() && !Var->isInvalidDecl() &&
  5594. RequireCompleteType(Var->getLocation(), Type,
  5595. diag::err_typecheck_decl_incomplete_type))
  5596. Var->setInvalidDecl();
  5597. // Make sure that the type is not abstract.
  5598. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  5599. RequireNonAbstractType(Var->getLocation(), Type,
  5600. diag::err_abstract_type_in_decl,
  5601. AbstractVariableType))
  5602. Var->setInvalidDecl();
  5603. return;
  5604. case VarDecl::TentativeDefinition:
  5605. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  5606. // object that has file scope without an initializer, and without a
  5607. // storage-class specifier or with the storage-class specifier "static",
  5608. // constitutes a tentative definition. Note: A tentative definition with
  5609. // external linkage is valid (C99 6.2.2p5).
  5610. if (!Var->isInvalidDecl()) {
  5611. if (const IncompleteArrayType *ArrayT
  5612. = Context.getAsIncompleteArrayType(Type)) {
  5613. if (RequireCompleteType(Var->getLocation(),
  5614. ArrayT->getElementType(),
  5615. diag::err_illegal_decl_array_incomplete_type))
  5616. Var->setInvalidDecl();
  5617. } else if (Var->getStorageClass() == SC_Static) {
  5618. // C99 6.9.2p3: If the declaration of an identifier for an object is
  5619. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  5620. // declared type shall not be an incomplete type.
  5621. // NOTE: code such as the following
  5622. // static struct s;
  5623. // struct s { int a; };
  5624. // is accepted by gcc. Hence here we issue a warning instead of
  5625. // an error and we do not invalidate the static declaration.
  5626. // NOTE: to avoid multiple warnings, only check the first declaration.
  5627. if (Var->getPreviousDecl() == 0)
  5628. RequireCompleteType(Var->getLocation(), Type,
  5629. diag::ext_typecheck_decl_incomplete_type);
  5630. }
  5631. }
  5632. // Record the tentative definition; we're done.
  5633. if (!Var->isInvalidDecl())
  5634. TentativeDefinitions.push_back(Var);
  5635. return;
  5636. }
  5637. // Provide a specific diagnostic for uninitialized variable
  5638. // definitions with incomplete array type.
  5639. if (Type->isIncompleteArrayType()) {
  5640. Diag(Var->getLocation(),
  5641. diag::err_typecheck_incomplete_array_needs_initializer);
  5642. Var->setInvalidDecl();
  5643. return;
  5644. }
  5645. // Provide a specific diagnostic for uninitialized variable
  5646. // definitions with reference type.
  5647. if (Type->isReferenceType()) {
  5648. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  5649. << Var->getDeclName()
  5650. << SourceRange(Var->getLocation(), Var->getLocation());
  5651. Var->setInvalidDecl();
  5652. return;
  5653. }
  5654. // Do not attempt to type-check the default initializer for a
  5655. // variable with dependent type.
  5656. if (Type->isDependentType())
  5657. return;
  5658. if (Var->isInvalidDecl())
  5659. return;
  5660. if (RequireCompleteType(Var->getLocation(),
  5661. Context.getBaseElementType(Type),
  5662. diag::err_typecheck_decl_incomplete_type)) {
  5663. Var->setInvalidDecl();
  5664. return;
  5665. }
  5666. // The variable can not have an abstract class type.
  5667. if (RequireNonAbstractType(Var->getLocation(), Type,
  5668. diag::err_abstract_type_in_decl,
  5669. AbstractVariableType)) {
  5670. Var->setInvalidDecl();
  5671. return;
  5672. }
  5673. // Check for jumps past the implicit initializer. C++0x
  5674. // clarifies that this applies to a "variable with automatic
  5675. // storage duration", not a "local variable".
  5676. // C++11 [stmt.dcl]p3
  5677. // A program that jumps from a point where a variable with automatic
  5678. // storage duration is not in scope to a point where it is in scope is
  5679. // ill-formed unless the variable has scalar type, class type with a
  5680. // trivial default constructor and a trivial destructor, a cv-qualified
  5681. // version of one of these types, or an array of one of the preceding
  5682. // types and is declared without an initializer.
  5683. if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) {
  5684. if (const RecordType *Record
  5685. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  5686. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  5687. // Mark the function for further checking even if the looser rules of
  5688. // C++11 do not require such checks, so that we can diagnose
  5689. // incompatibilities with C++98.
  5690. if (!CXXRecord->isPOD())
  5691. getCurFunction()->setHasBranchProtectedScope();
  5692. }
  5693. }
  5694. // C++03 [dcl.init]p9:
  5695. // If no initializer is specified for an object, and the
  5696. // object is of (possibly cv-qualified) non-POD class type (or
  5697. // array thereof), the object shall be default-initialized; if
  5698. // the object is of const-qualified type, the underlying class
  5699. // type shall have a user-declared default
  5700. // constructor. Otherwise, if no initializer is specified for
  5701. // a non- static object, the object and its subobjects, if
  5702. // any, have an indeterminate initial value); if the object
  5703. // or any of its subobjects are of const-qualified type, the
  5704. // program is ill-formed.
  5705. // C++0x [dcl.init]p11:
  5706. // If no initializer is specified for an object, the object is
  5707. // default-initialized; [...].
  5708. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  5709. InitializationKind Kind
  5710. = InitializationKind::CreateDefault(Var->getLocation());
  5711. InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
  5712. ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
  5713. MultiExprArg(*this, 0, 0));
  5714. if (Init.isInvalid())
  5715. Var->setInvalidDecl();
  5716. else if (Init.get())
  5717. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  5718. CheckCompleteVariableDeclaration(Var);
  5719. }
  5720. }
  5721. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  5722. VarDecl *VD = dyn_cast<VarDecl>(D);
  5723. if (!VD) {
  5724. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  5725. D->setInvalidDecl();
  5726. return;
  5727. }
  5728. VD->setCXXForRangeDecl(true);
  5729. // for-range-declaration cannot be given a storage class specifier.
  5730. int Error = -1;
  5731. switch (VD->getStorageClassAsWritten()) {
  5732. case SC_None:
  5733. break;
  5734. case SC_Extern:
  5735. Error = 0;
  5736. break;
  5737. case SC_Static:
  5738. Error = 1;
  5739. break;
  5740. case SC_PrivateExtern:
  5741. Error = 2;
  5742. break;
  5743. case SC_Auto:
  5744. Error = 3;
  5745. break;
  5746. case SC_Register:
  5747. Error = 4;
  5748. break;
  5749. case SC_OpenCLWorkGroupLocal:
  5750. llvm_unreachable("Unexpected storage class");
  5751. }
  5752. if (VD->isConstexpr())
  5753. Error = 5;
  5754. if (Error != -1) {
  5755. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  5756. << VD->getDeclName() << Error;
  5757. D->setInvalidDecl();
  5758. }
  5759. }
  5760. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  5761. if (var->isInvalidDecl()) return;
  5762. // In ARC, don't allow jumps past the implicit initialization of a
  5763. // local retaining variable.
  5764. if (getLangOptions().ObjCAutoRefCount &&
  5765. var->hasLocalStorage()) {
  5766. switch (var->getType().getObjCLifetime()) {
  5767. case Qualifiers::OCL_None:
  5768. case Qualifiers::OCL_ExplicitNone:
  5769. case Qualifiers::OCL_Autoreleasing:
  5770. break;
  5771. case Qualifiers::OCL_Weak:
  5772. case Qualifiers::OCL_Strong:
  5773. getCurFunction()->setHasBranchProtectedScope();
  5774. break;
  5775. }
  5776. }
  5777. // All the following checks are C++ only.
  5778. if (!getLangOptions().CPlusPlus) return;
  5779. QualType baseType = Context.getBaseElementType(var->getType());
  5780. if (baseType->isDependentType()) return;
  5781. // __block variables might require us to capture a copy-initializer.
  5782. if (var->hasAttr<BlocksAttr>()) {
  5783. // It's currently invalid to ever have a __block variable with an
  5784. // array type; should we diagnose that here?
  5785. // Regardless, we don't want to ignore array nesting when
  5786. // constructing this copy.
  5787. QualType type = var->getType();
  5788. if (type->isStructureOrClassType()) {
  5789. SourceLocation poi = var->getLocation();
  5790. Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi);
  5791. ExprResult result =
  5792. PerformCopyInitialization(
  5793. InitializedEntity::InitializeBlock(poi, type, false),
  5794. poi, Owned(varRef));
  5795. if (!result.isInvalid()) {
  5796. result = MaybeCreateExprWithCleanups(result);
  5797. Expr *init = result.takeAs<Expr>();
  5798. Context.setBlockVarCopyInits(var, init);
  5799. }
  5800. }
  5801. }
  5802. Expr *Init = var->getInit();
  5803. bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
  5804. if (!var->getDeclContext()->isDependentContext() && Init) {
  5805. if (IsGlobal && !var->isConstexpr() &&
  5806. getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
  5807. var->getLocation())
  5808. != DiagnosticsEngine::Ignored &&
  5809. !Init->isConstantInitializer(Context, baseType->isReferenceType()))
  5810. Diag(var->getLocation(), diag::warn_global_constructor)
  5811. << Init->getSourceRange();
  5812. if (var->isConstexpr()) {
  5813. llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
  5814. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  5815. SourceLocation DiagLoc = var->getLocation();
  5816. // If the note doesn't add any useful information other than a source
  5817. // location, fold it into the primary diagnostic.
  5818. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  5819. diag::note_invalid_subexpr_in_const_expr) {
  5820. DiagLoc = Notes[0].first;
  5821. Notes.clear();
  5822. }
  5823. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  5824. << var << Init->getSourceRange();
  5825. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  5826. Diag(Notes[I].first, Notes[I].second);
  5827. }
  5828. } else if (var->isUsableInConstantExpressions()) {
  5829. // Check whether the initializer of a const variable of integral or
  5830. // enumeration type is an ICE now, since we can't tell whether it was
  5831. // initialized by a constant expression if we check later.
  5832. var->checkInitIsICE();
  5833. }
  5834. }
  5835. // Require the destructor.
  5836. if (const RecordType *recordType = baseType->getAs<RecordType>())
  5837. FinalizeVarWithDestructor(var, recordType);
  5838. }
  5839. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  5840. /// any semantic actions necessary after any initializer has been attached.
  5841. void
  5842. Sema::FinalizeDeclaration(Decl *ThisDecl) {
  5843. // Note that we are no longer parsing the initializer for this declaration.
  5844. ParsingInitForAutoVars.erase(ThisDecl);
  5845. }
  5846. Sema::DeclGroupPtrTy
  5847. Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  5848. Decl **Group, unsigned NumDecls) {
  5849. SmallVector<Decl*, 8> Decls;
  5850. if (DS.isTypeSpecOwned())
  5851. Decls.push_back(DS.getRepAsDecl());
  5852. for (unsigned i = 0; i != NumDecls; ++i)
  5853. if (Decl *D = Group[i])
  5854. Decls.push_back(D);
  5855. return BuildDeclaratorGroup(Decls.data(), Decls.size(),
  5856. DS.getTypeSpecType() == DeclSpec::TST_auto);
  5857. }
  5858. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  5859. /// group, performing any necessary semantic checking.
  5860. Sema::DeclGroupPtrTy
  5861. Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
  5862. bool TypeMayContainAuto) {
  5863. // C++0x [dcl.spec.auto]p7:
  5864. // If the type deduced for the template parameter U is not the same in each
  5865. // deduction, the program is ill-formed.
  5866. // FIXME: When initializer-list support is added, a distinction is needed
  5867. // between the deduced type U and the deduced type which 'auto' stands for.
  5868. // auto a = 0, b = { 1, 2, 3 };
  5869. // is legal because the deduced type U is 'int' in both cases.
  5870. if (TypeMayContainAuto && NumDecls > 1) {
  5871. QualType Deduced;
  5872. CanQualType DeducedCanon;
  5873. VarDecl *DeducedDecl = 0;
  5874. for (unsigned i = 0; i != NumDecls; ++i) {
  5875. if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
  5876. AutoType *AT = D->getType()->getContainedAutoType();
  5877. // Don't reissue diagnostics when instantiating a template.
  5878. if (AT && D->isInvalidDecl())
  5879. break;
  5880. if (AT && AT->isDeduced()) {
  5881. QualType U = AT->getDeducedType();
  5882. CanQualType UCanon = Context.getCanonicalType(U);
  5883. if (Deduced.isNull()) {
  5884. Deduced = U;
  5885. DeducedCanon = UCanon;
  5886. DeducedDecl = D;
  5887. } else if (DeducedCanon != UCanon) {
  5888. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  5889. diag::err_auto_different_deductions)
  5890. << Deduced << DeducedDecl->getDeclName()
  5891. << U << D->getDeclName()
  5892. << DeducedDecl->getInit()->getSourceRange()
  5893. << D->getInit()->getSourceRange();
  5894. D->setInvalidDecl();
  5895. break;
  5896. }
  5897. }
  5898. }
  5899. }
  5900. }
  5901. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
  5902. }
  5903. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  5904. /// to introduce parameters into function prototype scope.
  5905. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  5906. const DeclSpec &DS = D.getDeclSpec();
  5907. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  5908. // C++03 [dcl.stc]p2 also permits 'auto'.
  5909. VarDecl::StorageClass StorageClass = SC_None;
  5910. VarDecl::StorageClass StorageClassAsWritten = SC_None;
  5911. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  5912. StorageClass = SC_Register;
  5913. StorageClassAsWritten = SC_Register;
  5914. } else if (getLangOptions().CPlusPlus &&
  5915. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  5916. StorageClass = SC_Auto;
  5917. StorageClassAsWritten = SC_Auto;
  5918. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  5919. Diag(DS.getStorageClassSpecLoc(),
  5920. diag::err_invalid_storage_class_in_func_decl);
  5921. D.getMutableDeclSpec().ClearStorageClassSpecs();
  5922. }
  5923. if (D.getDeclSpec().isThreadSpecified())
  5924. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  5925. if (D.getDeclSpec().isConstexprSpecified())
  5926. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5927. << 0;
  5928. DiagnoseFunctionSpecifiers(D);
  5929. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  5930. QualType parmDeclType = TInfo->getType();
  5931. if (getLangOptions().CPlusPlus) {
  5932. // Check that there are no default arguments inside the type of this
  5933. // parameter.
  5934. CheckExtraCXXDefaultArguments(D);
  5935. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  5936. if (D.getCXXScopeSpec().isSet()) {
  5937. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  5938. << D.getCXXScopeSpec().getRange();
  5939. D.getCXXScopeSpec().clear();
  5940. }
  5941. }
  5942. // Ensure we have a valid name
  5943. IdentifierInfo *II = 0;
  5944. if (D.hasName()) {
  5945. II = D.getIdentifier();
  5946. if (!II) {
  5947. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  5948. << GetNameForDeclarator(D).getName().getAsString();
  5949. D.setInvalidType(true);
  5950. }
  5951. }
  5952. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  5953. if (II) {
  5954. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  5955. ForRedeclaration);
  5956. LookupName(R, S);
  5957. if (R.isSingleResult()) {
  5958. NamedDecl *PrevDecl = R.getFoundDecl();
  5959. if (PrevDecl->isTemplateParameter()) {
  5960. // Maybe we will complain about the shadowed template parameter.
  5961. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  5962. // Just pretend that we didn't see the previous declaration.
  5963. PrevDecl = 0;
  5964. } else if (S->isDeclScope(PrevDecl)) {
  5965. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  5966. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  5967. // Recover by removing the name
  5968. II = 0;
  5969. D.SetIdentifier(0, D.getIdentifierLoc());
  5970. D.setInvalidType(true);
  5971. }
  5972. }
  5973. }
  5974. // Temporarily put parameter variables in the translation unit, not
  5975. // the enclosing context. This prevents them from accidentally
  5976. // looking like class members in C++.
  5977. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  5978. D.getSourceRange().getBegin(),
  5979. D.getIdentifierLoc(), II,
  5980. parmDeclType, TInfo,
  5981. StorageClass, StorageClassAsWritten);
  5982. if (D.isInvalidType())
  5983. New->setInvalidDecl();
  5984. assert(S->isFunctionPrototypeScope());
  5985. assert(S->getFunctionPrototypeDepth() >= 1);
  5986. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  5987. S->getNextFunctionPrototypeIndex());
  5988. // Add the parameter declaration into this scope.
  5989. S->AddDecl(New);
  5990. if (II)
  5991. IdResolver.AddDecl(New);
  5992. ProcessDeclAttributes(S, New, D);
  5993. if (D.getDeclSpec().isModulePrivateSpecified())
  5994. Diag(New->getLocation(), diag::err_module_private_local)
  5995. << 1 << New->getDeclName()
  5996. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5997. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5998. if (New->hasAttr<BlocksAttr>()) {
  5999. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  6000. }
  6001. return New;
  6002. }
  6003. /// \brief Synthesizes a variable for a parameter arising from a
  6004. /// typedef.
  6005. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  6006. SourceLocation Loc,
  6007. QualType T) {
  6008. /* FIXME: setting StartLoc == Loc.
  6009. Would it be worth to modify callers so as to provide proper source
  6010. location for the unnamed parameters, embedding the parameter's type? */
  6011. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
  6012. T, Context.getTrivialTypeSourceInfo(T, Loc),
  6013. SC_None, SC_None, 0);
  6014. Param->setImplicit();
  6015. return Param;
  6016. }
  6017. void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
  6018. ParmVarDecl * const *ParamEnd) {
  6019. // Don't diagnose unused-parameter errors in template instantiations; we
  6020. // will already have done so in the template itself.
  6021. if (!ActiveTemplateInstantiations.empty())
  6022. return;
  6023. for (; Param != ParamEnd; ++Param) {
  6024. if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
  6025. !(*Param)->hasAttr<UnusedAttr>()) {
  6026. Diag((*Param)->getLocation(), diag::warn_unused_parameter)
  6027. << (*Param)->getDeclName();
  6028. }
  6029. }
  6030. }
  6031. void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
  6032. ParmVarDecl * const *ParamEnd,
  6033. QualType ReturnTy,
  6034. NamedDecl *D) {
  6035. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  6036. return;
  6037. // Warn if the return value is pass-by-value and larger than the specified
  6038. // threshold.
  6039. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  6040. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  6041. if (Size > LangOpts.NumLargeByValueCopy)
  6042. Diag(D->getLocation(), diag::warn_return_value_size)
  6043. << D->getDeclName() << Size;
  6044. }
  6045. // Warn if any parameter is pass-by-value and larger than the specified
  6046. // threshold.
  6047. for (; Param != ParamEnd; ++Param) {
  6048. QualType T = (*Param)->getType();
  6049. if (T->isDependentType() || !T.isPODType(Context))
  6050. continue;
  6051. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  6052. if (Size > LangOpts.NumLargeByValueCopy)
  6053. Diag((*Param)->getLocation(), diag::warn_parameter_size)
  6054. << (*Param)->getDeclName() << Size;
  6055. }
  6056. }
  6057. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  6058. SourceLocation NameLoc, IdentifierInfo *Name,
  6059. QualType T, TypeSourceInfo *TSInfo,
  6060. VarDecl::StorageClass StorageClass,
  6061. VarDecl::StorageClass StorageClassAsWritten) {
  6062. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  6063. if (getLangOptions().ObjCAutoRefCount &&
  6064. T.getObjCLifetime() == Qualifiers::OCL_None &&
  6065. T->isObjCLifetimeType()) {
  6066. Qualifiers::ObjCLifetime lifetime;
  6067. // Special cases for arrays:
  6068. // - if it's const, use __unsafe_unretained
  6069. // - otherwise, it's an error
  6070. if (T->isArrayType()) {
  6071. if (!T.isConstQualified()) {
  6072. DelayedDiagnostics.add(
  6073. sema::DelayedDiagnostic::makeForbiddenType(
  6074. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  6075. }
  6076. lifetime = Qualifiers::OCL_ExplicitNone;
  6077. } else {
  6078. lifetime = T->getObjCARCImplicitLifetime();
  6079. }
  6080. T = Context.getLifetimeQualifiedType(T, lifetime);
  6081. }
  6082. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  6083. Context.getAdjustedParameterType(T),
  6084. TSInfo,
  6085. StorageClass, StorageClassAsWritten,
  6086. 0);
  6087. // Parameters can not be abstract class types.
  6088. // For record types, this is done by the AbstractClassUsageDiagnoser once
  6089. // the class has been completely parsed.
  6090. if (!CurContext->isRecord() &&
  6091. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  6092. AbstractParamType))
  6093. New->setInvalidDecl();
  6094. // Parameter declarators cannot be interface types. All ObjC objects are
  6095. // passed by reference.
  6096. if (T->isObjCObjectType()) {
  6097. Diag(NameLoc,
  6098. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  6099. << FixItHint::CreateInsertion(NameLoc, "*");
  6100. T = Context.getObjCObjectPointerType(T);
  6101. New->setType(T);
  6102. }
  6103. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  6104. // duration shall not be qualified by an address-space qualifier."
  6105. // Since all parameters have automatic store duration, they can not have
  6106. // an address space.
  6107. if (T.getAddressSpace() != 0) {
  6108. Diag(NameLoc, diag::err_arg_with_address_space);
  6109. New->setInvalidDecl();
  6110. }
  6111. return New;
  6112. }
  6113. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  6114. SourceLocation LocAfterDecls) {
  6115. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  6116. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  6117. // for a K&R function.
  6118. if (!FTI.hasPrototype) {
  6119. for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
  6120. --i;
  6121. if (FTI.ArgInfo[i].Param == 0) {
  6122. SmallString<256> Code;
  6123. llvm::raw_svector_ostream(Code) << " int "
  6124. << FTI.ArgInfo[i].Ident->getName()
  6125. << ";\n";
  6126. Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
  6127. << FTI.ArgInfo[i].Ident
  6128. << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
  6129. // Implicitly declare the argument as type 'int' for lack of a better
  6130. // type.
  6131. AttributeFactory attrs;
  6132. DeclSpec DS(attrs);
  6133. const char* PrevSpec; // unused
  6134. unsigned DiagID; // unused
  6135. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
  6136. PrevSpec, DiagID);
  6137. Declarator ParamD(DS, Declarator::KNRTypeListContext);
  6138. ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
  6139. FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
  6140. }
  6141. }
  6142. }
  6143. }
  6144. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
  6145. Declarator &D) {
  6146. assert(getCurFunctionDecl() == 0 && "Function parsing confused");
  6147. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  6148. Scope *ParentScope = FnBodyScope->getParent();
  6149. D.setFunctionDefinitionKind(FDK_Definition);
  6150. Decl *DP = HandleDeclarator(ParentScope, D,
  6151. MultiTemplateParamsArg(*this));
  6152. return ActOnStartOfFunctionDef(FnBodyScope, DP);
  6153. }
  6154. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
  6155. // Don't warn about invalid declarations.
  6156. if (FD->isInvalidDecl())
  6157. return false;
  6158. // Or declarations that aren't global.
  6159. if (!FD->isGlobal())
  6160. return false;
  6161. // Don't warn about C++ member functions.
  6162. if (isa<CXXMethodDecl>(FD))
  6163. return false;
  6164. // Don't warn about 'main'.
  6165. if (FD->isMain())
  6166. return false;
  6167. // Don't warn about inline functions.
  6168. if (FD->isInlined())
  6169. return false;
  6170. // Don't warn about function templates.
  6171. if (FD->getDescribedFunctionTemplate())
  6172. return false;
  6173. // Don't warn about function template specializations.
  6174. if (FD->isFunctionTemplateSpecialization())
  6175. return false;
  6176. bool MissingPrototype = true;
  6177. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  6178. Prev; Prev = Prev->getPreviousDecl()) {
  6179. // Ignore any declarations that occur in function or method
  6180. // scope, because they aren't visible from the header.
  6181. if (Prev->getDeclContext()->isFunctionOrMethod())
  6182. continue;
  6183. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  6184. break;
  6185. }
  6186. return MissingPrototype;
  6187. }
  6188. void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
  6189. // Don't complain if we're in GNU89 mode and the previous definition
  6190. // was an extern inline function.
  6191. const FunctionDecl *Definition;
  6192. if (FD->isDefined(Definition) &&
  6193. !canRedefineFunction(Definition, getLangOptions())) {
  6194. if (getLangOptions().GNUMode && Definition->isInlineSpecified() &&
  6195. Definition->getStorageClass() == SC_Extern)
  6196. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  6197. << FD->getDeclName() << getLangOptions().CPlusPlus;
  6198. else
  6199. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  6200. Diag(Definition->getLocation(), diag::note_previous_definition);
  6201. }
  6202. }
  6203. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
  6204. // Clear the last template instantiation error context.
  6205. LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
  6206. if (!D)
  6207. return D;
  6208. FunctionDecl *FD = 0;
  6209. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  6210. FD = FunTmpl->getTemplatedDecl();
  6211. else
  6212. FD = cast<FunctionDecl>(D);
  6213. // Enter a new function scope
  6214. PushFunctionScope();
  6215. // See if this is a redefinition.
  6216. if (!FD->isLateTemplateParsed())
  6217. CheckForFunctionRedefinition(FD);
  6218. // Builtin functions cannot be defined.
  6219. if (unsigned BuiltinID = FD->getBuiltinID()) {
  6220. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  6221. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  6222. FD->setInvalidDecl();
  6223. }
  6224. }
  6225. // The return type of a function definition must be complete
  6226. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  6227. QualType ResultType = FD->getResultType();
  6228. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  6229. !FD->isInvalidDecl() &&
  6230. RequireCompleteType(FD->getLocation(), ResultType,
  6231. diag::err_func_def_incomplete_result))
  6232. FD->setInvalidDecl();
  6233. // GNU warning -Wmissing-prototypes:
  6234. // Warn if a global function is defined without a previous
  6235. // prototype declaration. This warning is issued even if the
  6236. // definition itself provides a prototype. The aim is to detect
  6237. // global functions that fail to be declared in header files.
  6238. if (ShouldWarnAboutMissingPrototype(FD))
  6239. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  6240. if (FnBodyScope)
  6241. PushDeclContext(FnBodyScope, FD);
  6242. // Check the validity of our function parameters
  6243. CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
  6244. /*CheckParameterNames=*/true);
  6245. // Introduce our parameters into the function scope
  6246. for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
  6247. ParmVarDecl *Param = FD->getParamDecl(p);
  6248. Param->setOwningFunction(FD);
  6249. // If this has an identifier, add it to the scope stack.
  6250. if (Param->getIdentifier() && FnBodyScope) {
  6251. CheckShadow(FnBodyScope, Param);
  6252. PushOnScopeChains(Param, FnBodyScope);
  6253. }
  6254. }
  6255. // Checking attributes of current function definition
  6256. // dllimport attribute.
  6257. DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
  6258. if (DA && (!FD->getAttr<DLLExportAttr>())) {
  6259. // dllimport attribute cannot be directly applied to definition.
  6260. // Microsoft accepts dllimport for functions defined within class scope.
  6261. if (!DA->isInherited() &&
  6262. !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
  6263. Diag(FD->getLocation(),
  6264. diag::err_attribute_can_be_applied_only_to_symbol_declaration)
  6265. << "dllimport";
  6266. FD->setInvalidDecl();
  6267. return FD;
  6268. }
  6269. // Visual C++ appears to not think this is an issue, so only issue
  6270. // a warning when Microsoft extensions are disabled.
  6271. if (!LangOpts.MicrosoftExt) {
  6272. // If a symbol previously declared dllimport is later defined, the
  6273. // attribute is ignored in subsequent references, and a warning is
  6274. // emitted.
  6275. Diag(FD->getLocation(),
  6276. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  6277. << FD->getName() << "dllimport";
  6278. }
  6279. }
  6280. return FD;
  6281. }
  6282. /// \brief Given the set of return statements within a function body,
  6283. /// compute the variables that are subject to the named return value
  6284. /// optimization.
  6285. ///
  6286. /// Each of the variables that is subject to the named return value
  6287. /// optimization will be marked as NRVO variables in the AST, and any
  6288. /// return statement that has a marked NRVO variable as its NRVO candidate can
  6289. /// use the named return value optimization.
  6290. ///
  6291. /// This function applies a very simplistic algorithm for NRVO: if every return
  6292. /// statement in the function has the same NRVO candidate, that candidate is
  6293. /// the NRVO variable.
  6294. ///
  6295. /// FIXME: Employ a smarter algorithm that accounts for multiple return
  6296. /// statements and the lifetimes of the NRVO candidates. We should be able to
  6297. /// find a maximal set of NRVO variables.
  6298. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  6299. ReturnStmt **Returns = Scope->Returns.data();
  6300. const VarDecl *NRVOCandidate = 0;
  6301. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  6302. if (!Returns[I]->getNRVOCandidate())
  6303. return;
  6304. if (!NRVOCandidate)
  6305. NRVOCandidate = Returns[I]->getNRVOCandidate();
  6306. else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
  6307. return;
  6308. }
  6309. if (NRVOCandidate)
  6310. const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
  6311. }
  6312. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  6313. return ActOnFinishFunctionBody(D, move(BodyArg), false);
  6314. }
  6315. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  6316. bool IsInstantiation) {
  6317. FunctionDecl *FD = 0;
  6318. FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
  6319. if (FunTmpl)
  6320. FD = FunTmpl->getTemplatedDecl();
  6321. else
  6322. FD = dyn_cast_or_null<FunctionDecl>(dcl);
  6323. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  6324. sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
  6325. if (FD) {
  6326. FD->setBody(Body);
  6327. if (FD->isMain()) {
  6328. // C and C++ allow for main to automagically return 0.
  6329. // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  6330. FD->setHasImplicitReturnZero(true);
  6331. WP.disableCheckFallThrough();
  6332. } else if (FD->hasAttr<NakedAttr>()) {
  6333. // If the function is marked 'naked', don't complain about missing return
  6334. // statements.
  6335. WP.disableCheckFallThrough();
  6336. }
  6337. // MSVC permits the use of pure specifier (=0) on function definition,
  6338. // defined at class scope, warn about this non standard construct.
  6339. if (getLangOptions().MicrosoftExt && FD->isPure())
  6340. Diag(FD->getLocation(), diag::warn_pure_function_definition);
  6341. if (!FD->isInvalidDecl()) {
  6342. DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
  6343. DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
  6344. FD->getResultType(), FD);
  6345. // If this is a constructor, we need a vtable.
  6346. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  6347. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  6348. computeNRVO(Body, getCurFunction());
  6349. }
  6350. assert(FD == getCurFunctionDecl() && "Function parsing confused");
  6351. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  6352. assert(MD == getCurMethodDecl() && "Method parsing confused");
  6353. MD->setBody(Body);
  6354. if (Body)
  6355. MD->setEndLoc(Body->getLocEnd());
  6356. if (!MD->isInvalidDecl()) {
  6357. DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
  6358. DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
  6359. MD->getResultType(), MD);
  6360. if (Body)
  6361. computeNRVO(Body, getCurFunction());
  6362. }
  6363. if (ObjCShouldCallSuperDealloc) {
  6364. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc);
  6365. ObjCShouldCallSuperDealloc = false;
  6366. }
  6367. if (ObjCShouldCallSuperFinalize) {
  6368. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize);
  6369. ObjCShouldCallSuperFinalize = false;
  6370. }
  6371. } else {
  6372. return 0;
  6373. }
  6374. assert(!ObjCShouldCallSuperDealloc && "This should only be set for "
  6375. "ObjC methods, which should have been handled in the block above.");
  6376. assert(!ObjCShouldCallSuperFinalize && "This should only be set for "
  6377. "ObjC methods, which should have been handled in the block above.");
  6378. // Verify and clean out per-function state.
  6379. if (Body) {
  6380. // C++ constructors that have function-try-blocks can't have return
  6381. // statements in the handlers of that block. (C++ [except.handle]p14)
  6382. // Verify this.
  6383. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  6384. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  6385. // Verify that gotos and switch cases don't jump into scopes illegally.
  6386. if (getCurFunction()->NeedsScopeChecking() &&
  6387. !dcl->isInvalidDecl() &&
  6388. !hasAnyUnrecoverableErrorsInThisFunction())
  6389. DiagnoseInvalidJumps(Body);
  6390. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  6391. if (!Destructor->getParent()->isDependentType())
  6392. CheckDestructor(Destructor);
  6393. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  6394. Destructor->getParent());
  6395. }
  6396. // If any errors have occurred, clear out any temporaries that may have
  6397. // been leftover. This ensures that these temporaries won't be picked up for
  6398. // deletion in some later function.
  6399. if (PP.getDiagnostics().hasErrorOccurred() ||
  6400. PP.getDiagnostics().getSuppressAllDiagnostics()) {
  6401. DiscardCleanupsInEvaluationContext();
  6402. } else if (!isa<FunctionTemplateDecl>(dcl)) {
  6403. // Since the body is valid, issue any analysis-based warnings that are
  6404. // enabled.
  6405. ActivePolicy = &WP;
  6406. }
  6407. if (FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  6408. !CheckConstexprFunctionBody(FD, Body))
  6409. FD->setInvalidDecl();
  6410. assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
  6411. assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
  6412. assert(MaybeODRUseExprs.empty() &&
  6413. "Leftover expressions for odr-use checking");
  6414. }
  6415. if (!IsInstantiation)
  6416. PopDeclContext();
  6417. PopFunctionScopeInfo(ActivePolicy, dcl);
  6418. // If any errors have occurred, clear out any temporaries that may have
  6419. // been leftover. This ensures that these temporaries won't be picked up for
  6420. // deletion in some later function.
  6421. if (getDiagnostics().hasErrorOccurred()) {
  6422. DiscardCleanupsInEvaluationContext();
  6423. }
  6424. return dcl;
  6425. }
  6426. /// When we finish delayed parsing of an attribute, we must attach it to the
  6427. /// relevant Decl.
  6428. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  6429. ParsedAttributes &Attrs) {
  6430. // Always attach attributes to the underlying decl.
  6431. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  6432. D = TD->getTemplatedDecl();
  6433. ProcessDeclAttributeList(S, D, Attrs.getList());
  6434. }
  6435. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  6436. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  6437. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  6438. IdentifierInfo &II, Scope *S) {
  6439. // Before we produce a declaration for an implicitly defined
  6440. // function, see whether there was a locally-scoped declaration of
  6441. // this name as a function or variable. If so, use that
  6442. // (non-visible) declaration, and complain about it.
  6443. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  6444. = findLocallyScopedExternalDecl(&II);
  6445. if (Pos != LocallyScopedExternalDecls.end()) {
  6446. Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
  6447. Diag(Pos->second->getLocation(), diag::note_previous_declaration);
  6448. return Pos->second;
  6449. }
  6450. // Extension in C99. Legal in C90, but warn about it.
  6451. unsigned diag_id;
  6452. if (II.getName().startswith("__builtin_"))
  6453. diag_id = diag::warn_builtin_unknown;
  6454. else if (getLangOptions().C99)
  6455. diag_id = diag::ext_implicit_function_decl;
  6456. else
  6457. diag_id = diag::warn_implicit_function_decl;
  6458. Diag(Loc, diag_id) << &II;
  6459. // Because typo correction is expensive, only do it if the implicit
  6460. // function declaration is going to be treated as an error.
  6461. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  6462. TypoCorrection Corrected;
  6463. DeclFilterCCC<FunctionDecl> Validator;
  6464. if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
  6465. LookupOrdinaryName, S, 0, Validator))) {
  6466. std::string CorrectedStr = Corrected.getAsString(getLangOptions());
  6467. std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOptions());
  6468. FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
  6469. Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
  6470. << FixItHint::CreateReplacement(Loc, CorrectedStr);
  6471. if (Func->getLocation().isValid()
  6472. && !II.getName().startswith("__builtin_"))
  6473. Diag(Func->getLocation(), diag::note_previous_decl)
  6474. << CorrectedQuotedStr;
  6475. }
  6476. }
  6477. // Set a Declarator for the implicit definition: int foo();
  6478. const char *Dummy;
  6479. AttributeFactory attrFactory;
  6480. DeclSpec DS(attrFactory);
  6481. unsigned DiagID;
  6482. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
  6483. (void)Error; // Silence warning.
  6484. assert(!Error && "Error setting up implicit decl!");
  6485. Declarator D(DS, Declarator::BlockContext);
  6486. D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
  6487. 0, 0, true, SourceLocation(),
  6488. SourceLocation(), SourceLocation(),
  6489. SourceLocation(),
  6490. EST_None, SourceLocation(),
  6491. 0, 0, 0, 0, Loc, Loc, D),
  6492. DS.getAttributes(),
  6493. SourceLocation());
  6494. D.SetIdentifier(&II, Loc);
  6495. // Insert this function into translation-unit scope.
  6496. DeclContext *PrevDC = CurContext;
  6497. CurContext = Context.getTranslationUnitDecl();
  6498. FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
  6499. FD->setImplicit();
  6500. CurContext = PrevDC;
  6501. AddKnownFunctionAttributes(FD);
  6502. return FD;
  6503. }
  6504. /// \brief Adds any function attributes that we know a priori based on
  6505. /// the declaration of this function.
  6506. ///
  6507. /// These attributes can apply both to implicitly-declared builtins
  6508. /// (like __builtin___printf_chk) or to library-declared functions
  6509. /// like NSLog or printf.
  6510. ///
  6511. /// We need to check for duplicate attributes both here and where user-written
  6512. /// attributes are applied to declarations.
  6513. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  6514. if (FD->isInvalidDecl())
  6515. return;
  6516. // If this is a built-in function, map its builtin attributes to
  6517. // actual attributes.
  6518. if (unsigned BuiltinID = FD->getBuiltinID()) {
  6519. // Handle printf-formatting attributes.
  6520. unsigned FormatIdx;
  6521. bool HasVAListArg;
  6522. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  6523. if (!FD->getAttr<FormatAttr>()) {
  6524. const char *fmt = "printf";
  6525. unsigned int NumParams = FD->getNumParams();
  6526. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  6527. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  6528. fmt = "NSString";
  6529. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  6530. fmt, FormatIdx+1,
  6531. HasVAListArg ? 0 : FormatIdx+2));
  6532. }
  6533. }
  6534. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  6535. HasVAListArg)) {
  6536. if (!FD->getAttr<FormatAttr>())
  6537. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  6538. "scanf", FormatIdx+1,
  6539. HasVAListArg ? 0 : FormatIdx+2));
  6540. }
  6541. // Mark const if we don't care about errno and that is the only
  6542. // thing preventing the function from being const. This allows
  6543. // IRgen to use LLVM intrinsics for such functions.
  6544. if (!getLangOptions().MathErrno &&
  6545. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
  6546. if (!FD->getAttr<ConstAttr>())
  6547. FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
  6548. }
  6549. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  6550. !FD->getAttr<ReturnsTwiceAttr>())
  6551. FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
  6552. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
  6553. FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
  6554. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
  6555. FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
  6556. }
  6557. IdentifierInfo *Name = FD->getIdentifier();
  6558. if (!Name)
  6559. return;
  6560. if ((!getLangOptions().CPlusPlus &&
  6561. FD->getDeclContext()->isTranslationUnit()) ||
  6562. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  6563. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  6564. LinkageSpecDecl::lang_c)) {
  6565. // Okay: this could be a libc/libm/Objective-C function we know
  6566. // about.
  6567. } else
  6568. return;
  6569. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  6570. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  6571. // target-specific builtins, perhaps?
  6572. if (!FD->getAttr<FormatAttr>())
  6573. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  6574. "printf", 2,
  6575. Name->isStr("vasprintf") ? 0 : 3));
  6576. }
  6577. }
  6578. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  6579. TypeSourceInfo *TInfo) {
  6580. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  6581. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  6582. if (!TInfo) {
  6583. assert(D.isInvalidType() && "no declarator info for valid type");
  6584. TInfo = Context.getTrivialTypeSourceInfo(T);
  6585. }
  6586. // Scope manipulation handled by caller.
  6587. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  6588. D.getSourceRange().getBegin(),
  6589. D.getIdentifierLoc(),
  6590. D.getIdentifier(),
  6591. TInfo);
  6592. // Bail out immediately if we have an invalid declaration.
  6593. if (D.isInvalidType()) {
  6594. NewTD->setInvalidDecl();
  6595. return NewTD;
  6596. }
  6597. if (D.getDeclSpec().isModulePrivateSpecified()) {
  6598. if (CurContext->isFunctionOrMethod())
  6599. Diag(NewTD->getLocation(), diag::err_module_private_local)
  6600. << 2 << NewTD->getDeclName()
  6601. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  6602. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6603. else
  6604. NewTD->setModulePrivate();
  6605. }
  6606. // C++ [dcl.typedef]p8:
  6607. // If the typedef declaration defines an unnamed class (or
  6608. // enum), the first typedef-name declared by the declaration
  6609. // to be that class type (or enum type) is used to denote the
  6610. // class type (or enum type) for linkage purposes only.
  6611. // We need to check whether the type was declared in the declaration.
  6612. switch (D.getDeclSpec().getTypeSpecType()) {
  6613. case TST_enum:
  6614. case TST_struct:
  6615. case TST_union:
  6616. case TST_class: {
  6617. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  6618. // Do nothing if the tag is not anonymous or already has an
  6619. // associated typedef (from an earlier typedef in this decl group).
  6620. if (tagFromDeclSpec->getIdentifier()) break;
  6621. if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
  6622. // A well-formed anonymous tag must always be a TUK_Definition.
  6623. assert(tagFromDeclSpec->isThisDeclarationADefinition());
  6624. // The type must match the tag exactly; no qualifiers allowed.
  6625. if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
  6626. break;
  6627. // Otherwise, set this is the anon-decl typedef for the tag.
  6628. tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  6629. break;
  6630. }
  6631. default:
  6632. break;
  6633. }
  6634. return NewTD;
  6635. }
  6636. /// \brief Determine whether a tag with a given kind is acceptable
  6637. /// as a redeclaration of the given tag declaration.
  6638. ///
  6639. /// \returns true if the new tag kind is acceptable, false otherwise.
  6640. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  6641. TagTypeKind NewTag, bool isDefinition,
  6642. SourceLocation NewTagLoc,
  6643. const IdentifierInfo &Name) {
  6644. // C++ [dcl.type.elab]p3:
  6645. // The class-key or enum keyword present in the
  6646. // elaborated-type-specifier shall agree in kind with the
  6647. // declaration to which the name in the elaborated-type-specifier
  6648. // refers. This rule also applies to the form of
  6649. // elaborated-type-specifier that declares a class-name or
  6650. // friend class since it can be construed as referring to the
  6651. // definition of the class. Thus, in any
  6652. // elaborated-type-specifier, the enum keyword shall be used to
  6653. // refer to an enumeration (7.2), the union class-key shall be
  6654. // used to refer to a union (clause 9), and either the class or
  6655. // struct class-key shall be used to refer to a class (clause 9)
  6656. // declared using the class or struct class-key.
  6657. TagTypeKind OldTag = Previous->getTagKind();
  6658. if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
  6659. if (OldTag == NewTag)
  6660. return true;
  6661. if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
  6662. (NewTag == TTK_Struct || NewTag == TTK_Class)) {
  6663. // Warn about the struct/class tag mismatch.
  6664. bool isTemplate = false;
  6665. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  6666. isTemplate = Record->getDescribedClassTemplate();
  6667. if (!ActiveTemplateInstantiations.empty()) {
  6668. // In a template instantiation, do not offer fix-its for tag mismatches
  6669. // since they usually mess up the template instead of fixing the problem.
  6670. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  6671. << (NewTag == TTK_Class) << isTemplate << &Name;
  6672. return true;
  6673. }
  6674. if (isDefinition) {
  6675. // On definitions, check previous tags and issue a fix-it for each
  6676. // one that doesn't match the current tag.
  6677. if (Previous->getDefinition()) {
  6678. // Don't suggest fix-its for redefinitions.
  6679. return true;
  6680. }
  6681. bool previousMismatch = false;
  6682. for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
  6683. E(Previous->redecls_end()); I != E; ++I) {
  6684. if (I->getTagKind() != NewTag) {
  6685. if (!previousMismatch) {
  6686. previousMismatch = true;
  6687. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  6688. << (NewTag == TTK_Class) << isTemplate << &Name;
  6689. }
  6690. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  6691. << (NewTag == TTK_Class)
  6692. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  6693. NewTag == TTK_Class?
  6694. "class" : "struct");
  6695. }
  6696. }
  6697. return true;
  6698. }
  6699. // Check for a previous definition. If current tag and definition
  6700. // are same type, do nothing. If no definition, but disagree with
  6701. // with previous tag type, give a warning, but no fix-it.
  6702. const TagDecl *Redecl = Previous->getDefinition() ?
  6703. Previous->getDefinition() : Previous;
  6704. if (Redecl->getTagKind() == NewTag) {
  6705. return true;
  6706. }
  6707. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  6708. << (NewTag == TTK_Class)
  6709. << isTemplate << &Name;
  6710. Diag(Redecl->getLocation(), diag::note_previous_use);
  6711. // If there is a previous defintion, suggest a fix-it.
  6712. if (Previous->getDefinition()) {
  6713. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  6714. << (Redecl->getTagKind() == TTK_Class)
  6715. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  6716. Redecl->getTagKind() == TTK_Class? "class" : "struct");
  6717. }
  6718. return true;
  6719. }
  6720. return false;
  6721. }
  6722. /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
  6723. /// former case, Name will be non-null. In the later case, Name will be null.
  6724. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  6725. /// reference/declaration/definition of a tag.
  6726. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  6727. SourceLocation KWLoc, CXXScopeSpec &SS,
  6728. IdentifierInfo *Name, SourceLocation NameLoc,
  6729. AttributeList *Attr, AccessSpecifier AS,
  6730. SourceLocation ModulePrivateLoc,
  6731. MultiTemplateParamsArg TemplateParameterLists,
  6732. bool &OwnedDecl, bool &IsDependent,
  6733. SourceLocation ScopedEnumKWLoc,
  6734. bool ScopedEnumUsesClassTag,
  6735. TypeResult UnderlyingType) {
  6736. // If this is not a definition, it must have a name.
  6737. assert((Name != 0 || TUK == TUK_Definition) &&
  6738. "Nameless record must be a definition!");
  6739. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  6740. OwnedDecl = false;
  6741. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  6742. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  6743. // FIXME: Check explicit specializations more carefully.
  6744. bool isExplicitSpecialization = false;
  6745. bool Invalid = false;
  6746. // We only need to do this matching if we have template parameters
  6747. // or a scope specifier, which also conveniently avoids this work
  6748. // for non-C++ cases.
  6749. if (TemplateParameterLists.size() > 0 ||
  6750. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  6751. if (TemplateParameterList *TemplateParams
  6752. = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
  6753. TemplateParameterLists.get(),
  6754. TemplateParameterLists.size(),
  6755. TUK == TUK_Friend,
  6756. isExplicitSpecialization,
  6757. Invalid)) {
  6758. if (TemplateParams->size() > 0) {
  6759. // This is a declaration or definition of a class template (which may
  6760. // be a member of another template).
  6761. if (Invalid)
  6762. return 0;
  6763. OwnedDecl = false;
  6764. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  6765. SS, Name, NameLoc, Attr,
  6766. TemplateParams, AS,
  6767. ModulePrivateLoc,
  6768. TemplateParameterLists.size() - 1,
  6769. (TemplateParameterList**) TemplateParameterLists.release());
  6770. return Result.get();
  6771. } else {
  6772. // The "template<>" header is extraneous.
  6773. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  6774. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  6775. isExplicitSpecialization = true;
  6776. }
  6777. }
  6778. }
  6779. // Figure out the underlying type if this a enum declaration. We need to do
  6780. // this early, because it's needed to detect if this is an incompatible
  6781. // redeclaration.
  6782. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  6783. if (Kind == TTK_Enum) {
  6784. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
  6785. // No underlying type explicitly specified, or we failed to parse the
  6786. // type, default to int.
  6787. EnumUnderlying = Context.IntTy.getTypePtr();
  6788. else if (UnderlyingType.get()) {
  6789. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  6790. // integral type; any cv-qualification is ignored.
  6791. TypeSourceInfo *TI = 0;
  6792. QualType T = GetTypeFromParser(UnderlyingType.get(), &TI);
  6793. EnumUnderlying = TI;
  6794. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  6795. if (!T->isDependentType() && !T->isIntegralType(Context)) {
  6796. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
  6797. << T;
  6798. // Recover by falling back to int.
  6799. EnumUnderlying = Context.IntTy.getTypePtr();
  6800. }
  6801. if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI,
  6802. UPPC_FixedUnderlyingType))
  6803. EnumUnderlying = Context.IntTy.getTypePtr();
  6804. } else if (getLangOptions().MicrosoftExt)
  6805. // Microsoft enums are always of int type.
  6806. EnumUnderlying = Context.IntTy.getTypePtr();
  6807. }
  6808. DeclContext *SearchDC = CurContext;
  6809. DeclContext *DC = CurContext;
  6810. bool isStdBadAlloc = false;
  6811. RedeclarationKind Redecl = ForRedeclaration;
  6812. if (TUK == TUK_Friend || TUK == TUK_Reference)
  6813. Redecl = NotForRedeclaration;
  6814. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  6815. if (Name && SS.isNotEmpty()) {
  6816. // We have a nested-name tag ('struct foo::bar').
  6817. // Check for invalid 'foo::'.
  6818. if (SS.isInvalid()) {
  6819. Name = 0;
  6820. goto CreateNewDecl;
  6821. }
  6822. // If this is a friend or a reference to a class in a dependent
  6823. // context, don't try to make a decl for it.
  6824. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  6825. DC = computeDeclContext(SS, false);
  6826. if (!DC) {
  6827. IsDependent = true;
  6828. return 0;
  6829. }
  6830. } else {
  6831. DC = computeDeclContext(SS, true);
  6832. if (!DC) {
  6833. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  6834. << SS.getRange();
  6835. return 0;
  6836. }
  6837. }
  6838. if (RequireCompleteDeclContext(SS, DC))
  6839. return 0;
  6840. SearchDC = DC;
  6841. // Look-up name inside 'foo::'.
  6842. LookupQualifiedName(Previous, DC);
  6843. if (Previous.isAmbiguous())
  6844. return 0;
  6845. if (Previous.empty()) {
  6846. // Name lookup did not find anything. However, if the
  6847. // nested-name-specifier refers to the current instantiation,
  6848. // and that current instantiation has any dependent base
  6849. // classes, we might find something at instantiation time: treat
  6850. // this as a dependent elaborated-type-specifier.
  6851. // But this only makes any sense for reference-like lookups.
  6852. if (Previous.wasNotFoundInCurrentInstantiation() &&
  6853. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  6854. IsDependent = true;
  6855. return 0;
  6856. }
  6857. // A tag 'foo::bar' must already exist.
  6858. Diag(NameLoc, diag::err_not_tag_in_scope)
  6859. << Kind << Name << DC << SS.getRange();
  6860. Name = 0;
  6861. Invalid = true;
  6862. goto CreateNewDecl;
  6863. }
  6864. } else if (Name) {
  6865. // If this is a named struct, check to see if there was a previous forward
  6866. // declaration or definition.
  6867. // FIXME: We're looking into outer scopes here, even when we
  6868. // shouldn't be. Doing so can result in ambiguities that we
  6869. // shouldn't be diagnosing.
  6870. LookupName(Previous, S);
  6871. if (Previous.isAmbiguous() &&
  6872. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  6873. LookupResult::Filter F = Previous.makeFilter();
  6874. while (F.hasNext()) {
  6875. NamedDecl *ND = F.next();
  6876. if (ND->getDeclContext()->getRedeclContext() != SearchDC)
  6877. F.erase();
  6878. }
  6879. F.done();
  6880. }
  6881. // Note: there used to be some attempt at recovery here.
  6882. if (Previous.isAmbiguous())
  6883. return 0;
  6884. if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
  6885. // FIXME: This makes sure that we ignore the contexts associated
  6886. // with C structs, unions, and enums when looking for a matching
  6887. // tag declaration or definition. See the similar lookup tweak
  6888. // in Sema::LookupName; is there a better way to deal with this?
  6889. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  6890. SearchDC = SearchDC->getParent();
  6891. }
  6892. } else if (S->isFunctionPrototypeScope()) {
  6893. // If this is an enum declaration in function prototype scope, set its
  6894. // initial context to the translation unit.
  6895. SearchDC = Context.getTranslationUnitDecl();
  6896. }
  6897. if (Previous.isSingleResult() &&
  6898. Previous.getFoundDecl()->isTemplateParameter()) {
  6899. // Maybe we will complain about the shadowed template parameter.
  6900. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  6901. // Just pretend that we didn't see the previous declaration.
  6902. Previous.clear();
  6903. }
  6904. if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
  6905. DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
  6906. // This is a declaration of or a reference to "std::bad_alloc".
  6907. isStdBadAlloc = true;
  6908. if (Previous.empty() && StdBadAlloc) {
  6909. // std::bad_alloc has been implicitly declared (but made invisible to
  6910. // name lookup). Fill in this implicit declaration as the previous
  6911. // declaration, so that the declarations get chained appropriately.
  6912. Previous.addDecl(getStdBadAlloc());
  6913. }
  6914. }
  6915. // If we didn't find a previous declaration, and this is a reference
  6916. // (or friend reference), move to the correct scope. In C++, we
  6917. // also need to do a redeclaration lookup there, just in case
  6918. // there's a shadow friend decl.
  6919. if (Name && Previous.empty() &&
  6920. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  6921. if (Invalid) goto CreateNewDecl;
  6922. assert(SS.isEmpty());
  6923. if (TUK == TUK_Reference) {
  6924. // C++ [basic.scope.pdecl]p5:
  6925. // -- for an elaborated-type-specifier of the form
  6926. //
  6927. // class-key identifier
  6928. //
  6929. // if the elaborated-type-specifier is used in the
  6930. // decl-specifier-seq or parameter-declaration-clause of a
  6931. // function defined in namespace scope, the identifier is
  6932. // declared as a class-name in the namespace that contains
  6933. // the declaration; otherwise, except as a friend
  6934. // declaration, the identifier is declared in the smallest
  6935. // non-class, non-function-prototype scope that contains the
  6936. // declaration.
  6937. //
  6938. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  6939. // C structs and unions.
  6940. //
  6941. // It is an error in C++ to declare (rather than define) an enum
  6942. // type, including via an elaborated type specifier. We'll
  6943. // diagnose that later; for now, declare the enum in the same
  6944. // scope as we would have picked for any other tag type.
  6945. //
  6946. // GNU C also supports this behavior as part of its incomplete
  6947. // enum types extension, while GNU C++ does not.
  6948. //
  6949. // Find the context where we'll be declaring the tag.
  6950. // FIXME: We would like to maintain the current DeclContext as the
  6951. // lexical context,
  6952. while (SearchDC->isRecord() || SearchDC->isTransparentContext() ||
  6953. SearchDC->isObjCContainer())
  6954. SearchDC = SearchDC->getParent();
  6955. // Find the scope where we'll be declaring the tag.
  6956. while (S->isClassScope() ||
  6957. (getLangOptions().CPlusPlus &&
  6958. S->isFunctionPrototypeScope()) ||
  6959. ((S->getFlags() & Scope::DeclScope) == 0) ||
  6960. (S->getEntity() &&
  6961. ((DeclContext *)S->getEntity())->isTransparentContext()))
  6962. S = S->getParent();
  6963. } else {
  6964. assert(TUK == TUK_Friend);
  6965. // C++ [namespace.memdef]p3:
  6966. // If a friend declaration in a non-local class first declares a
  6967. // class or function, the friend class or function is a member of
  6968. // the innermost enclosing namespace.
  6969. SearchDC = SearchDC->getEnclosingNamespaceContext();
  6970. }
  6971. // In C++, we need to do a redeclaration lookup to properly
  6972. // diagnose some problems.
  6973. if (getLangOptions().CPlusPlus) {
  6974. Previous.setRedeclarationKind(ForRedeclaration);
  6975. LookupQualifiedName(Previous, SearchDC);
  6976. }
  6977. }
  6978. if (!Previous.empty()) {
  6979. NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
  6980. // It's okay to have a tag decl in the same scope as a typedef
  6981. // which hides a tag decl in the same scope. Finding this
  6982. // insanity with a redeclaration lookup can only actually happen
  6983. // in C++.
  6984. //
  6985. // This is also okay for elaborated-type-specifiers, which is
  6986. // technically forbidden by the current standard but which is
  6987. // okay according to the likely resolution of an open issue;
  6988. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  6989. if (getLangOptions().CPlusPlus) {
  6990. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  6991. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  6992. TagDecl *Tag = TT->getDecl();
  6993. if (Tag->getDeclName() == Name &&
  6994. Tag->getDeclContext()->getRedeclContext()
  6995. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  6996. PrevDecl = Tag;
  6997. Previous.clear();
  6998. Previous.addDecl(Tag);
  6999. Previous.resolveKind();
  7000. }
  7001. }
  7002. }
  7003. }
  7004. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  7005. // If this is a use of a previous tag, or if the tag is already declared
  7006. // in the same scope (so that the definition/declaration completes or
  7007. // rementions the tag), reuse the decl.
  7008. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  7009. isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
  7010. // Make sure that this wasn't declared as an enum and now used as a
  7011. // struct or something similar.
  7012. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  7013. TUK == TUK_Definition, KWLoc,
  7014. *Name)) {
  7015. bool SafeToContinue
  7016. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  7017. Kind != TTK_Enum);
  7018. if (SafeToContinue)
  7019. Diag(KWLoc, diag::err_use_with_wrong_tag)
  7020. << Name
  7021. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  7022. PrevTagDecl->getKindName());
  7023. else
  7024. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  7025. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  7026. if (SafeToContinue)
  7027. Kind = PrevTagDecl->getTagKind();
  7028. else {
  7029. // Recover by making this an anonymous redefinition.
  7030. Name = 0;
  7031. Previous.clear();
  7032. Invalid = true;
  7033. }
  7034. }
  7035. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  7036. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  7037. // If this is an elaborated-type-specifier for a scoped enumeration,
  7038. // the 'class' keyword is not necessary and not permitted.
  7039. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  7040. if (ScopedEnum)
  7041. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  7042. << PrevEnum->isScoped()
  7043. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  7044. return PrevTagDecl;
  7045. }
  7046. // All conflicts with previous declarations are recovered by
  7047. // returning the previous declaration.
  7048. if (ScopedEnum != PrevEnum->isScoped()) {
  7049. Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch)
  7050. << PrevEnum->isScoped();
  7051. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  7052. return PrevTagDecl;
  7053. }
  7054. else if (EnumUnderlying && PrevEnum->isFixed()) {
  7055. QualType T;
  7056. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  7057. T = TI->getType();
  7058. else
  7059. T = QualType(EnumUnderlying.get<const Type*>(), 0);
  7060. if (!Context.hasSameUnqualifiedType(T,
  7061. PrevEnum->getIntegerType())) {
  7062. Diag(NameLoc.isValid() ? NameLoc : KWLoc,
  7063. diag::err_enum_redeclare_type_mismatch)
  7064. << T
  7065. << PrevEnum->getIntegerType();
  7066. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  7067. return PrevTagDecl;
  7068. }
  7069. }
  7070. else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) {
  7071. Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch)
  7072. << PrevEnum->isFixed();
  7073. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  7074. return PrevTagDecl;
  7075. }
  7076. }
  7077. if (!Invalid) {
  7078. // If this is a use, just return the declaration we found.
  7079. // FIXME: In the future, return a variant or some other clue
  7080. // for the consumer of this Decl to know it doesn't own it.
  7081. // For our current ASTs this shouldn't be a problem, but will
  7082. // need to be changed with DeclGroups.
  7083. if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
  7084. getLangOptions().MicrosoftExt)) || TUK == TUK_Friend)
  7085. return PrevTagDecl;
  7086. // Diagnose attempts to redefine a tag.
  7087. if (TUK == TUK_Definition) {
  7088. if (TagDecl *Def = PrevTagDecl->getDefinition()) {
  7089. // If we're defining a specialization and the previous definition
  7090. // is from an implicit instantiation, don't emit an error
  7091. // here; we'll catch this in the general case below.
  7092. if (!isExplicitSpecialization ||
  7093. !isa<CXXRecordDecl>(Def) ||
  7094. cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
  7095. == TSK_ExplicitSpecialization) {
  7096. Diag(NameLoc, diag::err_redefinition) << Name;
  7097. Diag(Def->getLocation(), diag::note_previous_definition);
  7098. // If this is a redefinition, recover by making this
  7099. // struct be anonymous, which will make any later
  7100. // references get the previous definition.
  7101. Name = 0;
  7102. Previous.clear();
  7103. Invalid = true;
  7104. }
  7105. } else {
  7106. // If the type is currently being defined, complain
  7107. // about a nested redefinition.
  7108. const TagType *Tag
  7109. = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
  7110. if (Tag->isBeingDefined()) {
  7111. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  7112. Diag(PrevTagDecl->getLocation(),
  7113. diag::note_previous_definition);
  7114. Name = 0;
  7115. Previous.clear();
  7116. Invalid = true;
  7117. }
  7118. }
  7119. // Okay, this is definition of a previously declared or referenced
  7120. // tag PrevDecl. We're going to create a new Decl for it.
  7121. }
  7122. }
  7123. // If we get here we have (another) forward declaration or we
  7124. // have a definition. Just create a new decl.
  7125. } else {
  7126. // If we get here, this is a definition of a new tag type in a nested
  7127. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  7128. // new decl/type. We set PrevDecl to NULL so that the entities
  7129. // have distinct types.
  7130. Previous.clear();
  7131. }
  7132. // If we get here, we're going to create a new Decl. If PrevDecl
  7133. // is non-NULL, it's a definition of the tag declared by
  7134. // PrevDecl. If it's NULL, we have a new definition.
  7135. // Otherwise, PrevDecl is not a tag, but was found with tag
  7136. // lookup. This is only actually possible in C++, where a few
  7137. // things like templates still live in the tag namespace.
  7138. } else {
  7139. // Use a better diagnostic if an elaborated-type-specifier
  7140. // found the wrong kind of type on the first
  7141. // (non-redeclaration) lookup.
  7142. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  7143. !Previous.isForRedeclaration()) {
  7144. unsigned Kind = 0;
  7145. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  7146. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  7147. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  7148. Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
  7149. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  7150. Invalid = true;
  7151. // Otherwise, only diagnose if the declaration is in scope.
  7152. } else if (!isDeclInScope(PrevDecl, SearchDC, S,
  7153. isExplicitSpecialization)) {
  7154. // do nothing
  7155. // Diagnose implicit declarations introduced by elaborated types.
  7156. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  7157. unsigned Kind = 0;
  7158. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  7159. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  7160. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  7161. Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
  7162. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  7163. Invalid = true;
  7164. // Otherwise it's a declaration. Call out a particularly common
  7165. // case here.
  7166. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  7167. unsigned Kind = 0;
  7168. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  7169. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  7170. << Name << Kind << TND->getUnderlyingType();
  7171. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  7172. Invalid = true;
  7173. // Otherwise, diagnose.
  7174. } else {
  7175. // The tag name clashes with something else in the target scope,
  7176. // issue an error and recover by making this tag be anonymous.
  7177. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  7178. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  7179. Name = 0;
  7180. Invalid = true;
  7181. }
  7182. // The existing declaration isn't relevant to us; we're in a
  7183. // new scope, so clear out the previous declaration.
  7184. Previous.clear();
  7185. }
  7186. }
  7187. CreateNewDecl:
  7188. TagDecl *PrevDecl = 0;
  7189. if (Previous.isSingleResult())
  7190. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  7191. // If there is an identifier, use the location of the identifier as the
  7192. // location of the decl, otherwise use the location of the struct/union
  7193. // keyword.
  7194. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  7195. // Otherwise, create a new declaration. If there is a previous
  7196. // declaration of the same entity, the two will be linked via
  7197. // PrevDecl.
  7198. TagDecl *New;
  7199. bool IsForwardReference = false;
  7200. if (Kind == TTK_Enum) {
  7201. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  7202. // enum X { A, B, C } D; D should chain to X.
  7203. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  7204. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  7205. ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
  7206. // If this is an undefined enum, warn.
  7207. if (TUK != TUK_Definition && !Invalid) {
  7208. TagDecl *Def;
  7209. if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
  7210. // C++0x: 7.2p2: opaque-enum-declaration.
  7211. // Conflicts are diagnosed above. Do nothing.
  7212. }
  7213. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  7214. Diag(Loc, diag::ext_forward_ref_enum_def)
  7215. << New;
  7216. Diag(Def->getLocation(), diag::note_previous_definition);
  7217. } else {
  7218. unsigned DiagID = diag::ext_forward_ref_enum;
  7219. if (getLangOptions().MicrosoftExt)
  7220. DiagID = diag::ext_ms_forward_ref_enum;
  7221. else if (getLangOptions().CPlusPlus)
  7222. DiagID = diag::err_forward_ref_enum;
  7223. Diag(Loc, DiagID);
  7224. // If this is a forward-declared reference to an enumeration, make a
  7225. // note of it; we won't actually be introducing the declaration into
  7226. // the declaration context.
  7227. if (TUK == TUK_Reference)
  7228. IsForwardReference = true;
  7229. }
  7230. }
  7231. if (EnumUnderlying) {
  7232. EnumDecl *ED = cast<EnumDecl>(New);
  7233. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  7234. ED->setIntegerTypeSourceInfo(TI);
  7235. else
  7236. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  7237. ED->setPromotionType(ED->getIntegerType());
  7238. }
  7239. } else {
  7240. // struct/union/class
  7241. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  7242. // struct X { int A; } D; D should chain to X.
  7243. if (getLangOptions().CPlusPlus) {
  7244. // FIXME: Look for a way to use RecordDecl for simple structs.
  7245. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  7246. cast_or_null<CXXRecordDecl>(PrevDecl));
  7247. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  7248. StdBadAlloc = cast<CXXRecordDecl>(New);
  7249. } else
  7250. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  7251. cast_or_null<RecordDecl>(PrevDecl));
  7252. }
  7253. // Maybe add qualifier info.
  7254. if (SS.isNotEmpty()) {
  7255. if (SS.isSet()) {
  7256. New->setQualifierInfo(SS.getWithLocInContext(Context));
  7257. if (TemplateParameterLists.size() > 0) {
  7258. New->setTemplateParameterListsInfo(Context,
  7259. TemplateParameterLists.size(),
  7260. (TemplateParameterList**) TemplateParameterLists.release());
  7261. }
  7262. }
  7263. else
  7264. Invalid = true;
  7265. }
  7266. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  7267. // Add alignment attributes if necessary; these attributes are checked when
  7268. // the ASTContext lays out the structure.
  7269. //
  7270. // It is important for implementing the correct semantics that this
  7271. // happen here (in act on tag decl). The #pragma pack stack is
  7272. // maintained as a result of parser callbacks which can occur at
  7273. // many points during the parsing of a struct declaration (because
  7274. // the #pragma tokens are effectively skipped over during the
  7275. // parsing of the struct).
  7276. AddAlignmentAttributesForRecord(RD);
  7277. AddMsStructLayoutForRecord(RD);
  7278. }
  7279. if (ModulePrivateLoc.isValid()) {
  7280. if (isExplicitSpecialization)
  7281. Diag(New->getLocation(), diag::err_module_private_specialization)
  7282. << 2
  7283. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7284. // __module_private__ does not apply to local classes. However, we only
  7285. // diagnose this as an error when the declaration specifiers are
  7286. // freestanding. Here, we just ignore the __module_private__.
  7287. else if (!SearchDC->isFunctionOrMethod())
  7288. New->setModulePrivate();
  7289. }
  7290. // If this is a specialization of a member class (of a class template),
  7291. // check the specialization.
  7292. if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
  7293. Invalid = true;
  7294. if (Invalid)
  7295. New->setInvalidDecl();
  7296. if (Attr)
  7297. ProcessDeclAttributeList(S, New, Attr);
  7298. // If we're declaring or defining a tag in function prototype scope
  7299. // in C, note that this type can only be used within the function.
  7300. if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
  7301. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  7302. // Set the lexical context. If the tag has a C++ scope specifier, the
  7303. // lexical context will be different from the semantic context.
  7304. New->setLexicalDeclContext(CurContext);
  7305. // Mark this as a friend decl if applicable.
  7306. // In Microsoft mode, a friend declaration also acts as a forward
  7307. // declaration so we always pass true to setObjectOfFriendDecl to make
  7308. // the tag name visible.
  7309. if (TUK == TUK_Friend)
  7310. New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
  7311. getLangOptions().MicrosoftExt);
  7312. // Set the access specifier.
  7313. if (!Invalid && SearchDC->isRecord())
  7314. SetMemberAccessSpecifier(New, PrevDecl, AS);
  7315. if (TUK == TUK_Definition)
  7316. New->startDefinition();
  7317. // If this has an identifier, add it to the scope stack.
  7318. if (TUK == TUK_Friend) {
  7319. // We might be replacing an existing declaration in the lookup tables;
  7320. // if so, borrow its access specifier.
  7321. if (PrevDecl)
  7322. New->setAccess(PrevDecl->getAccess());
  7323. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  7324. DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
  7325. if (Name) // can be null along some error paths
  7326. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  7327. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  7328. } else if (Name) {
  7329. S = getNonFieldDeclScope(S);
  7330. PushOnScopeChains(New, S, !IsForwardReference);
  7331. if (IsForwardReference)
  7332. SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
  7333. } else {
  7334. CurContext->addDecl(New);
  7335. }
  7336. // If this is the C FILE type, notify the AST context.
  7337. if (IdentifierInfo *II = New->getIdentifier())
  7338. if (!New->isInvalidDecl() &&
  7339. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  7340. II->isStr("FILE"))
  7341. Context.setFILEDecl(New);
  7342. OwnedDecl = true;
  7343. return New;
  7344. }
  7345. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  7346. AdjustDeclIfTemplate(TagD);
  7347. TagDecl *Tag = cast<TagDecl>(TagD);
  7348. // Enter the tag context.
  7349. PushDeclContext(S, Tag);
  7350. }
  7351. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  7352. assert(isa<ObjCContainerDecl>(IDecl) &&
  7353. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  7354. DeclContext *OCD = cast<DeclContext>(IDecl);
  7355. assert(getContainingDC(OCD) == CurContext &&
  7356. "The next DeclContext should be lexically contained in the current one.");
  7357. CurContext = OCD;
  7358. return IDecl;
  7359. }
  7360. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  7361. SourceLocation FinalLoc,
  7362. SourceLocation LBraceLoc) {
  7363. AdjustDeclIfTemplate(TagD);
  7364. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  7365. FieldCollector->StartClass();
  7366. if (!Record->getIdentifier())
  7367. return;
  7368. if (FinalLoc.isValid())
  7369. Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
  7370. // C++ [class]p2:
  7371. // [...] The class-name is also inserted into the scope of the
  7372. // class itself; this is known as the injected-class-name. For
  7373. // purposes of access checking, the injected-class-name is treated
  7374. // as if it were a public member name.
  7375. CXXRecordDecl *InjectedClassName
  7376. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  7377. Record->getLocStart(), Record->getLocation(),
  7378. Record->getIdentifier(),
  7379. /*PrevDecl=*/0,
  7380. /*DelayTypeCreation=*/true);
  7381. Context.getTypeDeclType(InjectedClassName, Record);
  7382. InjectedClassName->setImplicit();
  7383. InjectedClassName->setAccess(AS_public);
  7384. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  7385. InjectedClassName->setDescribedClassTemplate(Template);
  7386. PushOnScopeChains(InjectedClassName, S);
  7387. assert(InjectedClassName->isInjectedClassName() &&
  7388. "Broken injected-class-name");
  7389. }
  7390. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  7391. SourceLocation RBraceLoc) {
  7392. AdjustDeclIfTemplate(TagD);
  7393. TagDecl *Tag = cast<TagDecl>(TagD);
  7394. Tag->setRBraceLoc(RBraceLoc);
  7395. if (isa<CXXRecordDecl>(Tag))
  7396. FieldCollector->FinishClass();
  7397. // Exit this scope of this tag's definition.
  7398. PopDeclContext();
  7399. // Notify the consumer that we've defined a tag.
  7400. Consumer.HandleTagDeclDefinition(Tag);
  7401. }
  7402. void Sema::ActOnObjCContainerFinishDefinition() {
  7403. // Exit this scope of this interface definition.
  7404. PopDeclContext();
  7405. }
  7406. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  7407. assert(DC == CurContext && "Mismatch of container contexts");
  7408. OriginalLexicalContext = DC;
  7409. ActOnObjCContainerFinishDefinition();
  7410. }
  7411. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  7412. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  7413. OriginalLexicalContext = 0;
  7414. }
  7415. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  7416. AdjustDeclIfTemplate(TagD);
  7417. TagDecl *Tag = cast<TagDecl>(TagD);
  7418. Tag->setInvalidDecl();
  7419. // We're undoing ActOnTagStartDefinition here, not
  7420. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  7421. // the FieldCollector.
  7422. PopDeclContext();
  7423. }
  7424. // Note that FieldName may be null for anonymous bitfields.
  7425. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  7426. IdentifierInfo *FieldName,
  7427. QualType FieldTy, Expr *BitWidth,
  7428. bool *ZeroWidth) {
  7429. // Default to true; that shouldn't confuse checks for emptiness
  7430. if (ZeroWidth)
  7431. *ZeroWidth = true;
  7432. // C99 6.7.2.1p4 - verify the field type.
  7433. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  7434. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  7435. // Handle incomplete types with specific error.
  7436. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  7437. return ExprError();
  7438. if (FieldName)
  7439. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  7440. << FieldName << FieldTy << BitWidth->getSourceRange();
  7441. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  7442. << FieldTy << BitWidth->getSourceRange();
  7443. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  7444. UPPC_BitFieldWidth))
  7445. return ExprError();
  7446. // If the bit-width is type- or value-dependent, don't try to check
  7447. // it now.
  7448. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  7449. return Owned(BitWidth);
  7450. llvm::APSInt Value;
  7451. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  7452. if (ICE.isInvalid())
  7453. return ICE;
  7454. BitWidth = ICE.take();
  7455. if (Value != 0 && ZeroWidth)
  7456. *ZeroWidth = false;
  7457. // Zero-width bitfield is ok for anonymous field.
  7458. if (Value == 0 && FieldName)
  7459. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  7460. if (Value.isSigned() && Value.isNegative()) {
  7461. if (FieldName)
  7462. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  7463. << FieldName << Value.toString(10);
  7464. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  7465. << Value.toString(10);
  7466. }
  7467. if (!FieldTy->isDependentType()) {
  7468. uint64_t TypeSize = Context.getTypeSize(FieldTy);
  7469. if (Value.getZExtValue() > TypeSize) {
  7470. if (!getLangOptions().CPlusPlus) {
  7471. if (FieldName)
  7472. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
  7473. << FieldName << (unsigned)Value.getZExtValue()
  7474. << (unsigned)TypeSize;
  7475. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
  7476. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  7477. }
  7478. if (FieldName)
  7479. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
  7480. << FieldName << (unsigned)Value.getZExtValue()
  7481. << (unsigned)TypeSize;
  7482. else
  7483. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
  7484. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  7485. }
  7486. }
  7487. return Owned(BitWidth);
  7488. }
  7489. /// ActOnField - Each field of a C struct/union is passed into this in order
  7490. /// to create a FieldDecl object for it.
  7491. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  7492. Declarator &D, Expr *BitfieldWidth) {
  7493. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  7494. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  7495. /*HasInit=*/false, AS_public);
  7496. return Res;
  7497. }
  7498. /// HandleField - Analyze a field of a C struct or a C++ data member.
  7499. ///
  7500. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  7501. SourceLocation DeclStart,
  7502. Declarator &D, Expr *BitWidth, bool HasInit,
  7503. AccessSpecifier AS) {
  7504. IdentifierInfo *II = D.getIdentifier();
  7505. SourceLocation Loc = DeclStart;
  7506. if (II) Loc = D.getIdentifierLoc();
  7507. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  7508. QualType T = TInfo->getType();
  7509. if (getLangOptions().CPlusPlus) {
  7510. CheckExtraCXXDefaultArguments(D);
  7511. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  7512. UPPC_DataMemberType)) {
  7513. D.setInvalidType();
  7514. T = Context.IntTy;
  7515. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  7516. }
  7517. }
  7518. DiagnoseFunctionSpecifiers(D);
  7519. if (D.getDeclSpec().isThreadSpecified())
  7520. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  7521. if (D.getDeclSpec().isConstexprSpecified())
  7522. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  7523. << 2;
  7524. // Check to see if this name was declared as a member previously
  7525. NamedDecl *PrevDecl = 0;
  7526. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  7527. LookupName(Previous, S);
  7528. switch (Previous.getResultKind()) {
  7529. case LookupResult::Found:
  7530. case LookupResult::FoundUnresolvedValue:
  7531. PrevDecl = Previous.getAsSingle<NamedDecl>();
  7532. break;
  7533. case LookupResult::FoundOverloaded:
  7534. PrevDecl = Previous.getRepresentativeDecl();
  7535. break;
  7536. case LookupResult::NotFound:
  7537. case LookupResult::NotFoundInCurrentInstantiation:
  7538. case LookupResult::Ambiguous:
  7539. break;
  7540. }
  7541. Previous.suppressDiagnostics();
  7542. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  7543. // Maybe we will complain about the shadowed template parameter.
  7544. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  7545. // Just pretend that we didn't see the previous declaration.
  7546. PrevDecl = 0;
  7547. }
  7548. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  7549. PrevDecl = 0;
  7550. bool Mutable
  7551. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  7552. SourceLocation TSSL = D.getSourceRange().getBegin();
  7553. FieldDecl *NewFD
  7554. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit,
  7555. TSSL, AS, PrevDecl, &D);
  7556. if (NewFD->isInvalidDecl())
  7557. Record->setInvalidDecl();
  7558. if (D.getDeclSpec().isModulePrivateSpecified())
  7559. NewFD->setModulePrivate();
  7560. if (NewFD->isInvalidDecl() && PrevDecl) {
  7561. // Don't introduce NewFD into scope; there's already something
  7562. // with the same name in the same scope.
  7563. } else if (II) {
  7564. PushOnScopeChains(NewFD, S);
  7565. } else
  7566. Record->addDecl(NewFD);
  7567. return NewFD;
  7568. }
  7569. /// \brief Build a new FieldDecl and check its well-formedness.
  7570. ///
  7571. /// This routine builds a new FieldDecl given the fields name, type,
  7572. /// record, etc. \p PrevDecl should refer to any previous declaration
  7573. /// with the same name and in the same scope as the field to be
  7574. /// created.
  7575. ///
  7576. /// \returns a new FieldDecl.
  7577. ///
  7578. /// \todo The Declarator argument is a hack. It will be removed once
  7579. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  7580. TypeSourceInfo *TInfo,
  7581. RecordDecl *Record, SourceLocation Loc,
  7582. bool Mutable, Expr *BitWidth, bool HasInit,
  7583. SourceLocation TSSL,
  7584. AccessSpecifier AS, NamedDecl *PrevDecl,
  7585. Declarator *D) {
  7586. IdentifierInfo *II = Name.getAsIdentifierInfo();
  7587. bool InvalidDecl = false;
  7588. if (D) InvalidDecl = D->isInvalidType();
  7589. // If we receive a broken type, recover by assuming 'int' and
  7590. // marking this declaration as invalid.
  7591. if (T.isNull()) {
  7592. InvalidDecl = true;
  7593. T = Context.IntTy;
  7594. }
  7595. QualType EltTy = Context.getBaseElementType(T);
  7596. if (!EltTy->isDependentType() &&
  7597. RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  7598. // Fields of incomplete type force their record to be invalid.
  7599. Record->setInvalidDecl();
  7600. InvalidDecl = true;
  7601. }
  7602. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  7603. // than a variably modified type.
  7604. if (!InvalidDecl && T->isVariablyModifiedType()) {
  7605. bool SizeIsNegative;
  7606. llvm::APSInt Oversized;
  7607. QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
  7608. SizeIsNegative,
  7609. Oversized);
  7610. if (!FixedTy.isNull()) {
  7611. Diag(Loc, diag::warn_illegal_constant_array_size);
  7612. T = FixedTy;
  7613. } else {
  7614. if (SizeIsNegative)
  7615. Diag(Loc, diag::err_typecheck_negative_array_size);
  7616. else if (Oversized.getBoolValue())
  7617. Diag(Loc, diag::err_array_too_large)
  7618. << Oversized.toString(10);
  7619. else
  7620. Diag(Loc, diag::err_typecheck_field_variable_size);
  7621. InvalidDecl = true;
  7622. }
  7623. }
  7624. // Fields can not have abstract class types
  7625. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  7626. diag::err_abstract_type_in_decl,
  7627. AbstractFieldType))
  7628. InvalidDecl = true;
  7629. bool ZeroWidth = false;
  7630. // If this is declared as a bit-field, check the bit-field.
  7631. if (!InvalidDecl && BitWidth) {
  7632. BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
  7633. if (!BitWidth) {
  7634. InvalidDecl = true;
  7635. BitWidth = 0;
  7636. ZeroWidth = false;
  7637. }
  7638. }
  7639. // Check that 'mutable' is consistent with the type of the declaration.
  7640. if (!InvalidDecl && Mutable) {
  7641. unsigned DiagID = 0;
  7642. if (T->isReferenceType())
  7643. DiagID = diag::err_mutable_reference;
  7644. else if (T.isConstQualified())
  7645. DiagID = diag::err_mutable_const;
  7646. if (DiagID) {
  7647. SourceLocation ErrLoc = Loc;
  7648. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  7649. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  7650. Diag(ErrLoc, DiagID);
  7651. Mutable = false;
  7652. InvalidDecl = true;
  7653. }
  7654. }
  7655. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  7656. BitWidth, Mutable, HasInit);
  7657. if (InvalidDecl)
  7658. NewFD->setInvalidDecl();
  7659. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  7660. Diag(Loc, diag::err_duplicate_member) << II;
  7661. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  7662. NewFD->setInvalidDecl();
  7663. }
  7664. if (!InvalidDecl && getLangOptions().CPlusPlus) {
  7665. if (Record->isUnion()) {
  7666. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  7667. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  7668. if (RDecl->getDefinition()) {
  7669. // C++ [class.union]p1: An object of a class with a non-trivial
  7670. // constructor, a non-trivial copy constructor, a non-trivial
  7671. // destructor, or a non-trivial copy assignment operator
  7672. // cannot be a member of a union, nor can an array of such
  7673. // objects.
  7674. if (CheckNontrivialField(NewFD))
  7675. NewFD->setInvalidDecl();
  7676. }
  7677. }
  7678. // C++ [class.union]p1: If a union contains a member of reference type,
  7679. // the program is ill-formed.
  7680. if (EltTy->isReferenceType()) {
  7681. Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
  7682. << NewFD->getDeclName() << EltTy;
  7683. NewFD->setInvalidDecl();
  7684. }
  7685. }
  7686. }
  7687. // FIXME: We need to pass in the attributes given an AST
  7688. // representation, not a parser representation.
  7689. if (D)
  7690. // FIXME: What to pass instead of TUScope?
  7691. ProcessDeclAttributes(TUScope, NewFD, *D);
  7692. // In auto-retain/release, infer strong retension for fields of
  7693. // retainable type.
  7694. if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  7695. NewFD->setInvalidDecl();
  7696. if (T.isObjCGCWeak())
  7697. Diag(Loc, diag::warn_attribute_weak_on_field);
  7698. NewFD->setAccess(AS);
  7699. return NewFD;
  7700. }
  7701. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  7702. assert(FD);
  7703. assert(getLangOptions().CPlusPlus && "valid check only for C++");
  7704. if (FD->isInvalidDecl())
  7705. return true;
  7706. QualType EltTy = Context.getBaseElementType(FD->getType());
  7707. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  7708. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  7709. if (RDecl->getDefinition()) {
  7710. // We check for copy constructors before constructors
  7711. // because otherwise we'll never get complaints about
  7712. // copy constructors.
  7713. CXXSpecialMember member = CXXInvalid;
  7714. if (!RDecl->hasTrivialCopyConstructor())
  7715. member = CXXCopyConstructor;
  7716. else if (!RDecl->hasTrivialDefaultConstructor())
  7717. member = CXXDefaultConstructor;
  7718. else if (!RDecl->hasTrivialCopyAssignment())
  7719. member = CXXCopyAssignment;
  7720. else if (!RDecl->hasTrivialDestructor())
  7721. member = CXXDestructor;
  7722. if (member != CXXInvalid) {
  7723. if (!getLangOptions().CPlusPlus0x &&
  7724. getLangOptions().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  7725. // Objective-C++ ARC: it is an error to have a non-trivial field of
  7726. // a union. However, system headers in Objective-C programs
  7727. // occasionally have Objective-C lifetime objects within unions,
  7728. // and rather than cause the program to fail, we make those
  7729. // members unavailable.
  7730. SourceLocation Loc = FD->getLocation();
  7731. if (getSourceManager().isInSystemHeader(Loc)) {
  7732. if (!FD->hasAttr<UnavailableAttr>())
  7733. FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
  7734. "this system field has retaining ownership"));
  7735. return false;
  7736. }
  7737. }
  7738. Diag(FD->getLocation(), getLangOptions().CPlusPlus0x ?
  7739. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  7740. diag::err_illegal_union_or_anon_struct_member)
  7741. << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
  7742. DiagnoseNontrivial(RT, member);
  7743. return !getLangOptions().CPlusPlus0x;
  7744. }
  7745. }
  7746. }
  7747. return false;
  7748. }
  7749. /// DiagnoseNontrivial - Given that a class has a non-trivial
  7750. /// special member, figure out why.
  7751. void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
  7752. QualType QT(T, 0U);
  7753. CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
  7754. // Check whether the member was user-declared.
  7755. switch (member) {
  7756. case CXXInvalid:
  7757. break;
  7758. case CXXDefaultConstructor:
  7759. if (RD->hasUserDeclaredConstructor()) {
  7760. typedef CXXRecordDecl::ctor_iterator ctor_iter;
  7761. for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
  7762. const FunctionDecl *body = 0;
  7763. ci->hasBody(body);
  7764. if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
  7765. SourceLocation CtorLoc = ci->getLocation();
  7766. Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
  7767. return;
  7768. }
  7769. }
  7770. llvm_unreachable("found no user-declared constructors");
  7771. }
  7772. break;
  7773. case CXXCopyConstructor:
  7774. if (RD->hasUserDeclaredCopyConstructor()) {
  7775. SourceLocation CtorLoc =
  7776. RD->getCopyConstructor(0)->getLocation();
  7777. Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
  7778. return;
  7779. }
  7780. break;
  7781. case CXXMoveConstructor:
  7782. if (RD->hasUserDeclaredMoveConstructor()) {
  7783. SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
  7784. Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
  7785. return;
  7786. }
  7787. break;
  7788. case CXXCopyAssignment:
  7789. if (RD->hasUserDeclaredCopyAssignment()) {
  7790. // FIXME: this should use the location of the copy
  7791. // assignment, not the type.
  7792. SourceLocation TyLoc = RD->getSourceRange().getBegin();
  7793. Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
  7794. return;
  7795. }
  7796. break;
  7797. case CXXMoveAssignment:
  7798. if (RD->hasUserDeclaredMoveAssignment()) {
  7799. SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
  7800. Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
  7801. return;
  7802. }
  7803. break;
  7804. case CXXDestructor:
  7805. if (RD->hasUserDeclaredDestructor()) {
  7806. SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
  7807. Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
  7808. return;
  7809. }
  7810. break;
  7811. }
  7812. typedef CXXRecordDecl::base_class_iterator base_iter;
  7813. // Virtual bases and members inhibit trivial copying/construction,
  7814. // but not trivial destruction.
  7815. if (member != CXXDestructor) {
  7816. // Check for virtual bases. vbases includes indirect virtual bases,
  7817. // so we just iterate through the direct bases.
  7818. for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
  7819. if (bi->isVirtual()) {
  7820. SourceLocation BaseLoc = bi->getSourceRange().getBegin();
  7821. Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
  7822. return;
  7823. }
  7824. // Check for virtual methods.
  7825. typedef CXXRecordDecl::method_iterator meth_iter;
  7826. for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
  7827. ++mi) {
  7828. if (mi->isVirtual()) {
  7829. SourceLocation MLoc = mi->getSourceRange().getBegin();
  7830. Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
  7831. return;
  7832. }
  7833. }
  7834. }
  7835. bool (CXXRecordDecl::*hasTrivial)() const;
  7836. switch (member) {
  7837. case CXXDefaultConstructor:
  7838. hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
  7839. case CXXCopyConstructor:
  7840. hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
  7841. case CXXCopyAssignment:
  7842. hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
  7843. case CXXDestructor:
  7844. hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
  7845. default:
  7846. llvm_unreachable("unexpected special member");
  7847. }
  7848. // Check for nontrivial bases (and recurse).
  7849. for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
  7850. const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
  7851. assert(BaseRT && "Don't know how to handle dependent bases");
  7852. CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
  7853. if (!(BaseRecTy->*hasTrivial)()) {
  7854. SourceLocation BaseLoc = bi->getSourceRange().getBegin();
  7855. Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
  7856. DiagnoseNontrivial(BaseRT, member);
  7857. return;
  7858. }
  7859. }
  7860. // Check for nontrivial members (and recurse).
  7861. typedef RecordDecl::field_iterator field_iter;
  7862. for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
  7863. ++fi) {
  7864. QualType EltTy = Context.getBaseElementType((*fi)->getType());
  7865. if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
  7866. CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
  7867. if (!(EltRD->*hasTrivial)()) {
  7868. SourceLocation FLoc = (*fi)->getLocation();
  7869. Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
  7870. DiagnoseNontrivial(EltRT, member);
  7871. return;
  7872. }
  7873. }
  7874. if (EltTy->isObjCLifetimeType()) {
  7875. switch (EltTy.getObjCLifetime()) {
  7876. case Qualifiers::OCL_None:
  7877. case Qualifiers::OCL_ExplicitNone:
  7878. break;
  7879. case Qualifiers::OCL_Autoreleasing:
  7880. case Qualifiers::OCL_Weak:
  7881. case Qualifiers::OCL_Strong:
  7882. Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership)
  7883. << QT << EltTy.getObjCLifetime();
  7884. return;
  7885. }
  7886. }
  7887. }
  7888. llvm_unreachable("found no explanation for non-trivial member");
  7889. }
  7890. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  7891. /// AST enum value.
  7892. static ObjCIvarDecl::AccessControl
  7893. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  7894. switch (ivarVisibility) {
  7895. default: llvm_unreachable("Unknown visitibility kind");
  7896. case tok::objc_private: return ObjCIvarDecl::Private;
  7897. case tok::objc_public: return ObjCIvarDecl::Public;
  7898. case tok::objc_protected: return ObjCIvarDecl::Protected;
  7899. case tok::objc_package: return ObjCIvarDecl::Package;
  7900. }
  7901. }
  7902. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  7903. /// in order to create an IvarDecl object for it.
  7904. Decl *Sema::ActOnIvar(Scope *S,
  7905. SourceLocation DeclStart,
  7906. Declarator &D, Expr *BitfieldWidth,
  7907. tok::ObjCKeywordKind Visibility) {
  7908. IdentifierInfo *II = D.getIdentifier();
  7909. Expr *BitWidth = (Expr*)BitfieldWidth;
  7910. SourceLocation Loc = DeclStart;
  7911. if (II) Loc = D.getIdentifierLoc();
  7912. // FIXME: Unnamed fields can be handled in various different ways, for
  7913. // example, unnamed unions inject all members into the struct namespace!
  7914. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  7915. QualType T = TInfo->getType();
  7916. if (BitWidth) {
  7917. // 6.7.2.1p3, 6.7.2.1p4
  7918. BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
  7919. if (!BitWidth)
  7920. D.setInvalidType();
  7921. } else {
  7922. // Not a bitfield.
  7923. // validate II.
  7924. }
  7925. if (T->isReferenceType()) {
  7926. Diag(Loc, diag::err_ivar_reference_type);
  7927. D.setInvalidType();
  7928. }
  7929. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  7930. // than a variably modified type.
  7931. else if (T->isVariablyModifiedType()) {
  7932. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  7933. D.setInvalidType();
  7934. }
  7935. // Get the visibility (access control) for this ivar.
  7936. ObjCIvarDecl::AccessControl ac =
  7937. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  7938. : ObjCIvarDecl::None;
  7939. // Must set ivar's DeclContext to its enclosing interface.
  7940. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  7941. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  7942. return 0;
  7943. ObjCContainerDecl *EnclosingContext;
  7944. if (ObjCImplementationDecl *IMPDecl =
  7945. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  7946. if (!LangOpts.ObjCNonFragileABI2) {
  7947. // Case of ivar declared in an implementation. Context is that of its class.
  7948. EnclosingContext = IMPDecl->getClassInterface();
  7949. assert(EnclosingContext && "Implementation has no class interface!");
  7950. }
  7951. else
  7952. EnclosingContext = EnclosingDecl;
  7953. } else {
  7954. if (ObjCCategoryDecl *CDecl =
  7955. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  7956. if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
  7957. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  7958. return 0;
  7959. }
  7960. }
  7961. EnclosingContext = EnclosingDecl;
  7962. }
  7963. // Construct the decl.
  7964. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  7965. DeclStart, Loc, II, T,
  7966. TInfo, ac, (Expr *)BitfieldWidth);
  7967. if (II) {
  7968. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  7969. ForRedeclaration);
  7970. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  7971. && !isa<TagDecl>(PrevDecl)) {
  7972. Diag(Loc, diag::err_duplicate_member) << II;
  7973. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  7974. NewID->setInvalidDecl();
  7975. }
  7976. }
  7977. // Process attributes attached to the ivar.
  7978. ProcessDeclAttributes(S, NewID, D);
  7979. if (D.isInvalidType())
  7980. NewID->setInvalidDecl();
  7981. // In ARC, infer 'retaining' for ivars of retainable type.
  7982. if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  7983. NewID->setInvalidDecl();
  7984. if (D.getDeclSpec().isModulePrivateSpecified())
  7985. NewID->setModulePrivate();
  7986. if (II) {
  7987. // FIXME: When interfaces are DeclContexts, we'll need to add
  7988. // these to the interface.
  7989. S->AddDecl(NewID);
  7990. IdResolver.AddDecl(NewID);
  7991. }
  7992. return NewID;
  7993. }
  7994. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  7995. /// class and class extensions. For every class @interface and class
  7996. /// extension @interface, if the last ivar is a bitfield of any type,
  7997. /// then add an implicit `char :0` ivar to the end of that interface.
  7998. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  7999. SmallVectorImpl<Decl *> &AllIvarDecls) {
  8000. if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
  8001. return;
  8002. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  8003. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  8004. if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
  8005. return;
  8006. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  8007. if (!ID) {
  8008. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  8009. if (!CD->IsClassExtension())
  8010. return;
  8011. }
  8012. // No need to add this to end of @implementation.
  8013. else
  8014. return;
  8015. }
  8016. // All conditions are met. Add a new bitfield to the tail end of ivars.
  8017. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  8018. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  8019. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  8020. DeclLoc, DeclLoc, 0,
  8021. Context.CharTy,
  8022. Context.getTrivialTypeSourceInfo(Context.CharTy,
  8023. DeclLoc),
  8024. ObjCIvarDecl::Private, BW,
  8025. true);
  8026. AllIvarDecls.push_back(Ivar);
  8027. }
  8028. void Sema::ActOnFields(Scope* S,
  8029. SourceLocation RecLoc, Decl *EnclosingDecl,
  8030. llvm::ArrayRef<Decl *> Fields,
  8031. SourceLocation LBrac, SourceLocation RBrac,
  8032. AttributeList *Attr) {
  8033. assert(EnclosingDecl && "missing record or interface decl");
  8034. // If the decl this is being inserted into is invalid, then it may be a
  8035. // redeclaration or some other bogus case. Don't try to add fields to it.
  8036. if (EnclosingDecl->isInvalidDecl())
  8037. return;
  8038. // Verify that all the fields are okay.
  8039. unsigned NumNamedMembers = 0;
  8040. SmallVector<FieldDecl*, 32> RecFields;
  8041. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  8042. bool ARCErrReported = false;
  8043. for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  8044. i != end; ++i) {
  8045. FieldDecl *FD = cast<FieldDecl>(*i);
  8046. // Get the type for the field.
  8047. const Type *FDTy = FD->getType().getTypePtr();
  8048. if (!FD->isAnonymousStructOrUnion()) {
  8049. // Remember all fields written by the user.
  8050. RecFields.push_back(FD);
  8051. }
  8052. // If the field is already invalid for some reason, don't emit more
  8053. // diagnostics about it.
  8054. if (FD->isInvalidDecl()) {
  8055. EnclosingDecl->setInvalidDecl();
  8056. continue;
  8057. }
  8058. // C99 6.7.2.1p2:
  8059. // A structure or union shall not contain a member with
  8060. // incomplete or function type (hence, a structure shall not
  8061. // contain an instance of itself, but may contain a pointer to
  8062. // an instance of itself), except that the last member of a
  8063. // structure with more than one named member may have incomplete
  8064. // array type; such a structure (and any union containing,
  8065. // possibly recursively, a member that is such a structure)
  8066. // shall not be a member of a structure or an element of an
  8067. // array.
  8068. if (FDTy->isFunctionType()) {
  8069. // Field declared as a function.
  8070. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  8071. << FD->getDeclName();
  8072. FD->setInvalidDecl();
  8073. EnclosingDecl->setInvalidDecl();
  8074. continue;
  8075. } else if (FDTy->isIncompleteArrayType() && Record &&
  8076. ((i + 1 == Fields.end() && !Record->isUnion()) ||
  8077. ((getLangOptions().MicrosoftExt ||
  8078. getLangOptions().CPlusPlus) &&
  8079. (i + 1 == Fields.end() || Record->isUnion())))) {
  8080. // Flexible array member.
  8081. // Microsoft and g++ is more permissive regarding flexible array.
  8082. // It will accept flexible array in union and also
  8083. // as the sole element of a struct/class.
  8084. if (getLangOptions().MicrosoftExt) {
  8085. if (Record->isUnion())
  8086. Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
  8087. << FD->getDeclName();
  8088. else if (Fields.size() == 1)
  8089. Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
  8090. << FD->getDeclName() << Record->getTagKind();
  8091. } else if (getLangOptions().CPlusPlus) {
  8092. if (Record->isUnion())
  8093. Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
  8094. << FD->getDeclName();
  8095. else if (Fields.size() == 1)
  8096. Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
  8097. << FD->getDeclName() << Record->getTagKind();
  8098. } else if (NumNamedMembers < 1) {
  8099. Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
  8100. << FD->getDeclName();
  8101. FD->setInvalidDecl();
  8102. EnclosingDecl->setInvalidDecl();
  8103. continue;
  8104. }
  8105. if (!FD->getType()->isDependentType() &&
  8106. !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
  8107. Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
  8108. << FD->getDeclName() << FD->getType();
  8109. FD->setInvalidDecl();
  8110. EnclosingDecl->setInvalidDecl();
  8111. continue;
  8112. }
  8113. // Okay, we have a legal flexible array member at the end of the struct.
  8114. if (Record)
  8115. Record->setHasFlexibleArrayMember(true);
  8116. } else if (!FDTy->isDependentType() &&
  8117. RequireCompleteType(FD->getLocation(), FD->getType(),
  8118. diag::err_field_incomplete)) {
  8119. // Incomplete type
  8120. FD->setInvalidDecl();
  8121. EnclosingDecl->setInvalidDecl();
  8122. continue;
  8123. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  8124. if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
  8125. // If this is a member of a union, then entire union becomes "flexible".
  8126. if (Record && Record->isUnion()) {
  8127. Record->setHasFlexibleArrayMember(true);
  8128. } else {
  8129. // If this is a struct/class and this is not the last element, reject
  8130. // it. Note that GCC supports variable sized arrays in the middle of
  8131. // structures.
  8132. if (i + 1 != Fields.end())
  8133. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  8134. << FD->getDeclName() << FD->getType();
  8135. else {
  8136. // We support flexible arrays at the end of structs in
  8137. // other structs as an extension.
  8138. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  8139. << FD->getDeclName();
  8140. if (Record)
  8141. Record->setHasFlexibleArrayMember(true);
  8142. }
  8143. }
  8144. }
  8145. if (Record && FDTTy->getDecl()->hasObjectMember())
  8146. Record->setHasObjectMember(true);
  8147. } else if (FDTy->isObjCObjectType()) {
  8148. /// A field cannot be an Objective-c object
  8149. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  8150. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  8151. QualType T = Context.getObjCObjectPointerType(FD->getType());
  8152. FD->setType(T);
  8153. }
  8154. else if (!getLangOptions().CPlusPlus) {
  8155. if (getLangOptions().ObjCAutoRefCount && Record && !ARCErrReported) {
  8156. // It's an error in ARC if a field has lifetime.
  8157. // We don't want to report this in a system header, though,
  8158. // so we just make the field unavailable.
  8159. // FIXME: that's really not sufficient; we need to make the type
  8160. // itself invalid to, say, initialize or copy.
  8161. QualType T = FD->getType();
  8162. Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
  8163. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
  8164. SourceLocation loc = FD->getLocation();
  8165. if (getSourceManager().isInSystemHeader(loc)) {
  8166. if (!FD->hasAttr<UnavailableAttr>()) {
  8167. FD->addAttr(new (Context) UnavailableAttr(loc, Context,
  8168. "this system field has retaining ownership"));
  8169. }
  8170. } else {
  8171. Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
  8172. << T->isBlockPointerType();
  8173. }
  8174. ARCErrReported = true;
  8175. }
  8176. }
  8177. else if (getLangOptions().ObjC1 &&
  8178. getLangOptions().getGC() != LangOptions::NonGC &&
  8179. Record && !Record->hasObjectMember()) {
  8180. if (FD->getType()->isObjCObjectPointerType() ||
  8181. FD->getType().isObjCGCStrong())
  8182. Record->setHasObjectMember(true);
  8183. else if (Context.getAsArrayType(FD->getType())) {
  8184. QualType BaseType = Context.getBaseElementType(FD->getType());
  8185. if (BaseType->isRecordType() &&
  8186. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  8187. Record->setHasObjectMember(true);
  8188. else if (BaseType->isObjCObjectPointerType() ||
  8189. BaseType.isObjCGCStrong())
  8190. Record->setHasObjectMember(true);
  8191. }
  8192. }
  8193. }
  8194. // Keep track of the number of named members.
  8195. if (FD->getIdentifier())
  8196. ++NumNamedMembers;
  8197. }
  8198. // Okay, we successfully defined 'Record'.
  8199. if (Record) {
  8200. bool Completed = false;
  8201. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  8202. if (!CXXRecord->isInvalidDecl()) {
  8203. // Set access bits correctly on the directly-declared conversions.
  8204. UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
  8205. for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
  8206. I != E; ++I)
  8207. Convs->setAccess(I, (*I)->getAccess());
  8208. if (!CXXRecord->isDependentType()) {
  8209. // Objective-C Automatic Reference Counting:
  8210. // If a class has a non-static data member of Objective-C pointer
  8211. // type (or array thereof), it is a non-POD type and its
  8212. // default constructor (if any), copy constructor, copy assignment
  8213. // operator, and destructor are non-trivial.
  8214. //
  8215. // This rule is also handled by CXXRecordDecl::completeDefinition().
  8216. // However, here we check whether this particular class is only
  8217. // non-POD because of the presence of an Objective-C pointer member.
  8218. // If so, objects of this type cannot be shared between code compiled
  8219. // with instant objects and code compiled with manual retain/release.
  8220. if (getLangOptions().ObjCAutoRefCount &&
  8221. CXXRecord->hasObjectMember() &&
  8222. CXXRecord->getLinkage() == ExternalLinkage) {
  8223. if (CXXRecord->isPOD()) {
  8224. Diag(CXXRecord->getLocation(),
  8225. diag::warn_arc_non_pod_class_with_object_member)
  8226. << CXXRecord;
  8227. } else {
  8228. // FIXME: Fix-Its would be nice here, but finding a good location
  8229. // for them is going to be tricky.
  8230. if (CXXRecord->hasTrivialCopyConstructor())
  8231. Diag(CXXRecord->getLocation(),
  8232. diag::warn_arc_trivial_member_function_with_object_member)
  8233. << CXXRecord << 0;
  8234. if (CXXRecord->hasTrivialCopyAssignment())
  8235. Diag(CXXRecord->getLocation(),
  8236. diag::warn_arc_trivial_member_function_with_object_member)
  8237. << CXXRecord << 1;
  8238. if (CXXRecord->hasTrivialDestructor())
  8239. Diag(CXXRecord->getLocation(),
  8240. diag::warn_arc_trivial_member_function_with_object_member)
  8241. << CXXRecord << 2;
  8242. }
  8243. }
  8244. // Adjust user-defined destructor exception spec.
  8245. if (getLangOptions().CPlusPlus0x &&
  8246. CXXRecord->hasUserDeclaredDestructor())
  8247. AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
  8248. // Add any implicitly-declared members to this class.
  8249. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  8250. // If we have virtual base classes, we may end up finding multiple
  8251. // final overriders for a given virtual function. Check for this
  8252. // problem now.
  8253. if (CXXRecord->getNumVBases()) {
  8254. CXXFinalOverriderMap FinalOverriders;
  8255. CXXRecord->getFinalOverriders(FinalOverriders);
  8256. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  8257. MEnd = FinalOverriders.end();
  8258. M != MEnd; ++M) {
  8259. for (OverridingMethods::iterator SO = M->second.begin(),
  8260. SOEnd = M->second.end();
  8261. SO != SOEnd; ++SO) {
  8262. assert(SO->second.size() > 0 &&
  8263. "Virtual function without overridding functions?");
  8264. if (SO->second.size() == 1)
  8265. continue;
  8266. // C++ [class.virtual]p2:
  8267. // In a derived class, if a virtual member function of a base
  8268. // class subobject has more than one final overrider the
  8269. // program is ill-formed.
  8270. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  8271. << (NamedDecl *)M->first << Record;
  8272. Diag(M->first->getLocation(),
  8273. diag::note_overridden_virtual_function);
  8274. for (OverridingMethods::overriding_iterator
  8275. OM = SO->second.begin(),
  8276. OMEnd = SO->second.end();
  8277. OM != OMEnd; ++OM)
  8278. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  8279. << (NamedDecl *)M->first << OM->Method->getParent();
  8280. Record->setInvalidDecl();
  8281. }
  8282. }
  8283. CXXRecord->completeDefinition(&FinalOverriders);
  8284. Completed = true;
  8285. }
  8286. }
  8287. }
  8288. }
  8289. if (!Completed)
  8290. Record->completeDefinition();
  8291. // Now that the record is complete, do any delayed exception spec checks
  8292. // we were missing.
  8293. while (!DelayedDestructorExceptionSpecChecks.empty()) {
  8294. const CXXDestructorDecl *Dtor =
  8295. DelayedDestructorExceptionSpecChecks.back().first;
  8296. if (Dtor->getParent() != Record)
  8297. break;
  8298. assert(!Dtor->getParent()->isDependentType() &&
  8299. "Should not ever add destructors of templates into the list.");
  8300. CheckOverridingFunctionExceptionSpec(Dtor,
  8301. DelayedDestructorExceptionSpecChecks.back().second);
  8302. DelayedDestructorExceptionSpecChecks.pop_back();
  8303. }
  8304. } else {
  8305. ObjCIvarDecl **ClsFields =
  8306. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  8307. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  8308. ID->setEndOfDefinitionLoc(RBrac);
  8309. // Add ivar's to class's DeclContext.
  8310. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  8311. ClsFields[i]->setLexicalDeclContext(ID);
  8312. ID->addDecl(ClsFields[i]);
  8313. }
  8314. // Must enforce the rule that ivars in the base classes may not be
  8315. // duplicates.
  8316. if (ID->getSuperClass())
  8317. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  8318. } else if (ObjCImplementationDecl *IMPDecl =
  8319. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  8320. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  8321. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  8322. // Ivar declared in @implementation never belongs to the implementation.
  8323. // Only it is in implementation's lexical context.
  8324. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  8325. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  8326. } else if (ObjCCategoryDecl *CDecl =
  8327. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  8328. // case of ivars in class extension; all other cases have been
  8329. // reported as errors elsewhere.
  8330. // FIXME. Class extension does not have a LocEnd field.
  8331. // CDecl->setLocEnd(RBrac);
  8332. // Add ivar's to class extension's DeclContext.
  8333. // Diagnose redeclaration of private ivars.
  8334. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  8335. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  8336. if (IDecl) {
  8337. if (const ObjCIvarDecl *ClsIvar =
  8338. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  8339. Diag(ClsFields[i]->getLocation(),
  8340. diag::err_duplicate_ivar_declaration);
  8341. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  8342. continue;
  8343. }
  8344. for (const ObjCCategoryDecl *ClsExtDecl =
  8345. IDecl->getFirstClassExtension();
  8346. ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
  8347. if (const ObjCIvarDecl *ClsExtIvar =
  8348. ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  8349. Diag(ClsFields[i]->getLocation(),
  8350. diag::err_duplicate_ivar_declaration);
  8351. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  8352. continue;
  8353. }
  8354. }
  8355. }
  8356. ClsFields[i]->setLexicalDeclContext(CDecl);
  8357. CDecl->addDecl(ClsFields[i]);
  8358. }
  8359. }
  8360. }
  8361. if (Attr)
  8362. ProcessDeclAttributeList(S, Record, Attr);
  8363. // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
  8364. // set the visibility of this record.
  8365. if (Record && !Record->getDeclContext()->isRecord())
  8366. AddPushedVisibilityAttribute(Record);
  8367. }
  8368. /// \brief Determine whether the given integral value is representable within
  8369. /// the given type T.
  8370. static bool isRepresentableIntegerValue(ASTContext &Context,
  8371. llvm::APSInt &Value,
  8372. QualType T) {
  8373. assert(T->isIntegralType(Context) && "Integral type required!");
  8374. unsigned BitWidth = Context.getIntWidth(T);
  8375. if (Value.isUnsigned() || Value.isNonNegative()) {
  8376. if (T->isSignedIntegerOrEnumerationType())
  8377. --BitWidth;
  8378. return Value.getActiveBits() <= BitWidth;
  8379. }
  8380. return Value.getMinSignedBits() <= BitWidth;
  8381. }
  8382. // \brief Given an integral type, return the next larger integral type
  8383. // (or a NULL type of no such type exists).
  8384. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  8385. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  8386. // enum checking below.
  8387. assert(T->isIntegralType(Context) && "Integral type required!");
  8388. const unsigned NumTypes = 4;
  8389. QualType SignedIntegralTypes[NumTypes] = {
  8390. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  8391. };
  8392. QualType UnsignedIntegralTypes[NumTypes] = {
  8393. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  8394. Context.UnsignedLongLongTy
  8395. };
  8396. unsigned BitWidth = Context.getTypeSize(T);
  8397. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  8398. : UnsignedIntegralTypes;
  8399. for (unsigned I = 0; I != NumTypes; ++I)
  8400. if (Context.getTypeSize(Types[I]) > BitWidth)
  8401. return Types[I];
  8402. return QualType();
  8403. }
  8404. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  8405. EnumConstantDecl *LastEnumConst,
  8406. SourceLocation IdLoc,
  8407. IdentifierInfo *Id,
  8408. Expr *Val) {
  8409. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  8410. llvm::APSInt EnumVal(IntWidth);
  8411. QualType EltTy;
  8412. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  8413. Val = 0;
  8414. if (Val)
  8415. Val = DefaultLvalueConversion(Val).take();
  8416. if (Val) {
  8417. if (Enum->isDependentType() || Val->isTypeDependent())
  8418. EltTy = Context.DependentTy;
  8419. else {
  8420. SourceLocation ExpLoc;
  8421. if (getLangOptions().CPlusPlus0x && Enum->isFixed() &&
  8422. !getLangOptions().MicrosoftMode) {
  8423. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  8424. // constant-expression in the enumerator-definition shall be a converted
  8425. // constant expression of the underlying type.
  8426. EltTy = Enum->getIntegerType();
  8427. ExprResult Converted =
  8428. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  8429. CCEK_Enumerator);
  8430. if (Converted.isInvalid())
  8431. Val = 0;
  8432. else
  8433. Val = Converted.take();
  8434. } else if (!Val->isValueDependent() &&
  8435. !(Val = VerifyIntegerConstantExpression(Val,
  8436. &EnumVal).take())) {
  8437. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  8438. } else {
  8439. if (!getLangOptions().CPlusPlus) {
  8440. // C99 6.7.2.2p2:
  8441. // The expression that defines the value of an enumeration constant
  8442. // shall be an integer constant expression that has a value
  8443. // representable as an int.
  8444. // Complain if the value is not representable in an int.
  8445. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  8446. Diag(IdLoc, diag::ext_enum_value_not_int)
  8447. << EnumVal.toString(10) << Val->getSourceRange()
  8448. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  8449. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  8450. // Force the type of the expression to 'int'.
  8451. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
  8452. }
  8453. }
  8454. if (Enum->isFixed()) {
  8455. EltTy = Enum->getIntegerType();
  8456. // In Obj-C and Microsoft mode, require the enumeration value to be
  8457. // representable in the underlying type of the enumeration. In C++11,
  8458. // we perform a non-narrowing conversion as part of converted constant
  8459. // expression checking.
  8460. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  8461. if (getLangOptions().MicrosoftExt) {
  8462. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  8463. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
  8464. } else
  8465. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  8466. } else
  8467. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
  8468. } else {
  8469. // C++11 [dcl.enum]p5:
  8470. // If the underlying type is not fixed, the type of each enumerator
  8471. // is the type of its initializing value:
  8472. // - If an initializer is specified for an enumerator, the
  8473. // initializing value has the same type as the expression.
  8474. EltTy = Val->getType();
  8475. }
  8476. }
  8477. }
  8478. }
  8479. if (!Val) {
  8480. if (Enum->isDependentType())
  8481. EltTy = Context.DependentTy;
  8482. else if (!LastEnumConst) {
  8483. // C++0x [dcl.enum]p5:
  8484. // If the underlying type is not fixed, the type of each enumerator
  8485. // is the type of its initializing value:
  8486. // - If no initializer is specified for the first enumerator, the
  8487. // initializing value has an unspecified integral type.
  8488. //
  8489. // GCC uses 'int' for its unspecified integral type, as does
  8490. // C99 6.7.2.2p3.
  8491. if (Enum->isFixed()) {
  8492. EltTy = Enum->getIntegerType();
  8493. }
  8494. else {
  8495. EltTy = Context.IntTy;
  8496. }
  8497. } else {
  8498. // Assign the last value + 1.
  8499. EnumVal = LastEnumConst->getInitVal();
  8500. ++EnumVal;
  8501. EltTy = LastEnumConst->getType();
  8502. // Check for overflow on increment.
  8503. if (EnumVal < LastEnumConst->getInitVal()) {
  8504. // C++0x [dcl.enum]p5:
  8505. // If the underlying type is not fixed, the type of each enumerator
  8506. // is the type of its initializing value:
  8507. //
  8508. // - Otherwise the type of the initializing value is the same as
  8509. // the type of the initializing value of the preceding enumerator
  8510. // unless the incremented value is not representable in that type,
  8511. // in which case the type is an unspecified integral type
  8512. // sufficient to contain the incremented value. If no such type
  8513. // exists, the program is ill-formed.
  8514. QualType T = getNextLargerIntegralType(Context, EltTy);
  8515. if (T.isNull() || Enum->isFixed()) {
  8516. // There is no integral type larger enough to represent this
  8517. // value. Complain, then allow the value to wrap around.
  8518. EnumVal = LastEnumConst->getInitVal();
  8519. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  8520. ++EnumVal;
  8521. if (Enum->isFixed())
  8522. // When the underlying type is fixed, this is ill-formed.
  8523. Diag(IdLoc, diag::err_enumerator_wrapped)
  8524. << EnumVal.toString(10)
  8525. << EltTy;
  8526. else
  8527. Diag(IdLoc, diag::warn_enumerator_too_large)
  8528. << EnumVal.toString(10);
  8529. } else {
  8530. EltTy = T;
  8531. }
  8532. // Retrieve the last enumerator's value, extent that type to the
  8533. // type that is supposed to be large enough to represent the incremented
  8534. // value, then increment.
  8535. EnumVal = LastEnumConst->getInitVal();
  8536. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  8537. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  8538. ++EnumVal;
  8539. // If we're not in C++, diagnose the overflow of enumerator values,
  8540. // which in C99 means that the enumerator value is not representable in
  8541. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  8542. // permits enumerator values that are representable in some larger
  8543. // integral type.
  8544. if (!getLangOptions().CPlusPlus && !T.isNull())
  8545. Diag(IdLoc, diag::warn_enum_value_overflow);
  8546. } else if (!getLangOptions().CPlusPlus &&
  8547. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  8548. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  8549. Diag(IdLoc, diag::ext_enum_value_not_int)
  8550. << EnumVal.toString(10) << 1;
  8551. }
  8552. }
  8553. }
  8554. if (!EltTy->isDependentType()) {
  8555. // Make the enumerator value match the signedness and size of the
  8556. // enumerator's type.
  8557. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  8558. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  8559. }
  8560. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  8561. Val, EnumVal);
  8562. }
  8563. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  8564. SourceLocation IdLoc, IdentifierInfo *Id,
  8565. AttributeList *Attr,
  8566. SourceLocation EqualLoc, Expr *Val) {
  8567. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  8568. EnumConstantDecl *LastEnumConst =
  8569. cast_or_null<EnumConstantDecl>(lastEnumConst);
  8570. // The scope passed in may not be a decl scope. Zip up the scope tree until
  8571. // we find one that is.
  8572. S = getNonFieldDeclScope(S);
  8573. // Verify that there isn't already something declared with this name in this
  8574. // scope.
  8575. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  8576. ForRedeclaration);
  8577. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  8578. // Maybe we will complain about the shadowed template parameter.
  8579. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  8580. // Just pretend that we didn't see the previous declaration.
  8581. PrevDecl = 0;
  8582. }
  8583. if (PrevDecl) {
  8584. // When in C++, we may get a TagDecl with the same name; in this case the
  8585. // enum constant will 'hide' the tag.
  8586. assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  8587. "Received TagDecl when not in C++!");
  8588. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  8589. if (isa<EnumConstantDecl>(PrevDecl))
  8590. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  8591. else
  8592. Diag(IdLoc, diag::err_redefinition) << Id;
  8593. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  8594. return 0;
  8595. }
  8596. }
  8597. // C++ [class.mem]p13:
  8598. // If T is the name of a class, then each of the following shall have a
  8599. // name different from T:
  8600. // - every enumerator of every member of class T that is an enumerated
  8601. // type
  8602. if (CXXRecordDecl *Record
  8603. = dyn_cast<CXXRecordDecl>(
  8604. TheEnumDecl->getDeclContext()->getRedeclContext()))
  8605. if (Record->getIdentifier() && Record->getIdentifier() == Id)
  8606. Diag(IdLoc, diag::err_member_name_of_class) << Id;
  8607. EnumConstantDecl *New =
  8608. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  8609. if (New) {
  8610. // Process attributes.
  8611. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  8612. // Register this decl in the current scope stack.
  8613. New->setAccess(TheEnumDecl->getAccess());
  8614. PushOnScopeChains(New, S);
  8615. }
  8616. return New;
  8617. }
  8618. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
  8619. SourceLocation RBraceLoc, Decl *EnumDeclX,
  8620. Decl **Elements, unsigned NumElements,
  8621. Scope *S, AttributeList *Attr) {
  8622. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  8623. QualType EnumType = Context.getTypeDeclType(Enum);
  8624. if (Attr)
  8625. ProcessDeclAttributeList(S, Enum, Attr);
  8626. if (Enum->isDependentType()) {
  8627. for (unsigned i = 0; i != NumElements; ++i) {
  8628. EnumConstantDecl *ECD =
  8629. cast_or_null<EnumConstantDecl>(Elements[i]);
  8630. if (!ECD) continue;
  8631. ECD->setType(EnumType);
  8632. }
  8633. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  8634. return;
  8635. }
  8636. // TODO: If the result value doesn't fit in an int, it must be a long or long
  8637. // long value. ISO C does not support this, but GCC does as an extension,
  8638. // emit a warning.
  8639. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  8640. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  8641. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  8642. // Verify that all the values are okay, compute the size of the values, and
  8643. // reverse the list.
  8644. unsigned NumNegativeBits = 0;
  8645. unsigned NumPositiveBits = 0;
  8646. // Keep track of whether all elements have type int.
  8647. bool AllElementsInt = true;
  8648. for (unsigned i = 0; i != NumElements; ++i) {
  8649. EnumConstantDecl *ECD =
  8650. cast_or_null<EnumConstantDecl>(Elements[i]);
  8651. if (!ECD) continue; // Already issued a diagnostic.
  8652. const llvm::APSInt &InitVal = ECD->getInitVal();
  8653. // Keep track of the size of positive and negative values.
  8654. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  8655. NumPositiveBits = std::max(NumPositiveBits,
  8656. (unsigned)InitVal.getActiveBits());
  8657. else
  8658. NumNegativeBits = std::max(NumNegativeBits,
  8659. (unsigned)InitVal.getMinSignedBits());
  8660. // Keep track of whether every enum element has type int (very commmon).
  8661. if (AllElementsInt)
  8662. AllElementsInt = ECD->getType() == Context.IntTy;
  8663. }
  8664. // Figure out the type that should be used for this enum.
  8665. QualType BestType;
  8666. unsigned BestWidth;
  8667. // C++0x N3000 [conv.prom]p3:
  8668. // An rvalue of an unscoped enumeration type whose underlying
  8669. // type is not fixed can be converted to an rvalue of the first
  8670. // of the following types that can represent all the values of
  8671. // the enumeration: int, unsigned int, long int, unsigned long
  8672. // int, long long int, or unsigned long long int.
  8673. // C99 6.4.4.3p2:
  8674. // An identifier declared as an enumeration constant has type int.
  8675. // The C99 rule is modified by a gcc extension
  8676. QualType BestPromotionType;
  8677. bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
  8678. // -fshort-enums is the equivalent to specifying the packed attribute on all
  8679. // enum definitions.
  8680. if (LangOpts.ShortEnums)
  8681. Packed = true;
  8682. if (Enum->isFixed()) {
  8683. BestType = Enum->getIntegerType();
  8684. if (BestType->isPromotableIntegerType())
  8685. BestPromotionType = Context.getPromotedIntegerType(BestType);
  8686. else
  8687. BestPromotionType = BestType;
  8688. // We don't need to set BestWidth, because BestType is going to be the type
  8689. // of the enumerators, but we do anyway because otherwise some compilers
  8690. // warn that it might be used uninitialized.
  8691. BestWidth = CharWidth;
  8692. }
  8693. else if (NumNegativeBits) {
  8694. // If there is a negative value, figure out the smallest integer type (of
  8695. // int/long/longlong) that fits.
  8696. // If it's packed, check also if it fits a char or a short.
  8697. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  8698. BestType = Context.SignedCharTy;
  8699. BestWidth = CharWidth;
  8700. } else if (Packed && NumNegativeBits <= ShortWidth &&
  8701. NumPositiveBits < ShortWidth) {
  8702. BestType = Context.ShortTy;
  8703. BestWidth = ShortWidth;
  8704. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  8705. BestType = Context.IntTy;
  8706. BestWidth = IntWidth;
  8707. } else {
  8708. BestWidth = Context.getTargetInfo().getLongWidth();
  8709. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  8710. BestType = Context.LongTy;
  8711. } else {
  8712. BestWidth = Context.getTargetInfo().getLongLongWidth();
  8713. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  8714. Diag(Enum->getLocation(), diag::warn_enum_too_large);
  8715. BestType = Context.LongLongTy;
  8716. }
  8717. }
  8718. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  8719. } else {
  8720. // If there is no negative value, figure out the smallest type that fits
  8721. // all of the enumerator values.
  8722. // If it's packed, check also if it fits a char or a short.
  8723. if (Packed && NumPositiveBits <= CharWidth) {
  8724. BestType = Context.UnsignedCharTy;
  8725. BestPromotionType = Context.IntTy;
  8726. BestWidth = CharWidth;
  8727. } else if (Packed && NumPositiveBits <= ShortWidth) {
  8728. BestType = Context.UnsignedShortTy;
  8729. BestPromotionType = Context.IntTy;
  8730. BestWidth = ShortWidth;
  8731. } else if (NumPositiveBits <= IntWidth) {
  8732. BestType = Context.UnsignedIntTy;
  8733. BestWidth = IntWidth;
  8734. BestPromotionType
  8735. = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
  8736. ? Context.UnsignedIntTy : Context.IntTy;
  8737. } else if (NumPositiveBits <=
  8738. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  8739. BestType = Context.UnsignedLongTy;
  8740. BestPromotionType
  8741. = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
  8742. ? Context.UnsignedLongTy : Context.LongTy;
  8743. } else {
  8744. BestWidth = Context.getTargetInfo().getLongLongWidth();
  8745. assert(NumPositiveBits <= BestWidth &&
  8746. "How could an initializer get larger than ULL?");
  8747. BestType = Context.UnsignedLongLongTy;
  8748. BestPromotionType
  8749. = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
  8750. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  8751. }
  8752. }
  8753. // Loop over all of the enumerator constants, changing their types to match
  8754. // the type of the enum if needed.
  8755. for (unsigned i = 0; i != NumElements; ++i) {
  8756. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  8757. if (!ECD) continue; // Already issued a diagnostic.
  8758. // Standard C says the enumerators have int type, but we allow, as an
  8759. // extension, the enumerators to be larger than int size. If each
  8760. // enumerator value fits in an int, type it as an int, otherwise type it the
  8761. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  8762. // that X has type 'int', not 'unsigned'.
  8763. // Determine whether the value fits into an int.
  8764. llvm::APSInt InitVal = ECD->getInitVal();
  8765. // If it fits into an integer type, force it. Otherwise force it to match
  8766. // the enum decl type.
  8767. QualType NewTy;
  8768. unsigned NewWidth;
  8769. bool NewSign;
  8770. if (!getLangOptions().CPlusPlus &&
  8771. !Enum->isFixed() &&
  8772. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  8773. NewTy = Context.IntTy;
  8774. NewWidth = IntWidth;
  8775. NewSign = true;
  8776. } else if (ECD->getType() == BestType) {
  8777. // Already the right type!
  8778. if (getLangOptions().CPlusPlus)
  8779. // C++ [dcl.enum]p4: Following the closing brace of an
  8780. // enum-specifier, each enumerator has the type of its
  8781. // enumeration.
  8782. ECD->setType(EnumType);
  8783. continue;
  8784. } else {
  8785. NewTy = BestType;
  8786. NewWidth = BestWidth;
  8787. NewSign = BestType->isSignedIntegerOrEnumerationType();
  8788. }
  8789. // Adjust the APSInt value.
  8790. InitVal = InitVal.extOrTrunc(NewWidth);
  8791. InitVal.setIsSigned(NewSign);
  8792. ECD->setInitVal(InitVal);
  8793. // Adjust the Expr initializer and type.
  8794. if (ECD->getInitExpr() &&
  8795. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  8796. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  8797. CK_IntegralCast,
  8798. ECD->getInitExpr(),
  8799. /*base paths*/ 0,
  8800. VK_RValue));
  8801. if (getLangOptions().CPlusPlus)
  8802. // C++ [dcl.enum]p4: Following the closing brace of an
  8803. // enum-specifier, each enumerator has the type of its
  8804. // enumeration.
  8805. ECD->setType(EnumType);
  8806. else
  8807. ECD->setType(NewTy);
  8808. }
  8809. Enum->completeDefinition(BestType, BestPromotionType,
  8810. NumPositiveBits, NumNegativeBits);
  8811. }
  8812. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  8813. SourceLocation StartLoc,
  8814. SourceLocation EndLoc) {
  8815. StringLiteral *AsmString = cast<StringLiteral>(expr);
  8816. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  8817. AsmString, StartLoc,
  8818. EndLoc);
  8819. CurContext->addDecl(New);
  8820. return New;
  8821. }
  8822. DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
  8823. SourceLocation ImportLoc,
  8824. ModuleIdPath Path) {
  8825. Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
  8826. Module::AllVisible,
  8827. /*IsIncludeDirective=*/false);
  8828. if (!Mod)
  8829. return true;
  8830. llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
  8831. Module *ModCheck = Mod;
  8832. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  8833. // If we've run out of module parents, just drop the remaining identifiers.
  8834. // We need the length to be consistent.
  8835. if (!ModCheck)
  8836. break;
  8837. ModCheck = ModCheck->Parent;
  8838. IdentifierLocs.push_back(Path[I].second);
  8839. }
  8840. ImportDecl *Import = ImportDecl::Create(Context,
  8841. Context.getTranslationUnitDecl(),
  8842. AtLoc.isValid()? AtLoc : ImportLoc,
  8843. Mod, IdentifierLocs);
  8844. Context.getTranslationUnitDecl()->addDecl(Import);
  8845. return Import;
  8846. }
  8847. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  8848. SourceLocation PragmaLoc,
  8849. SourceLocation NameLoc) {
  8850. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  8851. if (PrevDecl) {
  8852. PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
  8853. } else {
  8854. (void)WeakUndeclaredIdentifiers.insert(
  8855. std::pair<IdentifierInfo*,WeakInfo>
  8856. (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
  8857. }
  8858. }
  8859. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  8860. IdentifierInfo* AliasName,
  8861. SourceLocation PragmaLoc,
  8862. SourceLocation NameLoc,
  8863. SourceLocation AliasNameLoc) {
  8864. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  8865. LookupOrdinaryName);
  8866. WeakInfo W = WeakInfo(Name, NameLoc);
  8867. if (PrevDecl) {
  8868. if (!PrevDecl->hasAttr<AliasAttr>())
  8869. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  8870. DeclApplyPragmaWeak(TUScope, ND, W);
  8871. } else {
  8872. (void)WeakUndeclaredIdentifiers.insert(
  8873. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  8874. }
  8875. }
  8876. Decl *Sema::getObjCDeclContext() const {
  8877. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  8878. }
  8879. AvailabilityResult Sema::getCurContextAvailability() const {
  8880. const Decl *D = cast<Decl>(getCurLexicalContext());
  8881. // A category implicitly has the availability of the interface.
  8882. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
  8883. D = CatD->getClassInterface();
  8884. return D->getAvailability();
  8885. }