SemaDecl.cpp 444 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585
  1. //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for declarations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "TypeLocBuilder.h"
  15. #include "clang/AST/ASTConsumer.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/CommentDiagnostic.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclTemplate.h"
  23. #include "clang/AST/EvaluatedExprVisitor.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/StmtCXX.h"
  26. #include "clang/Basic/PartialDiagnostic.h"
  27. #include "clang/Basic/SourceManager.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
  30. #include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
  31. #include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
  32. #include "clang/Parse/ParseDiagnostic.h"
  33. #include "clang/Sema/CXXFieldCollector.h"
  34. #include "clang/Sema/DeclSpec.h"
  35. #include "clang/Sema/DelayedDiagnostic.h"
  36. #include "clang/Sema/Initialization.h"
  37. #include "clang/Sema/Lookup.h"
  38. #include "clang/Sema/ParsedTemplate.h"
  39. #include "clang/Sema/Scope.h"
  40. #include "clang/Sema/ScopeInfo.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, bool WantClass=false)
  59. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
  60. WantExpressionKeywords = false;
  61. WantCXXNamedCasts = false;
  62. WantRemainingKeywords = false;
  63. }
  64. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  65. if (NamedDecl *ND = candidate.getCorrectionDecl())
  66. return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
  67. (AllowInvalidDecl || !ND->isInvalidDecl());
  68. else
  69. return !WantClassName && candidate.isKeyword();
  70. }
  71. private:
  72. bool AllowInvalidDecl;
  73. bool WantClassName;
  74. };
  75. }
  76. /// \brief Determine whether the token kind starts a simple-type-specifier.
  77. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  78. switch (Kind) {
  79. // FIXME: Take into account the current language when deciding whether a
  80. // token kind is a valid type specifier
  81. case tok::kw_short:
  82. case tok::kw_long:
  83. case tok::kw___int64:
  84. case tok::kw___int128:
  85. case tok::kw_signed:
  86. case tok::kw_unsigned:
  87. case tok::kw_void:
  88. case tok::kw_char:
  89. case tok::kw_int:
  90. case tok::kw_half:
  91. case tok::kw_float:
  92. case tok::kw_double:
  93. case tok::kw_wchar_t:
  94. case tok::kw_bool:
  95. case tok::kw___underlying_type:
  96. return true;
  97. case tok::annot_typename:
  98. case tok::kw_char16_t:
  99. case tok::kw_char32_t:
  100. case tok::kw_typeof:
  101. case tok::kw_decltype:
  102. return getLangOpts().CPlusPlus;
  103. default:
  104. break;
  105. }
  106. return false;
  107. }
  108. /// \brief If the identifier refers to a type name within this scope,
  109. /// return the declaration of that type.
  110. ///
  111. /// This routine performs ordinary name lookup of the identifier II
  112. /// within the given scope, with optional C++ scope specifier SS, to
  113. /// determine whether the name refers to a type. If so, returns an
  114. /// opaque pointer (actually a QualType) corresponding to that
  115. /// type. Otherwise, returns NULL.
  116. ///
  117. /// If name lookup results in an ambiguity, this routine will complain
  118. /// and then return NULL.
  119. ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
  120. Scope *S, CXXScopeSpec *SS,
  121. bool isClassName, bool HasTrailingDot,
  122. ParsedType ObjectTypePtr,
  123. bool IsCtorOrDtorName,
  124. bool WantNontrivialTypeSourceInfo,
  125. IdentifierInfo **CorrectedII) {
  126. // Determine where we will perform name lookup.
  127. DeclContext *LookupCtx = 0;
  128. if (ObjectTypePtr) {
  129. QualType ObjectType = ObjectTypePtr.get();
  130. if (ObjectType->isRecordType())
  131. LookupCtx = computeDeclContext(ObjectType);
  132. } else if (SS && SS->isNotEmpty()) {
  133. LookupCtx = computeDeclContext(*SS, false);
  134. if (!LookupCtx) {
  135. if (isDependentScopeSpecifier(*SS)) {
  136. // C++ [temp.res]p3:
  137. // A qualified-id that refers to a type and in which the
  138. // nested-name-specifier depends on a template-parameter (14.6.2)
  139. // shall be prefixed by the keyword typename to indicate that the
  140. // qualified-id denotes a type, forming an
  141. // elaborated-type-specifier (7.1.5.3).
  142. //
  143. // We therefore do not perform any name lookup if the result would
  144. // refer to a member of an unknown specialization.
  145. if (!isClassName && !IsCtorOrDtorName)
  146. return ParsedType();
  147. // We know from the grammar that this name refers to a type,
  148. // so build a dependent node to describe the type.
  149. if (WantNontrivialTypeSourceInfo)
  150. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  151. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  152. QualType T =
  153. CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  154. II, NameLoc);
  155. return ParsedType::make(T);
  156. }
  157. return ParsedType();
  158. }
  159. if (!LookupCtx->isDependentContext() &&
  160. RequireCompleteDeclContext(*SS, LookupCtx))
  161. return ParsedType();
  162. }
  163. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  164. // lookup for class-names.
  165. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  166. LookupOrdinaryName;
  167. LookupResult Result(*this, &II, NameLoc, Kind);
  168. if (LookupCtx) {
  169. // Perform "qualified" name lookup into the declaration context we
  170. // computed, which is either the type of the base of a member access
  171. // expression or the declaration context associated with a prior
  172. // nested-name-specifier.
  173. LookupQualifiedName(Result, LookupCtx);
  174. if (ObjectTypePtr && Result.empty()) {
  175. // C++ [basic.lookup.classref]p3:
  176. // If the unqualified-id is ~type-name, the type-name is looked up
  177. // in the context of the entire postfix-expression. If the type T of
  178. // the object expression is of a class type C, the type-name is also
  179. // looked up in the scope of class C. At least one of the lookups shall
  180. // find a name that refers to (possibly cv-qualified) T.
  181. LookupName(Result, S);
  182. }
  183. } else {
  184. // Perform unqualified name lookup.
  185. LookupName(Result, S);
  186. }
  187. NamedDecl *IIDecl = 0;
  188. switch (Result.getResultKind()) {
  189. case LookupResult::NotFound:
  190. case LookupResult::NotFoundInCurrentInstantiation:
  191. if (CorrectedII) {
  192. TypeNameValidatorCCC Validator(true, isClassName);
  193. TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
  194. Kind, S, SS, Validator);
  195. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  196. TemplateTy Template;
  197. bool MemberOfUnknownSpecialization;
  198. UnqualifiedId TemplateName;
  199. TemplateName.setIdentifier(NewII, NameLoc);
  200. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  201. CXXScopeSpec NewSS, *NewSSPtr = SS;
  202. if (SS && NNS) {
  203. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  204. NewSSPtr = &NewSS;
  205. }
  206. if (Correction && (NNS || NewII != &II) &&
  207. // Ignore a correction to a template type as the to-be-corrected
  208. // identifier is not a template (typo correction for template names
  209. // is handled elsewhere).
  210. !(getLangOpts().CPlusPlus && NewSSPtr &&
  211. isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
  212. false, Template, MemberOfUnknownSpecialization))) {
  213. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  214. isClassName, HasTrailingDot, ObjectTypePtr,
  215. IsCtorOrDtorName,
  216. WantNontrivialTypeSourceInfo);
  217. if (Ty) {
  218. std::string CorrectedStr(Correction.getAsString(getLangOpts()));
  219. std::string CorrectedQuotedStr(
  220. Correction.getQuoted(getLangOpts()));
  221. Diag(NameLoc, diag::err_unknown_type_or_class_name_suggest)
  222. << Result.getLookupName() << CorrectedQuotedStr << isClassName
  223. << FixItHint::CreateReplacement(SourceRange(NameLoc),
  224. CorrectedStr);
  225. if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
  226. Diag(FirstDecl->getLocation(), diag::note_previous_decl)
  227. << CorrectedQuotedStr;
  228. if (SS && NNS)
  229. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  230. *CorrectedII = NewII;
  231. return Ty;
  232. }
  233. }
  234. }
  235. // If typo correction failed or was not performed, fall through
  236. case LookupResult::FoundOverloaded:
  237. case LookupResult::FoundUnresolvedValue:
  238. Result.suppressDiagnostics();
  239. return ParsedType();
  240. case LookupResult::Ambiguous:
  241. // Recover from type-hiding ambiguities by hiding the type. We'll
  242. // do the lookup again when looking for an object, and we can
  243. // diagnose the error then. If we don't do this, then the error
  244. // about hiding the type will be immediately followed by an error
  245. // that only makes sense if the identifier was treated like a type.
  246. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  247. Result.suppressDiagnostics();
  248. return ParsedType();
  249. }
  250. // Look to see if we have a type anywhere in the list of results.
  251. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  252. Res != ResEnd; ++Res) {
  253. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
  254. if (!IIDecl ||
  255. (*Res)->getLocation().getRawEncoding() <
  256. IIDecl->getLocation().getRawEncoding())
  257. IIDecl = *Res;
  258. }
  259. }
  260. if (!IIDecl) {
  261. // None of the entities we found is a type, so there is no way
  262. // to even assume that the result is a type. In this case, don't
  263. // complain about the ambiguity. The parser will either try to
  264. // perform this lookup again (e.g., as an object name), which
  265. // will produce the ambiguity, or will complain that it expected
  266. // a type name.
  267. Result.suppressDiagnostics();
  268. return ParsedType();
  269. }
  270. // We found a type within the ambiguous lookup; diagnose the
  271. // ambiguity and then return that type. This might be the right
  272. // answer, or it might not be, but it suppresses any attempt to
  273. // perform the name lookup again.
  274. break;
  275. case LookupResult::Found:
  276. IIDecl = Result.getFoundDecl();
  277. break;
  278. }
  279. assert(IIDecl && "Didn't find decl");
  280. QualType T;
  281. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  282. DiagnoseUseOfDecl(IIDecl, NameLoc);
  283. if (T.isNull())
  284. T = Context.getTypeDeclType(TD);
  285. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  286. // constructor or destructor name (in such a case, the scope specifier
  287. // will be attached to the enclosing Expr or Decl node).
  288. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
  289. if (WantNontrivialTypeSourceInfo) {
  290. // Construct a type with type-source information.
  291. TypeLocBuilder Builder;
  292. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  293. T = getElaboratedType(ETK_None, *SS, T);
  294. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  295. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  296. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  297. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  298. } else {
  299. T = getElaboratedType(ETK_None, *SS, T);
  300. }
  301. }
  302. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  303. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  304. if (!HasTrailingDot)
  305. T = Context.getObjCInterfaceType(IDecl);
  306. }
  307. if (T.isNull()) {
  308. // If it's not plausibly a type, suppress diagnostics.
  309. Result.suppressDiagnostics();
  310. return ParsedType();
  311. }
  312. return ParsedType::make(T);
  313. }
  314. /// isTagName() - This method is called *for error recovery purposes only*
  315. /// to determine if the specified name is a valid tag name ("struct foo"). If
  316. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  317. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  318. /// cases in C where the user forgot to specify the tag.
  319. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  320. // Do a tag name lookup in this scope.
  321. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  322. LookupName(R, S, false);
  323. R.suppressDiagnostics();
  324. if (R.getResultKind() == LookupResult::Found)
  325. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  326. switch (TD->getTagKind()) {
  327. case TTK_Struct: return DeclSpec::TST_struct;
  328. case TTK_Interface: return DeclSpec::TST_interface;
  329. case TTK_Union: return DeclSpec::TST_union;
  330. case TTK_Class: return DeclSpec::TST_class;
  331. case TTK_Enum: return DeclSpec::TST_enum;
  332. }
  333. }
  334. return DeclSpec::TST_unspecified;
  335. }
  336. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  337. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  338. /// then downgrade the missing typename error to a warning.
  339. /// This is needed for MSVC compatibility; Example:
  340. /// @code
  341. /// template<class T> class A {
  342. /// public:
  343. /// typedef int TYPE;
  344. /// };
  345. /// template<class T> class B : public A<T> {
  346. /// public:
  347. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  348. /// };
  349. /// @endcode
  350. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  351. if (CurContext->isRecord()) {
  352. const Type *Ty = SS->getScopeRep()->getAsType();
  353. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  354. for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
  355. BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
  356. if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
  357. return true;
  358. return S->isFunctionPrototypeScope();
  359. }
  360. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  361. }
  362. bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  363. SourceLocation IILoc,
  364. Scope *S,
  365. CXXScopeSpec *SS,
  366. ParsedType &SuggestedType) {
  367. // We don't have anything to suggest (yet).
  368. SuggestedType = ParsedType();
  369. // There may have been a typo in the name of the type. Look up typo
  370. // results, in case we have something that we can suggest.
  371. TypeNameValidatorCCC Validator(false);
  372. if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
  373. LookupOrdinaryName, S, SS,
  374. Validator)) {
  375. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  376. std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
  377. if (Corrected.isKeyword()) {
  378. // We corrected to a keyword.
  379. IdentifierInfo *NewII = Corrected.getCorrectionAsIdentifierInfo();
  380. if (!isSimpleTypeSpecifier(NewII->getTokenID()))
  381. CorrectedQuotedStr = "the keyword " + CorrectedQuotedStr;
  382. Diag(IILoc, diag::err_unknown_typename_suggest)
  383. << II << CorrectedQuotedStr
  384. << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
  385. II = NewII;
  386. } else {
  387. NamedDecl *Result = Corrected.getCorrectionDecl();
  388. // We found a similarly-named type or interface; suggest that.
  389. if (!SS || !SS->isSet())
  390. Diag(IILoc, diag::err_unknown_typename_suggest)
  391. << II << CorrectedQuotedStr
  392. << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
  393. else if (DeclContext *DC = computeDeclContext(*SS, false))
  394. Diag(IILoc, diag::err_unknown_nested_typename_suggest)
  395. << II << DC << CorrectedQuotedStr << SS->getRange()
  396. << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
  397. CorrectedStr);
  398. else
  399. llvm_unreachable("could not have corrected a typo here");
  400. Diag(Result->getLocation(), diag::note_previous_decl)
  401. << CorrectedQuotedStr;
  402. SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
  403. false, false, ParsedType(),
  404. /*IsCtorOrDtorName=*/false,
  405. /*NonTrivialTypeSourceInfo=*/true);
  406. }
  407. return true;
  408. }
  409. if (getLangOpts().CPlusPlus) {
  410. // See if II is a class template that the user forgot to pass arguments to.
  411. UnqualifiedId Name;
  412. Name.setIdentifier(II, IILoc);
  413. CXXScopeSpec EmptySS;
  414. TemplateTy TemplateResult;
  415. bool MemberOfUnknownSpecialization;
  416. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  417. Name, ParsedType(), true, TemplateResult,
  418. MemberOfUnknownSpecialization) == TNK_Type_template) {
  419. TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
  420. Diag(IILoc, diag::err_template_missing_args) << TplName;
  421. if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
  422. Diag(TplDecl->getLocation(), diag::note_template_decl_here)
  423. << TplDecl->getTemplateParameters()->getSourceRange();
  424. }
  425. return true;
  426. }
  427. }
  428. // FIXME: Should we move the logic that tries to recover from a missing tag
  429. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  430. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  431. Diag(IILoc, diag::err_unknown_typename) << II;
  432. else if (DeclContext *DC = computeDeclContext(*SS, false))
  433. Diag(IILoc, diag::err_typename_nested_not_found)
  434. << II << DC << SS->getRange();
  435. else if (isDependentScopeSpecifier(*SS)) {
  436. unsigned DiagID = diag::err_typename_missing;
  437. if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
  438. DiagID = diag::warn_typename_missing;
  439. Diag(SS->getRange().getBegin(), DiagID)
  440. << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
  441. << SourceRange(SS->getRange().getBegin(), IILoc)
  442. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  443. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  444. *SS, *II, IILoc).get();
  445. } else {
  446. assert(SS && SS->isInvalid() &&
  447. "Invalid scope specifier has already been diagnosed");
  448. }
  449. return true;
  450. }
  451. /// \brief Determine whether the given result set contains either a type name
  452. /// or
  453. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  454. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  455. NextToken.is(tok::less);
  456. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  457. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  458. return true;
  459. if (CheckTemplate && isa<TemplateDecl>(*I))
  460. return true;
  461. }
  462. return false;
  463. }
  464. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  465. Scope *S, CXXScopeSpec &SS,
  466. IdentifierInfo *&Name,
  467. SourceLocation NameLoc) {
  468. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  469. SemaRef.LookupParsedName(R, S, &SS);
  470. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  471. const char *TagName = 0;
  472. const char *FixItTagName = 0;
  473. switch (Tag->getTagKind()) {
  474. case TTK_Class:
  475. TagName = "class";
  476. FixItTagName = "class ";
  477. break;
  478. case TTK_Enum:
  479. TagName = "enum";
  480. FixItTagName = "enum ";
  481. break;
  482. case TTK_Struct:
  483. TagName = "struct";
  484. FixItTagName = "struct ";
  485. break;
  486. case TTK_Interface:
  487. TagName = "__interface";
  488. FixItTagName = "__interface ";
  489. break;
  490. case TTK_Union:
  491. TagName = "union";
  492. FixItTagName = "union ";
  493. break;
  494. }
  495. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  496. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  497. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  498. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  499. I != IEnd; ++I)
  500. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  501. << Name << TagName;
  502. // Replace lookup results with just the tag decl.
  503. Result.clear(Sema::LookupTagName);
  504. SemaRef.LookupParsedName(Result, S, &SS);
  505. return true;
  506. }
  507. return false;
  508. }
  509. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  510. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  511. QualType T, SourceLocation NameLoc) {
  512. ASTContext &Context = S.Context;
  513. TypeLocBuilder Builder;
  514. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  515. T = S.getElaboratedType(ETK_None, SS, T);
  516. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  517. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  518. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  519. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  520. }
  521. Sema::NameClassification Sema::ClassifyName(Scope *S,
  522. CXXScopeSpec &SS,
  523. IdentifierInfo *&Name,
  524. SourceLocation NameLoc,
  525. const Token &NextToken,
  526. bool IsAddressOfOperand,
  527. CorrectionCandidateCallback *CCC) {
  528. DeclarationNameInfo NameInfo(Name, NameLoc);
  529. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  530. if (NextToken.is(tok::coloncolon)) {
  531. BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
  532. QualType(), false, SS, 0, false);
  533. }
  534. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  535. LookupParsedName(Result, S, &SS, !CurMethod);
  536. // Perform lookup for Objective-C instance variables (including automatically
  537. // synthesized instance variables), if we're in an Objective-C method.
  538. // FIXME: This lookup really, really needs to be folded in to the normal
  539. // unqualified lookup mechanism.
  540. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  541. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  542. if (E.get() || E.isInvalid())
  543. return E;
  544. }
  545. bool SecondTry = false;
  546. bool IsFilteredTemplateName = false;
  547. Corrected:
  548. switch (Result.getResultKind()) {
  549. case LookupResult::NotFound:
  550. // If an unqualified-id is followed by a '(', then we have a function
  551. // call.
  552. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  553. // In C++, this is an ADL-only call.
  554. // FIXME: Reference?
  555. if (getLangOpts().CPlusPlus)
  556. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  557. // C90 6.3.2.2:
  558. // If the expression that precedes the parenthesized argument list in a
  559. // function call consists solely of an identifier, and if no
  560. // declaration is visible for this identifier, the identifier is
  561. // implicitly declared exactly as if, in the innermost block containing
  562. // the function call, the declaration
  563. //
  564. // extern int identifier ();
  565. //
  566. // appeared.
  567. //
  568. // We also allow this in C99 as an extension.
  569. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  570. Result.addDecl(D);
  571. Result.resolveKind();
  572. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  573. }
  574. }
  575. // In C, we first see whether there is a tag type by the same name, in
  576. // which case it's likely that the user just forget to write "enum",
  577. // "struct", or "union".
  578. if (!getLangOpts().CPlusPlus && !SecondTry &&
  579. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  580. break;
  581. }
  582. // Perform typo correction to determine if there is another name that is
  583. // close to this name.
  584. if (!SecondTry && CCC) {
  585. SecondTry = true;
  586. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  587. Result.getLookupKind(), S,
  588. &SS, *CCC)) {
  589. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  590. unsigned QualifiedDiag = diag::err_no_member_suggest;
  591. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  592. std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
  593. NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
  594. NamedDecl *UnderlyingFirstDecl
  595. = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
  596. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  597. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  598. UnqualifiedDiag = diag::err_no_template_suggest;
  599. QualifiedDiag = diag::err_no_member_template_suggest;
  600. } else if (UnderlyingFirstDecl &&
  601. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  602. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  603. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  604. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  605. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  606. }
  607. if (SS.isEmpty())
  608. Diag(NameLoc, UnqualifiedDiag)
  609. << Name << CorrectedQuotedStr
  610. << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
  611. else // FIXME: is this even reachable? Test it.
  612. Diag(NameLoc, QualifiedDiag)
  613. << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
  614. << SS.getRange()
  615. << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
  616. CorrectedStr);
  617. // Update the name, so that the caller has the new name.
  618. Name = Corrected.getCorrectionAsIdentifierInfo();
  619. // Typo correction corrected to a keyword.
  620. if (Corrected.isKeyword())
  621. return Corrected.getCorrectionAsIdentifierInfo();
  622. // Also update the LookupResult...
  623. // FIXME: This should probably go away at some point
  624. Result.clear();
  625. Result.setLookupName(Corrected.getCorrection());
  626. if (FirstDecl) {
  627. Result.addDecl(FirstDecl);
  628. Diag(FirstDecl->getLocation(), diag::note_previous_decl)
  629. << CorrectedQuotedStr;
  630. }
  631. // If we found an Objective-C instance variable, let
  632. // LookupInObjCMethod build the appropriate expression to
  633. // reference the ivar.
  634. // FIXME: This is a gross hack.
  635. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  636. Result.clear();
  637. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  638. return E;
  639. }
  640. goto Corrected;
  641. }
  642. }
  643. // We failed to correct; just fall through and let the parser deal with it.
  644. Result.suppressDiagnostics();
  645. return NameClassification::Unknown();
  646. case LookupResult::NotFoundInCurrentInstantiation: {
  647. // We performed name lookup into the current instantiation, and there were
  648. // dependent bases, so we treat this result the same way as any other
  649. // dependent nested-name-specifier.
  650. // C++ [temp.res]p2:
  651. // A name used in a template declaration or definition and that is
  652. // dependent on a template-parameter is assumed not to name a type
  653. // unless the applicable name lookup finds a type name or the name is
  654. // qualified by the keyword typename.
  655. //
  656. // FIXME: If the next token is '<', we might want to ask the parser to
  657. // perform some heroics to see if we actually have a
  658. // template-argument-list, which would indicate a missing 'template'
  659. // keyword here.
  660. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  661. NameInfo, IsAddressOfOperand,
  662. /*TemplateArgs=*/0);
  663. }
  664. case LookupResult::Found:
  665. case LookupResult::FoundOverloaded:
  666. case LookupResult::FoundUnresolvedValue:
  667. break;
  668. case LookupResult::Ambiguous:
  669. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  670. hasAnyAcceptableTemplateNames(Result)) {
  671. // C++ [temp.local]p3:
  672. // A lookup that finds an injected-class-name (10.2) can result in an
  673. // ambiguity in certain cases (for example, if it is found in more than
  674. // one base class). If all of the injected-class-names that are found
  675. // refer to specializations of the same class template, and if the name
  676. // is followed by a template-argument-list, the reference refers to the
  677. // class template itself and not a specialization thereof, and is not
  678. // ambiguous.
  679. //
  680. // This filtering can make an ambiguous result into an unambiguous one,
  681. // so try again after filtering out template names.
  682. FilterAcceptableTemplateNames(Result);
  683. if (!Result.isAmbiguous()) {
  684. IsFilteredTemplateName = true;
  685. break;
  686. }
  687. }
  688. // Diagnose the ambiguity and return an error.
  689. return NameClassification::Error();
  690. }
  691. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  692. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  693. // C++ [temp.names]p3:
  694. // After name lookup (3.4) finds that a name is a template-name or that
  695. // an operator-function-id or a literal- operator-id refers to a set of
  696. // overloaded functions any member of which is a function template if
  697. // this is followed by a <, the < is always taken as the delimiter of a
  698. // template-argument-list and never as the less-than operator.
  699. if (!IsFilteredTemplateName)
  700. FilterAcceptableTemplateNames(Result);
  701. if (!Result.empty()) {
  702. bool IsFunctionTemplate;
  703. TemplateName Template;
  704. if (Result.end() - Result.begin() > 1) {
  705. IsFunctionTemplate = true;
  706. Template = Context.getOverloadedTemplateName(Result.begin(),
  707. Result.end());
  708. } else {
  709. TemplateDecl *TD
  710. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  711. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  712. if (SS.isSet() && !SS.isInvalid())
  713. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  714. /*TemplateKeyword=*/false,
  715. TD);
  716. else
  717. Template = TemplateName(TD);
  718. }
  719. if (IsFunctionTemplate) {
  720. // Function templates always go through overload resolution, at which
  721. // point we'll perform the various checks (e.g., accessibility) we need
  722. // to based on which function we selected.
  723. Result.suppressDiagnostics();
  724. return NameClassification::FunctionTemplate(Template);
  725. }
  726. return NameClassification::TypeTemplate(Template);
  727. }
  728. }
  729. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  730. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  731. DiagnoseUseOfDecl(Type, NameLoc);
  732. QualType T = Context.getTypeDeclType(Type);
  733. if (SS.isNotEmpty())
  734. return buildNestedType(*this, SS, T, NameLoc);
  735. return ParsedType::make(T);
  736. }
  737. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  738. if (!Class) {
  739. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  740. if (ObjCCompatibleAliasDecl *Alias
  741. = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  742. Class = Alias->getClassInterface();
  743. }
  744. if (Class) {
  745. DiagnoseUseOfDecl(Class, NameLoc);
  746. if (NextToken.is(tok::period)) {
  747. // Interface. <something> is parsed as a property reference expression.
  748. // Just return "unknown" as a fall-through for now.
  749. Result.suppressDiagnostics();
  750. return NameClassification::Unknown();
  751. }
  752. QualType T = Context.getObjCInterfaceType(Class);
  753. return ParsedType::make(T);
  754. }
  755. // We can have a type template here if we're classifying a template argument.
  756. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
  757. return NameClassification::TypeTemplate(
  758. TemplateName(cast<TemplateDecl>(FirstDecl)));
  759. // Check for a tag type hidden by a non-type decl in a few cases where it
  760. // seems likely a type is wanted instead of the non-type that was found.
  761. if (!getLangOpts().ObjC1) {
  762. bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
  763. if ((NextToken.is(tok::identifier) ||
  764. (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
  765. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  766. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  767. DiagnoseUseOfDecl(Type, NameLoc);
  768. QualType T = Context.getTypeDeclType(Type);
  769. if (SS.isNotEmpty())
  770. return buildNestedType(*this, SS, T, NameLoc);
  771. return ParsedType::make(T);
  772. }
  773. }
  774. if (FirstDecl->isCXXClassMember())
  775. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
  776. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  777. return BuildDeclarationNameExpr(SS, Result, ADL);
  778. }
  779. // Determines the context to return to after temporarily entering a
  780. // context. This depends in an unnecessarily complicated way on the
  781. // exact ordering of callbacks from the parser.
  782. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  783. // Functions defined inline within classes aren't parsed until we've
  784. // finished parsing the top-level class, so the top-level class is
  785. // the context we'll need to return to.
  786. if (isa<FunctionDecl>(DC)) {
  787. DC = DC->getLexicalParent();
  788. // A function not defined within a class will always return to its
  789. // lexical context.
  790. if (!isa<CXXRecordDecl>(DC))
  791. return DC;
  792. // A C++ inline method/friend is parsed *after* the topmost class
  793. // it was declared in is fully parsed ("complete"); the topmost
  794. // class is the context we need to return to.
  795. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  796. DC = RD;
  797. // Return the declaration context of the topmost class the inline method is
  798. // declared in.
  799. return DC;
  800. }
  801. return DC->getLexicalParent();
  802. }
  803. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  804. assert(getContainingDC(DC) == CurContext &&
  805. "The next DeclContext should be lexically contained in the current one.");
  806. CurContext = DC;
  807. S->setEntity(DC);
  808. }
  809. void Sema::PopDeclContext() {
  810. assert(CurContext && "DeclContext imbalance!");
  811. CurContext = getContainingDC(CurContext);
  812. assert(CurContext && "Popped translation unit!");
  813. }
  814. /// EnterDeclaratorContext - Used when we must lookup names in the context
  815. /// of a declarator's nested name specifier.
  816. ///
  817. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  818. // C++0x [basic.lookup.unqual]p13:
  819. // A name used in the definition of a static data member of class
  820. // X (after the qualified-id of the static member) is looked up as
  821. // if the name was used in a member function of X.
  822. // C++0x [basic.lookup.unqual]p14:
  823. // If a variable member of a namespace is defined outside of the
  824. // scope of its namespace then any name used in the definition of
  825. // the variable member (after the declarator-id) is looked up as
  826. // if the definition of the variable member occurred in its
  827. // namespace.
  828. // Both of these imply that we should push a scope whose context
  829. // is the semantic context of the declaration. We can't use
  830. // PushDeclContext here because that context is not necessarily
  831. // lexically contained in the current context. Fortunately,
  832. // the containing scope should have the appropriate information.
  833. assert(!S->getEntity() && "scope already has entity");
  834. #ifndef NDEBUG
  835. Scope *Ancestor = S->getParent();
  836. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  837. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  838. #endif
  839. CurContext = DC;
  840. S->setEntity(DC);
  841. }
  842. void Sema::ExitDeclaratorContext(Scope *S) {
  843. assert(S->getEntity() == CurContext && "Context imbalance!");
  844. // Switch back to the lexical context. The safety of this is
  845. // enforced by an assert in EnterDeclaratorContext.
  846. Scope *Ancestor = S->getParent();
  847. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  848. CurContext = (DeclContext*) Ancestor->getEntity();
  849. // We don't need to do anything with the scope, which is going to
  850. // disappear.
  851. }
  852. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  853. FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  854. if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
  855. // We assume that the caller has already called
  856. // ActOnReenterTemplateScope
  857. FD = TFD->getTemplatedDecl();
  858. }
  859. if (!FD)
  860. return;
  861. // Same implementation as PushDeclContext, but enters the context
  862. // from the lexical parent, rather than the top-level class.
  863. assert(CurContext == FD->getLexicalParent() &&
  864. "The next DeclContext should be lexically contained in the current one.");
  865. CurContext = FD;
  866. S->setEntity(CurContext);
  867. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  868. ParmVarDecl *Param = FD->getParamDecl(P);
  869. // If the parameter has an identifier, then add it to the scope
  870. if (Param->getIdentifier()) {
  871. S->AddDecl(Param);
  872. IdResolver.AddDecl(Param);
  873. }
  874. }
  875. }
  876. void Sema::ActOnExitFunctionContext() {
  877. // Same implementation as PopDeclContext, but returns to the lexical parent,
  878. // rather than the top-level class.
  879. assert(CurContext && "DeclContext imbalance!");
  880. CurContext = CurContext->getLexicalParent();
  881. assert(CurContext && "Popped translation unit!");
  882. }
  883. /// \brief Determine whether we allow overloading of the function
  884. /// PrevDecl with another declaration.
  885. ///
  886. /// This routine determines whether overloading is possible, not
  887. /// whether some new function is actually an overload. It will return
  888. /// true in C++ (where we can always provide overloads) or, as an
  889. /// extension, in C when the previous function is already an
  890. /// overloaded function declaration or has the "overloadable"
  891. /// attribute.
  892. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  893. ASTContext &Context) {
  894. if (Context.getLangOpts().CPlusPlus)
  895. return true;
  896. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  897. return true;
  898. return (Previous.getResultKind() == LookupResult::Found
  899. && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
  900. }
  901. /// Add this decl to the scope shadowed decl chains.
  902. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  903. // Move up the scope chain until we find the nearest enclosing
  904. // non-transparent context. The declaration will be introduced into this
  905. // scope.
  906. while (S->getEntity() &&
  907. ((DeclContext *)S->getEntity())->isTransparentContext())
  908. S = S->getParent();
  909. // Add scoped declarations into their context, so that they can be
  910. // found later. Declarations without a context won't be inserted
  911. // into any context.
  912. if (AddToContext)
  913. CurContext->addDecl(D);
  914. // Out-of-line definitions shouldn't be pushed into scope in C++.
  915. // Out-of-line variable and function definitions shouldn't even in C.
  916. if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
  917. D->isOutOfLine() &&
  918. !D->getDeclContext()->getRedeclContext()->Equals(
  919. D->getLexicalDeclContext()->getRedeclContext()))
  920. return;
  921. // Template instantiations should also not be pushed into scope.
  922. if (isa<FunctionDecl>(D) &&
  923. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  924. return;
  925. // If this replaces anything in the current scope,
  926. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  927. IEnd = IdResolver.end();
  928. for (; I != IEnd; ++I) {
  929. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  930. S->RemoveDecl(*I);
  931. IdResolver.RemoveDecl(*I);
  932. // Should only need to replace one decl.
  933. break;
  934. }
  935. }
  936. S->AddDecl(D);
  937. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  938. // Implicitly-generated labels may end up getting generated in an order that
  939. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  940. // the label at the appropriate place in the identifier chain.
  941. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  942. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  943. if (IDC == CurContext) {
  944. if (!S->isDeclScope(*I))
  945. continue;
  946. } else if (IDC->Encloses(CurContext))
  947. break;
  948. }
  949. IdResolver.InsertDeclAfter(I, D);
  950. } else {
  951. IdResolver.AddDecl(D);
  952. }
  953. }
  954. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  955. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  956. TUScope->AddDecl(D);
  957. }
  958. bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
  959. bool ExplicitInstantiationOrSpecialization) {
  960. return IdResolver.isDeclInScope(D, Ctx, S,
  961. ExplicitInstantiationOrSpecialization);
  962. }
  963. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  964. DeclContext *TargetDC = DC->getPrimaryContext();
  965. do {
  966. if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
  967. if (ScopeDC->getPrimaryContext() == TargetDC)
  968. return S;
  969. } while ((S = S->getParent()));
  970. return 0;
  971. }
  972. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  973. DeclContext*,
  974. ASTContext&);
  975. /// Filters out lookup results that don't fall within the given scope
  976. /// as determined by isDeclInScope.
  977. void Sema::FilterLookupForScope(LookupResult &R,
  978. DeclContext *Ctx, Scope *S,
  979. bool ConsiderLinkage,
  980. bool ExplicitInstantiationOrSpecialization) {
  981. LookupResult::Filter F = R.makeFilter();
  982. while (F.hasNext()) {
  983. NamedDecl *D = F.next();
  984. if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
  985. continue;
  986. if (ConsiderLinkage &&
  987. isOutOfScopePreviousDeclaration(D, Ctx, Context))
  988. continue;
  989. F.erase();
  990. }
  991. F.done();
  992. }
  993. static bool isUsingDecl(NamedDecl *D) {
  994. return isa<UsingShadowDecl>(D) ||
  995. isa<UnresolvedUsingTypenameDecl>(D) ||
  996. isa<UnresolvedUsingValueDecl>(D);
  997. }
  998. /// Removes using shadow declarations from the lookup results.
  999. static void RemoveUsingDecls(LookupResult &R) {
  1000. LookupResult::Filter F = R.makeFilter();
  1001. while (F.hasNext())
  1002. if (isUsingDecl(F.next()))
  1003. F.erase();
  1004. F.done();
  1005. }
  1006. /// \brief Check for this common pattern:
  1007. /// @code
  1008. /// class S {
  1009. /// S(const S&); // DO NOT IMPLEMENT
  1010. /// void operator=(const S&); // DO NOT IMPLEMENT
  1011. /// };
  1012. /// @endcode
  1013. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1014. // FIXME: Should check for private access too but access is set after we get
  1015. // the decl here.
  1016. if (D->doesThisDeclarationHaveABody())
  1017. return false;
  1018. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1019. return CD->isCopyConstructor();
  1020. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  1021. return Method->isCopyAssignmentOperator();
  1022. return false;
  1023. }
  1024. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1025. assert(D);
  1026. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1027. return false;
  1028. // Ignore class templates.
  1029. if (D->getDeclContext()->isDependentContext() ||
  1030. D->getLexicalDeclContext()->isDependentContext())
  1031. return false;
  1032. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1033. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1034. return false;
  1035. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1036. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1037. return false;
  1038. } else {
  1039. // 'static inline' functions are used in headers; don't warn.
  1040. if (FD->getStorageClass() == SC_Static &&
  1041. FD->isInlineSpecified())
  1042. return false;
  1043. }
  1044. if (FD->doesThisDeclarationHaveABody() &&
  1045. Context.DeclMustBeEmitted(FD))
  1046. return false;
  1047. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1048. // Don't warn on variables of const-qualified or reference type, since their
  1049. // values can be used even if though they're not odr-used, and because const
  1050. // qualified variables can appear in headers in contexts where they're not
  1051. // intended to be used.
  1052. // FIXME: Use more principled rules for these exemptions.
  1053. if (!VD->isFileVarDecl() ||
  1054. VD->getType().isConstQualified() ||
  1055. VD->getType()->isReferenceType() ||
  1056. Context.DeclMustBeEmitted(VD))
  1057. return false;
  1058. if (VD->isStaticDataMember() &&
  1059. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1060. return false;
  1061. } else {
  1062. return false;
  1063. }
  1064. // Only warn for unused decls internal to the translation unit.
  1065. if (D->getLinkage() == ExternalLinkage)
  1066. return false;
  1067. return true;
  1068. }
  1069. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1070. if (!D)
  1071. return;
  1072. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1073. const FunctionDecl *First = FD->getFirstDeclaration();
  1074. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1075. return; // First should already be in the vector.
  1076. }
  1077. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1078. const VarDecl *First = VD->getFirstDeclaration();
  1079. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1080. return; // First should already be in the vector.
  1081. }
  1082. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1083. UnusedFileScopedDecls.push_back(D);
  1084. }
  1085. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1086. if (D->isInvalidDecl())
  1087. return false;
  1088. if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1089. return false;
  1090. if (isa<LabelDecl>(D))
  1091. return true;
  1092. // White-list anything that isn't a local variable.
  1093. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
  1094. !D->getDeclContext()->isFunctionOrMethod())
  1095. return false;
  1096. // Types of valid local variables should be complete, so this should succeed.
  1097. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1098. // White-list anything with an __attribute__((unused)) type.
  1099. QualType Ty = VD->getType();
  1100. // Only look at the outermost level of typedef.
  1101. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1102. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1103. return false;
  1104. }
  1105. // If we failed to complete the type for some reason, or if the type is
  1106. // dependent, don't diagnose the variable.
  1107. if (Ty->isIncompleteType() || Ty->isDependentType())
  1108. return false;
  1109. if (const TagType *TT = Ty->getAs<TagType>()) {
  1110. const TagDecl *Tag = TT->getDecl();
  1111. if (Tag->hasAttr<UnusedAttr>())
  1112. return false;
  1113. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1114. if (!RD->hasTrivialDestructor())
  1115. return false;
  1116. if (const Expr *Init = VD->getInit()) {
  1117. if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
  1118. Init = Cleanups->getSubExpr();
  1119. const CXXConstructExpr *Construct =
  1120. dyn_cast<CXXConstructExpr>(Init);
  1121. if (Construct && !Construct->isElidable()) {
  1122. CXXConstructorDecl *CD = Construct->getConstructor();
  1123. if (!CD->isTrivial())
  1124. return false;
  1125. }
  1126. }
  1127. }
  1128. }
  1129. // TODO: __attribute__((unused)) templates?
  1130. }
  1131. return true;
  1132. }
  1133. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1134. FixItHint &Hint) {
  1135. if (isa<LabelDecl>(D)) {
  1136. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1137. tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
  1138. if (AfterColon.isInvalid())
  1139. return;
  1140. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1141. getCharRange(D->getLocStart(), AfterColon));
  1142. }
  1143. return;
  1144. }
  1145. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1146. /// unless they are marked attr(unused).
  1147. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1148. FixItHint Hint;
  1149. if (!ShouldDiagnoseUnusedDecl(D))
  1150. return;
  1151. GenerateFixForUnusedDecl(D, Context, Hint);
  1152. unsigned DiagID;
  1153. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1154. DiagID = diag::warn_unused_exception_param;
  1155. else if (isa<LabelDecl>(D))
  1156. DiagID = diag::warn_unused_label;
  1157. else
  1158. DiagID = diag::warn_unused_variable;
  1159. Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
  1160. }
  1161. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1162. // Verify that we have no forward references left. If so, there was a goto
  1163. // or address of a label taken, but no definition of it. Label fwd
  1164. // definitions are indicated with a null substmt.
  1165. if (L->getStmt() == 0)
  1166. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1167. }
  1168. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1169. if (S->decl_empty()) return;
  1170. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1171. "Scope shouldn't contain decls!");
  1172. for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
  1173. I != E; ++I) {
  1174. Decl *TmpD = (*I);
  1175. assert(TmpD && "This decl didn't get pushed??");
  1176. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1177. NamedDecl *D = cast<NamedDecl>(TmpD);
  1178. if (!D->getDeclName()) continue;
  1179. // Diagnose unused variables in this scope.
  1180. if (!S->hasErrorOccurred())
  1181. DiagnoseUnusedDecl(D);
  1182. // If this was a forward reference to a label, verify it was defined.
  1183. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1184. CheckPoppedLabel(LD, *this);
  1185. // Remove this name from our lexical scope.
  1186. IdResolver.RemoveDecl(D);
  1187. }
  1188. }
  1189. void Sema::ActOnStartFunctionDeclarator() {
  1190. ++InFunctionDeclarator;
  1191. }
  1192. void Sema::ActOnEndFunctionDeclarator() {
  1193. assert(InFunctionDeclarator);
  1194. --InFunctionDeclarator;
  1195. }
  1196. /// \brief Look for an Objective-C class in the translation unit.
  1197. ///
  1198. /// \param Id The name of the Objective-C class we're looking for. If
  1199. /// typo-correction fixes this name, the Id will be updated
  1200. /// to the fixed name.
  1201. ///
  1202. /// \param IdLoc The location of the name in the translation unit.
  1203. ///
  1204. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1205. /// if there is no class with the given name.
  1206. ///
  1207. /// \returns The declaration of the named Objective-C class, or NULL if the
  1208. /// class could not be found.
  1209. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1210. SourceLocation IdLoc,
  1211. bool DoTypoCorrection) {
  1212. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1213. // creation from this context.
  1214. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1215. if (!IDecl && DoTypoCorrection) {
  1216. // Perform typo correction at the given location, but only if we
  1217. // find an Objective-C class name.
  1218. DeclFilterCCC<ObjCInterfaceDecl> Validator;
  1219. if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
  1220. LookupOrdinaryName, TUScope, NULL,
  1221. Validator)) {
  1222. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1223. Diag(IdLoc, diag::err_undef_interface_suggest)
  1224. << Id << IDecl->getDeclName()
  1225. << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
  1226. Diag(IDecl->getLocation(), diag::note_previous_decl)
  1227. << IDecl->getDeclName();
  1228. Id = IDecl->getIdentifier();
  1229. }
  1230. }
  1231. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1232. // This routine must always return a class definition, if any.
  1233. if (Def && Def->getDefinition())
  1234. Def = Def->getDefinition();
  1235. return Def;
  1236. }
  1237. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1238. /// from S, where a non-field would be declared. This routine copes
  1239. /// with the difference between C and C++ scoping rules in structs and
  1240. /// unions. For example, the following code is well-formed in C but
  1241. /// ill-formed in C++:
  1242. /// @code
  1243. /// struct S6 {
  1244. /// enum { BAR } e;
  1245. /// };
  1246. ///
  1247. /// void test_S6() {
  1248. /// struct S6 a;
  1249. /// a.e = BAR;
  1250. /// }
  1251. /// @endcode
  1252. /// For the declaration of BAR, this routine will return a different
  1253. /// scope. The scope S will be the scope of the unnamed enumeration
  1254. /// within S6. In C++, this routine will return the scope associated
  1255. /// with S6, because the enumeration's scope is a transparent
  1256. /// context but structures can contain non-field names. In C, this
  1257. /// routine will return the translation unit scope, since the
  1258. /// enumeration's scope is a transparent context and structures cannot
  1259. /// contain non-field names.
  1260. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1261. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1262. (S->getEntity() &&
  1263. ((DeclContext *)S->getEntity())->isTransparentContext()) ||
  1264. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1265. S = S->getParent();
  1266. return S;
  1267. }
  1268. /// \brief Looks up the declaration of "struct objc_super" and
  1269. /// saves it for later use in building builtin declaration of
  1270. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1271. /// pre-existing declaration exists no action takes place.
  1272. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1273. IdentifierInfo *II) {
  1274. if (!II->isStr("objc_msgSendSuper"))
  1275. return;
  1276. ASTContext &Context = ThisSema.Context;
  1277. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1278. SourceLocation(), Sema::LookupTagName);
  1279. ThisSema.LookupName(Result, S);
  1280. if (Result.getResultKind() == LookupResult::Found)
  1281. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1282. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1283. }
  1284. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1285. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1286. /// if we're creating this built-in in anticipation of redeclaring the
  1287. /// built-in.
  1288. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
  1289. Scope *S, bool ForRedeclaration,
  1290. SourceLocation Loc) {
  1291. LookupPredefedObjCSuperType(*this, S, II);
  1292. Builtin::ID BID = (Builtin::ID)bid;
  1293. ASTContext::GetBuiltinTypeError Error;
  1294. QualType R = Context.GetBuiltinType(BID, Error);
  1295. switch (Error) {
  1296. case ASTContext::GE_None:
  1297. // Okay
  1298. break;
  1299. case ASTContext::GE_Missing_stdio:
  1300. if (ForRedeclaration)
  1301. Diag(Loc, diag::warn_implicit_decl_requires_stdio)
  1302. << Context.BuiltinInfo.GetName(BID);
  1303. return 0;
  1304. case ASTContext::GE_Missing_setjmp:
  1305. if (ForRedeclaration)
  1306. Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
  1307. << Context.BuiltinInfo.GetName(BID);
  1308. return 0;
  1309. case ASTContext::GE_Missing_ucontext:
  1310. if (ForRedeclaration)
  1311. Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
  1312. << Context.BuiltinInfo.GetName(BID);
  1313. return 0;
  1314. }
  1315. if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  1316. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1317. << Context.BuiltinInfo.GetName(BID)
  1318. << R;
  1319. if (Context.BuiltinInfo.getHeaderName(BID) &&
  1320. Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
  1321. != DiagnosticsEngine::Ignored)
  1322. Diag(Loc, diag::note_please_include_header)
  1323. << Context.BuiltinInfo.getHeaderName(BID)
  1324. << Context.BuiltinInfo.GetName(BID);
  1325. }
  1326. FunctionDecl *New = FunctionDecl::Create(Context,
  1327. Context.getTranslationUnitDecl(),
  1328. Loc, Loc, II, R, /*TInfo=*/0,
  1329. SC_Extern,
  1330. SC_None, false,
  1331. /*hasPrototype=*/true);
  1332. New->setImplicit();
  1333. // Create Decl objects for each parameter, adding them to the
  1334. // FunctionDecl.
  1335. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1336. SmallVector<ParmVarDecl*, 16> Params;
  1337. for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
  1338. ParmVarDecl *parm =
  1339. ParmVarDecl::Create(Context, New, SourceLocation(),
  1340. SourceLocation(), 0,
  1341. FT->getArgType(i), /*TInfo=*/0,
  1342. SC_None, SC_None, 0);
  1343. parm->setScopeInfo(0, i);
  1344. Params.push_back(parm);
  1345. }
  1346. New->setParams(Params);
  1347. }
  1348. AddKnownFunctionAttributes(New);
  1349. // TUScope is the translation-unit scope to insert this function into.
  1350. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1351. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1352. // entirely, but we're not there yet.
  1353. DeclContext *SavedContext = CurContext;
  1354. CurContext = Context.getTranslationUnitDecl();
  1355. PushOnScopeChains(New, TUScope);
  1356. CurContext = SavedContext;
  1357. return New;
  1358. }
  1359. /// \brief Filter out any previous declarations that the given declaration
  1360. /// should not consider because they are not permitted to conflict, e.g.,
  1361. /// because they come from hidden sub-modules and do not refer to the same
  1362. /// entity.
  1363. static void filterNonConflictingPreviousDecls(ASTContext &context,
  1364. NamedDecl *decl,
  1365. LookupResult &previous){
  1366. // This is only interesting when modules are enabled.
  1367. if (!context.getLangOpts().Modules)
  1368. return;
  1369. // Empty sets are uninteresting.
  1370. if (previous.empty())
  1371. return;
  1372. // If this declaration has external
  1373. bool hasExternalLinkage = (decl->getLinkage() == ExternalLinkage);
  1374. LookupResult::Filter filter = previous.makeFilter();
  1375. while (filter.hasNext()) {
  1376. NamedDecl *old = filter.next();
  1377. // Non-hidden declarations are never ignored.
  1378. if (!old->isHidden())
  1379. continue;
  1380. // If either has no-external linkage, ignore the old declaration.
  1381. if (!hasExternalLinkage || old->getLinkage() != ExternalLinkage)
  1382. filter.erase();
  1383. }
  1384. filter.done();
  1385. }
  1386. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1387. QualType OldType;
  1388. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1389. OldType = OldTypedef->getUnderlyingType();
  1390. else
  1391. OldType = Context.getTypeDeclType(Old);
  1392. QualType NewType = New->getUnderlyingType();
  1393. if (NewType->isVariablyModifiedType()) {
  1394. // Must not redefine a typedef with a variably-modified type.
  1395. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1396. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1397. << Kind << NewType;
  1398. if (Old->getLocation().isValid())
  1399. Diag(Old->getLocation(), diag::note_previous_definition);
  1400. New->setInvalidDecl();
  1401. return true;
  1402. }
  1403. if (OldType != NewType &&
  1404. !OldType->isDependentType() &&
  1405. !NewType->isDependentType() &&
  1406. !Context.hasSameType(OldType, NewType)) {
  1407. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1408. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1409. << Kind << NewType << OldType;
  1410. if (Old->getLocation().isValid())
  1411. Diag(Old->getLocation(), diag::note_previous_definition);
  1412. New->setInvalidDecl();
  1413. return true;
  1414. }
  1415. return false;
  1416. }
  1417. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1418. /// same name and scope as a previous declaration 'Old'. Figure out
  1419. /// how to resolve this situation, merging decls or emitting
  1420. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1421. ///
  1422. void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
  1423. // If the new decl is known invalid already, don't bother doing any
  1424. // merging checks.
  1425. if (New->isInvalidDecl()) return;
  1426. // Allow multiple definitions for ObjC built-in typedefs.
  1427. // FIXME: Verify the underlying types are equivalent!
  1428. if (getLangOpts().ObjC1) {
  1429. const IdentifierInfo *TypeID = New->getIdentifier();
  1430. switch (TypeID->getLength()) {
  1431. default: break;
  1432. case 2:
  1433. {
  1434. if (!TypeID->isStr("id"))
  1435. break;
  1436. QualType T = New->getUnderlyingType();
  1437. if (!T->isPointerType())
  1438. break;
  1439. if (!T->isVoidPointerType()) {
  1440. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1441. if (!PT->isStructureType())
  1442. break;
  1443. }
  1444. Context.setObjCIdRedefinitionType(T);
  1445. // Install the built-in type for 'id', ignoring the current definition.
  1446. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1447. return;
  1448. }
  1449. case 5:
  1450. if (!TypeID->isStr("Class"))
  1451. break;
  1452. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1453. // Install the built-in type for 'Class', ignoring the current definition.
  1454. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1455. return;
  1456. case 3:
  1457. if (!TypeID->isStr("SEL"))
  1458. break;
  1459. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1460. // Install the built-in type for 'SEL', ignoring the current definition.
  1461. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1462. return;
  1463. }
  1464. // Fall through - the typedef name was not a builtin type.
  1465. }
  1466. // Verify the old decl was also a type.
  1467. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1468. if (!Old) {
  1469. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1470. << New->getDeclName();
  1471. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1472. if (OldD->getLocation().isValid())
  1473. Diag(OldD->getLocation(), diag::note_previous_definition);
  1474. return New->setInvalidDecl();
  1475. }
  1476. // If the old declaration is invalid, just give up here.
  1477. if (Old->isInvalidDecl())
  1478. return New->setInvalidDecl();
  1479. // If the typedef types are not identical, reject them in all languages and
  1480. // with any extensions enabled.
  1481. if (isIncompatibleTypedef(Old, New))
  1482. return;
  1483. // The types match. Link up the redeclaration chain if the old
  1484. // declaration was a typedef.
  1485. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
  1486. New->setPreviousDeclaration(Typedef);
  1487. if (getLangOpts().MicrosoftExt)
  1488. return;
  1489. if (getLangOpts().CPlusPlus) {
  1490. // C++ [dcl.typedef]p2:
  1491. // In a given non-class scope, a typedef specifier can be used to
  1492. // redefine the name of any type declared in that scope to refer
  1493. // to the type to which it already refers.
  1494. if (!isa<CXXRecordDecl>(CurContext))
  1495. return;
  1496. // C++0x [dcl.typedef]p4:
  1497. // In a given class scope, a typedef specifier can be used to redefine
  1498. // any class-name declared in that scope that is not also a typedef-name
  1499. // to refer to the type to which it already refers.
  1500. //
  1501. // This wording came in via DR424, which was a correction to the
  1502. // wording in DR56, which accidentally banned code like:
  1503. //
  1504. // struct S {
  1505. // typedef struct A { } A;
  1506. // };
  1507. //
  1508. // in the C++03 standard. We implement the C++0x semantics, which
  1509. // allow the above but disallow
  1510. //
  1511. // struct S {
  1512. // typedef int I;
  1513. // typedef int I;
  1514. // };
  1515. //
  1516. // since that was the intent of DR56.
  1517. if (!isa<TypedefNameDecl>(Old))
  1518. return;
  1519. Diag(New->getLocation(), diag::err_redefinition)
  1520. << New->getDeclName();
  1521. Diag(Old->getLocation(), diag::note_previous_definition);
  1522. return New->setInvalidDecl();
  1523. }
  1524. // Modules always permit redefinition of typedefs, as does C11.
  1525. if (getLangOpts().Modules || getLangOpts().C11)
  1526. return;
  1527. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1528. // is normally mapped to an error, but can be controlled with
  1529. // -Wtypedef-redefinition. If either the original or the redefinition is
  1530. // in a system header, don't emit this for compatibility with GCC.
  1531. if (getDiagnostics().getSuppressSystemWarnings() &&
  1532. (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1533. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1534. return;
  1535. Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
  1536. << New->getDeclName();
  1537. Diag(Old->getLocation(), diag::note_previous_definition);
  1538. return;
  1539. }
  1540. /// DeclhasAttr - returns true if decl Declaration already has the target
  1541. /// attribute.
  1542. static bool
  1543. DeclHasAttr(const Decl *D, const Attr *A) {
  1544. // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
  1545. // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
  1546. // responsible for making sure they are consistent.
  1547. const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
  1548. if (AA)
  1549. return false;
  1550. // The following thread safety attributes can also be duplicated.
  1551. switch (A->getKind()) {
  1552. case attr::ExclusiveLocksRequired:
  1553. case attr::SharedLocksRequired:
  1554. case attr::LocksExcluded:
  1555. case attr::ExclusiveLockFunction:
  1556. case attr::SharedLockFunction:
  1557. case attr::UnlockFunction:
  1558. case attr::ExclusiveTrylockFunction:
  1559. case attr::SharedTrylockFunction:
  1560. case attr::GuardedBy:
  1561. case attr::PtGuardedBy:
  1562. case attr::AcquiredBefore:
  1563. case attr::AcquiredAfter:
  1564. return false;
  1565. default:
  1566. ;
  1567. }
  1568. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  1569. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  1570. for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
  1571. if ((*i)->getKind() == A->getKind()) {
  1572. if (Ann) {
  1573. if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
  1574. return true;
  1575. continue;
  1576. }
  1577. // FIXME: Don't hardcode this check
  1578. if (OA && isa<OwnershipAttr>(*i))
  1579. return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
  1580. return true;
  1581. }
  1582. return false;
  1583. }
  1584. bool Sema::mergeDeclAttribute(NamedDecl *D, InheritableAttr *Attr,
  1585. bool Override) {
  1586. InheritableAttr *NewAttr = NULL;
  1587. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  1588. if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
  1589. NewAttr = mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
  1590. AA->getIntroduced(), AA->getDeprecated(),
  1591. AA->getObsoleted(), AA->getUnavailable(),
  1592. AA->getMessage(), Override,
  1593. AttrSpellingListIndex);
  1594. else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
  1595. NewAttr = mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  1596. AttrSpellingListIndex);
  1597. else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
  1598. NewAttr = mergeDLLImportAttr(D, ImportA->getRange(),
  1599. AttrSpellingListIndex);
  1600. else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
  1601. NewAttr = mergeDLLExportAttr(D, ExportA->getRange(),
  1602. AttrSpellingListIndex);
  1603. else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
  1604. NewAttr = mergeFormatAttr(D, FA->getRange(), FA->getType(),
  1605. FA->getFormatIdx(), FA->getFirstArg(),
  1606. AttrSpellingListIndex);
  1607. else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
  1608. NewAttr = mergeSectionAttr(D, SA->getRange(), SA->getName(),
  1609. AttrSpellingListIndex);
  1610. else if (!DeclHasAttr(D, Attr))
  1611. NewAttr = cast<InheritableAttr>(Attr->clone(Context));
  1612. if (NewAttr) {
  1613. NewAttr->setInherited(true);
  1614. D->addAttr(NewAttr);
  1615. return true;
  1616. }
  1617. return false;
  1618. }
  1619. static const Decl *getDefinition(const Decl *D) {
  1620. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  1621. return TD->getDefinition();
  1622. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1623. return VD->getDefinition();
  1624. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1625. const FunctionDecl* Def;
  1626. if (FD->hasBody(Def))
  1627. return Def;
  1628. }
  1629. return NULL;
  1630. }
  1631. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  1632. for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
  1633. I != E; ++I) {
  1634. Attr *Attribute = *I;
  1635. if (Attribute->getKind() == Kind)
  1636. return true;
  1637. }
  1638. return false;
  1639. }
  1640. /// checkNewAttributesAfterDef - If we already have a definition, check that
  1641. /// there are no new attributes in this declaration.
  1642. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  1643. if (!New->hasAttrs())
  1644. return;
  1645. const Decl *Def = getDefinition(Old);
  1646. if (!Def || Def == New)
  1647. return;
  1648. AttrVec &NewAttributes = New->getAttrs();
  1649. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  1650. const Attr *NewAttribute = NewAttributes[I];
  1651. if (hasAttribute(Def, NewAttribute->getKind())) {
  1652. ++I;
  1653. continue; // regular attr merging will take care of validating this.
  1654. }
  1655. // C's _Noreturn is allowed to be added to a function after it is defined.
  1656. if (isa<C11NoReturnAttr>(NewAttribute)) {
  1657. ++I;
  1658. continue;
  1659. }
  1660. S.Diag(NewAttribute->getLocation(),
  1661. diag::warn_attribute_precede_definition);
  1662. S.Diag(Def->getLocation(), diag::note_previous_definition);
  1663. NewAttributes.erase(NewAttributes.begin() + I);
  1664. --E;
  1665. }
  1666. }
  1667. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  1668. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  1669. AvailabilityMergeKind AMK) {
  1670. if (!Old->hasAttrs() && !New->hasAttrs())
  1671. return;
  1672. // attributes declared post-definition are currently ignored
  1673. checkNewAttributesAfterDef(*this, New, Old);
  1674. if (!Old->hasAttrs())
  1675. return;
  1676. bool foundAny = New->hasAttrs();
  1677. // Ensure that any moving of objects within the allocated map is done before
  1678. // we process them.
  1679. if (!foundAny) New->setAttrs(AttrVec());
  1680. for (specific_attr_iterator<InheritableAttr>
  1681. i = Old->specific_attr_begin<InheritableAttr>(),
  1682. e = Old->specific_attr_end<InheritableAttr>();
  1683. i != e; ++i) {
  1684. bool Override = false;
  1685. // Ignore deprecated/unavailable/availability attributes if requested.
  1686. if (isa<DeprecatedAttr>(*i) ||
  1687. isa<UnavailableAttr>(*i) ||
  1688. isa<AvailabilityAttr>(*i)) {
  1689. switch (AMK) {
  1690. case AMK_None:
  1691. continue;
  1692. case AMK_Redeclaration:
  1693. break;
  1694. case AMK_Override:
  1695. Override = true;
  1696. break;
  1697. }
  1698. }
  1699. if (mergeDeclAttribute(New, *i, Override))
  1700. foundAny = true;
  1701. }
  1702. if (!foundAny) New->dropAttrs();
  1703. }
  1704. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  1705. /// to the new one.
  1706. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  1707. const ParmVarDecl *oldDecl,
  1708. Sema &S) {
  1709. // C++11 [dcl.attr.depend]p2:
  1710. // The first declaration of a function shall specify the
  1711. // carries_dependency attribute for its declarator-id if any declaration
  1712. // of the function specifies the carries_dependency attribute.
  1713. if (newDecl->hasAttr<CarriesDependencyAttr>() &&
  1714. !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  1715. S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
  1716. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  1717. // Find the first declaration of the parameter.
  1718. // FIXME: Should we build redeclaration chains for function parameters?
  1719. const FunctionDecl *FirstFD =
  1720. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDeclaration();
  1721. const ParmVarDecl *FirstVD =
  1722. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  1723. S.Diag(FirstVD->getLocation(),
  1724. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  1725. }
  1726. if (!oldDecl->hasAttrs())
  1727. return;
  1728. bool foundAny = newDecl->hasAttrs();
  1729. // Ensure that any moving of objects within the allocated map is
  1730. // done before we process them.
  1731. if (!foundAny) newDecl->setAttrs(AttrVec());
  1732. for (specific_attr_iterator<InheritableParamAttr>
  1733. i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
  1734. e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
  1735. if (!DeclHasAttr(newDecl, *i)) {
  1736. InheritableAttr *newAttr =
  1737. cast<InheritableParamAttr>((*i)->clone(S.Context));
  1738. newAttr->setInherited(true);
  1739. newDecl->addAttr(newAttr);
  1740. foundAny = true;
  1741. }
  1742. }
  1743. if (!foundAny) newDecl->dropAttrs();
  1744. }
  1745. namespace {
  1746. /// Used in MergeFunctionDecl to keep track of function parameters in
  1747. /// C.
  1748. struct GNUCompatibleParamWarning {
  1749. ParmVarDecl *OldParm;
  1750. ParmVarDecl *NewParm;
  1751. QualType PromotedType;
  1752. };
  1753. }
  1754. /// getSpecialMember - get the special member enum for a method.
  1755. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  1756. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  1757. if (Ctor->isDefaultConstructor())
  1758. return Sema::CXXDefaultConstructor;
  1759. if (Ctor->isCopyConstructor())
  1760. return Sema::CXXCopyConstructor;
  1761. if (Ctor->isMoveConstructor())
  1762. return Sema::CXXMoveConstructor;
  1763. } else if (isa<CXXDestructorDecl>(MD)) {
  1764. return Sema::CXXDestructor;
  1765. } else if (MD->isCopyAssignmentOperator()) {
  1766. return Sema::CXXCopyAssignment;
  1767. } else if (MD->isMoveAssignmentOperator()) {
  1768. return Sema::CXXMoveAssignment;
  1769. }
  1770. return Sema::CXXInvalid;
  1771. }
  1772. /// canRedefineFunction - checks if a function can be redefined. Currently,
  1773. /// only extern inline functions can be redefined, and even then only in
  1774. /// GNU89 mode.
  1775. static bool canRedefineFunction(const FunctionDecl *FD,
  1776. const LangOptions& LangOpts) {
  1777. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  1778. !LangOpts.CPlusPlus &&
  1779. FD->isInlineSpecified() &&
  1780. FD->getStorageClass() == SC_Extern);
  1781. }
  1782. /// Is the given calling convention the ABI default for the given
  1783. /// declaration?
  1784. static bool isABIDefaultCC(Sema &S, CallingConv CC, FunctionDecl *D) {
  1785. CallingConv ABIDefaultCC;
  1786. if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  1787. ABIDefaultCC = S.Context.getDefaultCXXMethodCallConv(D->isVariadic());
  1788. } else {
  1789. // Free C function or a static method.
  1790. ABIDefaultCC = (S.Context.getLangOpts().MRTD ? CC_X86StdCall : CC_C);
  1791. }
  1792. return ABIDefaultCC == CC;
  1793. }
  1794. /// MergeFunctionDecl - We just parsed a function 'New' from
  1795. /// declarator D which has the same name and scope as a previous
  1796. /// declaration 'Old'. Figure out how to resolve this situation,
  1797. /// merging decls or emitting diagnostics as appropriate.
  1798. ///
  1799. /// In C++, New and Old must be declarations that are not
  1800. /// overloaded. Use IsOverload to determine whether New and Old are
  1801. /// overloaded, and to select the Old declaration that New should be
  1802. /// merged with.
  1803. ///
  1804. /// Returns true if there was an error, false otherwise.
  1805. bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
  1806. // Verify the old decl was also a function.
  1807. FunctionDecl *Old = 0;
  1808. if (FunctionTemplateDecl *OldFunctionTemplate
  1809. = dyn_cast<FunctionTemplateDecl>(OldD))
  1810. Old = OldFunctionTemplate->getTemplatedDecl();
  1811. else
  1812. Old = dyn_cast<FunctionDecl>(OldD);
  1813. if (!Old) {
  1814. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  1815. Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  1816. Diag(Shadow->getTargetDecl()->getLocation(),
  1817. diag::note_using_decl_target);
  1818. Diag(Shadow->getUsingDecl()->getLocation(),
  1819. diag::note_using_decl) << 0;
  1820. return true;
  1821. }
  1822. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1823. << New->getDeclName();
  1824. Diag(OldD->getLocation(), diag::note_previous_definition);
  1825. return true;
  1826. }
  1827. // Determine whether the previous declaration was a definition,
  1828. // implicit declaration, or a declaration.
  1829. diag::kind PrevDiag;
  1830. if (Old->isThisDeclarationADefinition())
  1831. PrevDiag = diag::note_previous_definition;
  1832. else if (Old->isImplicit())
  1833. PrevDiag = diag::note_previous_implicit_declaration;
  1834. else
  1835. PrevDiag = diag::note_previous_declaration;
  1836. QualType OldQType = Context.getCanonicalType(Old->getType());
  1837. QualType NewQType = Context.getCanonicalType(New->getType());
  1838. // Don't complain about this if we're in GNU89 mode and the old function
  1839. // is an extern inline function.
  1840. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  1841. New->getStorageClass() == SC_Static &&
  1842. Old->getStorageClass() != SC_Static &&
  1843. !canRedefineFunction(Old, getLangOpts())) {
  1844. if (getLangOpts().MicrosoftExt) {
  1845. Diag(New->getLocation(), diag::warn_static_non_static) << New;
  1846. Diag(Old->getLocation(), PrevDiag);
  1847. } else {
  1848. Diag(New->getLocation(), diag::err_static_non_static) << New;
  1849. Diag(Old->getLocation(), PrevDiag);
  1850. return true;
  1851. }
  1852. }
  1853. // If a function is first declared with a calling convention, but is
  1854. // later declared or defined without one, the second decl assumes the
  1855. // calling convention of the first.
  1856. //
  1857. // It's OK if a function is first declared without a calling convention,
  1858. // but is later declared or defined with the default calling convention.
  1859. //
  1860. // For the new decl, we have to look at the NON-canonical type to tell the
  1861. // difference between a function that really doesn't have a calling
  1862. // convention and one that is declared cdecl. That's because in
  1863. // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
  1864. // because it is the default calling convention.
  1865. //
  1866. // Note also that we DO NOT return at this point, because we still have
  1867. // other tests to run.
  1868. const FunctionType *OldType = cast<FunctionType>(OldQType);
  1869. const FunctionType *NewType = New->getType()->getAs<FunctionType>();
  1870. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  1871. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  1872. bool RequiresAdjustment = false;
  1873. if (OldTypeInfo.getCC() == NewTypeInfo.getCC()) {
  1874. // Fast path: nothing to do.
  1875. // Inherit the CC from the previous declaration if it was specified
  1876. // there but not here.
  1877. } else if (NewTypeInfo.getCC() == CC_Default) {
  1878. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  1879. RequiresAdjustment = true;
  1880. // Don't complain about mismatches when the default CC is
  1881. // effectively the same as the explict one.
  1882. } else if (OldTypeInfo.getCC() == CC_Default &&
  1883. isABIDefaultCC(*this, NewTypeInfo.getCC(), New)) {
  1884. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  1885. RequiresAdjustment = true;
  1886. } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
  1887. NewTypeInfo.getCC())) {
  1888. // Calling conventions really aren't compatible, so complain.
  1889. Diag(New->getLocation(), diag::err_cconv_change)
  1890. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  1891. << (OldTypeInfo.getCC() == CC_Default)
  1892. << (OldTypeInfo.getCC() == CC_Default ? "" :
  1893. FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
  1894. Diag(Old->getLocation(), diag::note_previous_declaration);
  1895. return true;
  1896. }
  1897. // FIXME: diagnose the other way around?
  1898. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  1899. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  1900. RequiresAdjustment = true;
  1901. }
  1902. // Merge regparm attribute.
  1903. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  1904. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  1905. if (NewTypeInfo.getHasRegParm()) {
  1906. Diag(New->getLocation(), diag::err_regparm_mismatch)
  1907. << NewType->getRegParmType()
  1908. << OldType->getRegParmType();
  1909. Diag(Old->getLocation(), diag::note_previous_declaration);
  1910. return true;
  1911. }
  1912. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  1913. RequiresAdjustment = true;
  1914. }
  1915. // Merge ns_returns_retained attribute.
  1916. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  1917. if (NewTypeInfo.getProducesResult()) {
  1918. Diag(New->getLocation(), diag::err_returns_retained_mismatch);
  1919. Diag(Old->getLocation(), diag::note_previous_declaration);
  1920. return true;
  1921. }
  1922. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  1923. RequiresAdjustment = true;
  1924. }
  1925. if (RequiresAdjustment) {
  1926. NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
  1927. New->setType(QualType(NewType, 0));
  1928. NewQType = Context.getCanonicalType(New->getType());
  1929. }
  1930. // If this redeclaration makes the function inline, we may need to add it to
  1931. // UndefinedButUsed.
  1932. if (!Old->isInlined() && New->isInlined() &&
  1933. !New->hasAttr<GNUInlineAttr>() &&
  1934. (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
  1935. Old->isUsed(false) &&
  1936. !Old->isDefined() && !New->isThisDeclarationADefinition())
  1937. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  1938. SourceLocation()));
  1939. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  1940. // about it.
  1941. if (New->hasAttr<GNUInlineAttr>() &&
  1942. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  1943. UndefinedButUsed.erase(Old->getCanonicalDecl());
  1944. }
  1945. if (getLangOpts().CPlusPlus) {
  1946. // (C++98 13.1p2):
  1947. // Certain function declarations cannot be overloaded:
  1948. // -- Function declarations that differ only in the return type
  1949. // cannot be overloaded.
  1950. QualType OldReturnType = OldType->getResultType();
  1951. QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
  1952. QualType ResQT;
  1953. if (OldReturnType != NewReturnType) {
  1954. if (NewReturnType->isObjCObjectPointerType()
  1955. && OldReturnType->isObjCObjectPointerType())
  1956. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  1957. if (ResQT.isNull()) {
  1958. if (New->isCXXClassMember() && New->isOutOfLine())
  1959. Diag(New->getLocation(),
  1960. diag::err_member_def_does_not_match_ret_type) << New;
  1961. else
  1962. Diag(New->getLocation(), diag::err_ovl_diff_return_type);
  1963. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1964. return true;
  1965. }
  1966. else
  1967. NewQType = ResQT;
  1968. }
  1969. const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
  1970. CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
  1971. if (OldMethod && NewMethod) {
  1972. // Preserve triviality.
  1973. NewMethod->setTrivial(OldMethod->isTrivial());
  1974. // MSVC allows explicit template specialization at class scope:
  1975. // 2 CXMethodDecls referring to the same function will be injected.
  1976. // We don't want a redeclartion error.
  1977. bool IsClassScopeExplicitSpecialization =
  1978. OldMethod->isFunctionTemplateSpecialization() &&
  1979. NewMethod->isFunctionTemplateSpecialization();
  1980. bool isFriend = NewMethod->getFriendObjectKind();
  1981. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  1982. !IsClassScopeExplicitSpecialization) {
  1983. // -- Member function declarations with the same name and the
  1984. // same parameter types cannot be overloaded if any of them
  1985. // is a static member function declaration.
  1986. if (OldMethod->isStatic() || NewMethod->isStatic()) {
  1987. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  1988. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1989. return true;
  1990. }
  1991. // C++ [class.mem]p1:
  1992. // [...] A member shall not be declared twice in the
  1993. // member-specification, except that a nested class or member
  1994. // class template can be declared and then later defined.
  1995. if (ActiveTemplateInstantiations.empty()) {
  1996. unsigned NewDiag;
  1997. if (isa<CXXConstructorDecl>(OldMethod))
  1998. NewDiag = diag::err_constructor_redeclared;
  1999. else if (isa<CXXDestructorDecl>(NewMethod))
  2000. NewDiag = diag::err_destructor_redeclared;
  2001. else if (isa<CXXConversionDecl>(NewMethod))
  2002. NewDiag = diag::err_conv_function_redeclared;
  2003. else
  2004. NewDiag = diag::err_member_redeclared;
  2005. Diag(New->getLocation(), NewDiag);
  2006. } else {
  2007. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2008. << New << New->getType();
  2009. }
  2010. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  2011. // Complain if this is an explicit declaration of a special
  2012. // member that was initially declared implicitly.
  2013. //
  2014. // As an exception, it's okay to befriend such methods in order
  2015. // to permit the implicit constructor/destructor/operator calls.
  2016. } else if (OldMethod->isImplicit()) {
  2017. if (isFriend) {
  2018. NewMethod->setImplicit();
  2019. } else {
  2020. Diag(NewMethod->getLocation(),
  2021. diag::err_definition_of_implicitly_declared_member)
  2022. << New << getSpecialMember(OldMethod);
  2023. return true;
  2024. }
  2025. } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
  2026. Diag(NewMethod->getLocation(),
  2027. diag::err_definition_of_explicitly_defaulted_member)
  2028. << getSpecialMember(OldMethod);
  2029. return true;
  2030. }
  2031. }
  2032. // C++11 [dcl.attr.noreturn]p1:
  2033. // The first declaration of a function shall specify the noreturn
  2034. // attribute if any declaration of that function specifies the noreturn
  2035. // attribute.
  2036. if (New->hasAttr<CXX11NoReturnAttr>() &&
  2037. !Old->hasAttr<CXX11NoReturnAttr>()) {
  2038. Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
  2039. diag::err_noreturn_missing_on_first_decl);
  2040. Diag(Old->getFirstDeclaration()->getLocation(),
  2041. diag::note_noreturn_missing_first_decl);
  2042. }
  2043. // C++11 [dcl.attr.depend]p2:
  2044. // The first declaration of a function shall specify the
  2045. // carries_dependency attribute for its declarator-id if any declaration
  2046. // of the function specifies the carries_dependency attribute.
  2047. if (New->hasAttr<CarriesDependencyAttr>() &&
  2048. !Old->hasAttr<CarriesDependencyAttr>()) {
  2049. Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
  2050. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  2051. Diag(Old->getFirstDeclaration()->getLocation(),
  2052. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  2053. }
  2054. // (C++98 8.3.5p3):
  2055. // All declarations for a function shall agree exactly in both the
  2056. // return type and the parameter-type-list.
  2057. // We also want to respect all the extended bits except noreturn.
  2058. // noreturn should now match unless the old type info didn't have it.
  2059. QualType OldQTypeForComparison = OldQType;
  2060. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  2061. assert(OldQType == QualType(OldType, 0));
  2062. const FunctionType *OldTypeForComparison
  2063. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  2064. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  2065. assert(OldQTypeForComparison.isCanonical());
  2066. }
  2067. if (!Old->hasCLanguageLinkage() && New->hasCLanguageLinkage()) {
  2068. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  2069. Diag(Old->getLocation(), PrevDiag);
  2070. return true;
  2071. }
  2072. if (OldQTypeForComparison == NewQType)
  2073. return MergeCompatibleFunctionDecls(New, Old, S);
  2074. // Fall through for conflicting redeclarations and redefinitions.
  2075. }
  2076. // C: Function types need to be compatible, not identical. This handles
  2077. // duplicate function decls like "void f(int); void f(enum X);" properly.
  2078. if (!getLangOpts().CPlusPlus &&
  2079. Context.typesAreCompatible(OldQType, NewQType)) {
  2080. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  2081. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  2082. const FunctionProtoType *OldProto = 0;
  2083. if (isa<FunctionNoProtoType>(NewFuncType) &&
  2084. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  2085. // The old declaration provided a function prototype, but the
  2086. // new declaration does not. Merge in the prototype.
  2087. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  2088. SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
  2089. OldProto->arg_type_end());
  2090. NewQType = Context.getFunctionType(NewFuncType->getResultType(),
  2091. ParamTypes.data(), ParamTypes.size(),
  2092. OldProto->getExtProtoInfo());
  2093. New->setType(NewQType);
  2094. New->setHasInheritedPrototype();
  2095. // Synthesize a parameter for each argument type.
  2096. SmallVector<ParmVarDecl*, 16> Params;
  2097. for (FunctionProtoType::arg_type_iterator
  2098. ParamType = OldProto->arg_type_begin(),
  2099. ParamEnd = OldProto->arg_type_end();
  2100. ParamType != ParamEnd; ++ParamType) {
  2101. ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
  2102. SourceLocation(),
  2103. SourceLocation(), 0,
  2104. *ParamType, /*TInfo=*/0,
  2105. SC_None, SC_None,
  2106. 0);
  2107. Param->setScopeInfo(0, Params.size());
  2108. Param->setImplicit();
  2109. Params.push_back(Param);
  2110. }
  2111. New->setParams(Params);
  2112. }
  2113. return MergeCompatibleFunctionDecls(New, Old, S);
  2114. }
  2115. // GNU C permits a K&R definition to follow a prototype declaration
  2116. // if the declared types of the parameters in the K&R definition
  2117. // match the types in the prototype declaration, even when the
  2118. // promoted types of the parameters from the K&R definition differ
  2119. // from the types in the prototype. GCC then keeps the types from
  2120. // the prototype.
  2121. //
  2122. // If a variadic prototype is followed by a non-variadic K&R definition,
  2123. // the K&R definition becomes variadic. This is sort of an edge case, but
  2124. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  2125. // C99 6.9.1p8.
  2126. if (!getLangOpts().CPlusPlus &&
  2127. Old->hasPrototype() && !New->hasPrototype() &&
  2128. New->getType()->getAs<FunctionProtoType>() &&
  2129. Old->getNumParams() == New->getNumParams()) {
  2130. SmallVector<QualType, 16> ArgTypes;
  2131. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  2132. const FunctionProtoType *OldProto
  2133. = Old->getType()->getAs<FunctionProtoType>();
  2134. const FunctionProtoType *NewProto
  2135. = New->getType()->getAs<FunctionProtoType>();
  2136. // Determine whether this is the GNU C extension.
  2137. QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
  2138. NewProto->getResultType());
  2139. bool LooseCompatible = !MergedReturn.isNull();
  2140. for (unsigned Idx = 0, End = Old->getNumParams();
  2141. LooseCompatible && Idx != End; ++Idx) {
  2142. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  2143. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  2144. if (Context.typesAreCompatible(OldParm->getType(),
  2145. NewProto->getArgType(Idx))) {
  2146. ArgTypes.push_back(NewParm->getType());
  2147. } else if (Context.typesAreCompatible(OldParm->getType(),
  2148. NewParm->getType(),
  2149. /*CompareUnqualified=*/true)) {
  2150. GNUCompatibleParamWarning Warn
  2151. = { OldParm, NewParm, NewProto->getArgType(Idx) };
  2152. Warnings.push_back(Warn);
  2153. ArgTypes.push_back(NewParm->getType());
  2154. } else
  2155. LooseCompatible = false;
  2156. }
  2157. if (LooseCompatible) {
  2158. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  2159. Diag(Warnings[Warn].NewParm->getLocation(),
  2160. diag::ext_param_promoted_not_compatible_with_prototype)
  2161. << Warnings[Warn].PromotedType
  2162. << Warnings[Warn].OldParm->getType();
  2163. if (Warnings[Warn].OldParm->getLocation().isValid())
  2164. Diag(Warnings[Warn].OldParm->getLocation(),
  2165. diag::note_previous_declaration);
  2166. }
  2167. New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
  2168. ArgTypes.size(),
  2169. OldProto->getExtProtoInfo()));
  2170. return MergeCompatibleFunctionDecls(New, Old, S);
  2171. }
  2172. // Fall through to diagnose conflicting types.
  2173. }
  2174. // A function that has already been declared has been redeclared or defined
  2175. // with a different type- show appropriate diagnostic
  2176. if (unsigned BuiltinID = Old->getBuiltinID()) {
  2177. // The user has declared a builtin function with an incompatible
  2178. // signature.
  2179. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  2180. // The function the user is redeclaring is a library-defined
  2181. // function like 'malloc' or 'printf'. Warn about the
  2182. // redeclaration, then pretend that we don't know about this
  2183. // library built-in.
  2184. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  2185. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  2186. << Old << Old->getType();
  2187. New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
  2188. Old->setInvalidDecl();
  2189. return false;
  2190. }
  2191. PrevDiag = diag::note_previous_builtin_declaration;
  2192. }
  2193. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  2194. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  2195. return true;
  2196. }
  2197. /// \brief Completes the merge of two function declarations that are
  2198. /// known to be compatible.
  2199. ///
  2200. /// This routine handles the merging of attributes and other
  2201. /// properties of function declarations form the old declaration to
  2202. /// the new declaration, once we know that New is in fact a
  2203. /// redeclaration of Old.
  2204. ///
  2205. /// \returns false
  2206. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  2207. Scope *S) {
  2208. // Merge the attributes
  2209. mergeDeclAttributes(New, Old);
  2210. // Merge the storage class.
  2211. if (Old->getStorageClass() != SC_Extern &&
  2212. Old->getStorageClass() != SC_None)
  2213. New->setStorageClass(Old->getStorageClass());
  2214. // Merge "pure" flag.
  2215. if (Old->isPure())
  2216. New->setPure();
  2217. // Merge "used" flag.
  2218. if (Old->isUsed(false))
  2219. New->setUsed();
  2220. // Merge attributes from the parameters. These can mismatch with K&R
  2221. // declarations.
  2222. if (New->getNumParams() == Old->getNumParams())
  2223. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
  2224. mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
  2225. *this);
  2226. if (getLangOpts().CPlusPlus)
  2227. return MergeCXXFunctionDecl(New, Old, S);
  2228. // Merge the function types so the we get the composite types for the return
  2229. // and argument types.
  2230. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  2231. if (!Merged.isNull())
  2232. New->setType(Merged);
  2233. return false;
  2234. }
  2235. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  2236. ObjCMethodDecl *oldMethod) {
  2237. // Merge the attributes, including deprecated/unavailable
  2238. mergeDeclAttributes(newMethod, oldMethod, AMK_Override);
  2239. // Merge attributes from the parameters.
  2240. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  2241. oe = oldMethod->param_end();
  2242. for (ObjCMethodDecl::param_iterator
  2243. ni = newMethod->param_begin(), ne = newMethod->param_end();
  2244. ni != ne && oi != oe; ++ni, ++oi)
  2245. mergeParamDeclAttributes(*ni, *oi, *this);
  2246. CheckObjCMethodOverride(newMethod, oldMethod);
  2247. }
  2248. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  2249. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  2250. /// emitting diagnostics as appropriate.
  2251. ///
  2252. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  2253. /// to here in AddInitializerToDecl. We can't check them before the initializer
  2254. /// is attached.
  2255. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
  2256. if (New->isInvalidDecl() || Old->isInvalidDecl())
  2257. return;
  2258. QualType MergedT;
  2259. if (getLangOpts().CPlusPlus) {
  2260. AutoType *AT = New->getType()->getContainedAutoType();
  2261. if (AT && !AT->isDeduced()) {
  2262. // We don't know what the new type is until the initializer is attached.
  2263. return;
  2264. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  2265. // These could still be something that needs exception specs checked.
  2266. return MergeVarDeclExceptionSpecs(New, Old);
  2267. }
  2268. // C++ [basic.link]p10:
  2269. // [...] the types specified by all declarations referring to a given
  2270. // object or function shall be identical, except that declarations for an
  2271. // array object can specify array types that differ by the presence or
  2272. // absence of a major array bound (8.3.4).
  2273. else if (Old->getType()->isIncompleteArrayType() &&
  2274. New->getType()->isArrayType()) {
  2275. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  2276. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  2277. if (Context.hasSameType(OldArray->getElementType(),
  2278. NewArray->getElementType()))
  2279. MergedT = New->getType();
  2280. } else if (Old->getType()->isArrayType() &&
  2281. New->getType()->isIncompleteArrayType()) {
  2282. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  2283. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  2284. if (Context.hasSameType(OldArray->getElementType(),
  2285. NewArray->getElementType()))
  2286. MergedT = Old->getType();
  2287. } else if (New->getType()->isObjCObjectPointerType()
  2288. && Old->getType()->isObjCObjectPointerType()) {
  2289. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  2290. Old->getType());
  2291. }
  2292. } else {
  2293. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  2294. }
  2295. if (MergedT.isNull()) {
  2296. Diag(New->getLocation(), diag::err_redefinition_different_type)
  2297. << New->getDeclName() << New->getType() << Old->getType();
  2298. Diag(Old->getLocation(), diag::note_previous_definition);
  2299. return New->setInvalidDecl();
  2300. }
  2301. New->setType(MergedT);
  2302. }
  2303. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  2304. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  2305. /// situation, merging decls or emitting diagnostics as appropriate.
  2306. ///
  2307. /// Tentative definition rules (C99 6.9.2p2) are checked by
  2308. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  2309. /// definitions here, since the initializer hasn't been attached.
  2310. ///
  2311. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  2312. // If the new decl is already invalid, don't do any other checking.
  2313. if (New->isInvalidDecl())
  2314. return;
  2315. // Verify the old decl was also a variable.
  2316. VarDecl *Old = 0;
  2317. if (!Previous.isSingleResult() ||
  2318. !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
  2319. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2320. << New->getDeclName();
  2321. Diag(Previous.getRepresentativeDecl()->getLocation(),
  2322. diag::note_previous_definition);
  2323. return New->setInvalidDecl();
  2324. }
  2325. // C++ [class.mem]p1:
  2326. // A member shall not be declared twice in the member-specification [...]
  2327. //
  2328. // Here, we need only consider static data members.
  2329. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  2330. Diag(New->getLocation(), diag::err_duplicate_member)
  2331. << New->getIdentifier();
  2332. Diag(Old->getLocation(), diag::note_previous_declaration);
  2333. New->setInvalidDecl();
  2334. }
  2335. mergeDeclAttributes(New, Old);
  2336. // Warn if an already-declared variable is made a weak_import in a subsequent
  2337. // declaration
  2338. if (New->getAttr<WeakImportAttr>() &&
  2339. Old->getStorageClass() == SC_None &&
  2340. !Old->getAttr<WeakImportAttr>()) {
  2341. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  2342. Diag(Old->getLocation(), diag::note_previous_definition);
  2343. // Remove weak_import attribute on new declaration.
  2344. New->dropAttr<WeakImportAttr>();
  2345. }
  2346. // Merge the types.
  2347. MergeVarDeclTypes(New, Old);
  2348. if (New->isInvalidDecl())
  2349. return;
  2350. // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
  2351. if (New->getStorageClass() == SC_Static &&
  2352. (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
  2353. Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
  2354. Diag(Old->getLocation(), diag::note_previous_definition);
  2355. return New->setInvalidDecl();
  2356. }
  2357. // C99 6.2.2p4:
  2358. // For an identifier declared with the storage-class specifier
  2359. // extern in a scope in which a prior declaration of that
  2360. // identifier is visible,23) if the prior declaration specifies
  2361. // internal or external linkage, the linkage of the identifier at
  2362. // the later declaration is the same as the linkage specified at
  2363. // the prior declaration. If no prior declaration is visible, or
  2364. // if the prior declaration specifies no linkage, then the
  2365. // identifier has external linkage.
  2366. if (New->hasExternalStorage() && Old->hasLinkage())
  2367. /* Okay */;
  2368. else if (New->getStorageClass() != SC_Static &&
  2369. Old->getStorageClass() == SC_Static) {
  2370. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  2371. Diag(Old->getLocation(), diag::note_previous_definition);
  2372. return New->setInvalidDecl();
  2373. }
  2374. // Check if extern is followed by non-extern and vice-versa.
  2375. if (New->hasExternalStorage() &&
  2376. !Old->hasLinkage() && Old->isLocalVarDecl()) {
  2377. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  2378. Diag(Old->getLocation(), diag::note_previous_definition);
  2379. return New->setInvalidDecl();
  2380. }
  2381. if (Old->hasExternalStorage() &&
  2382. !New->hasLinkage() && New->isLocalVarDecl()) {
  2383. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  2384. Diag(Old->getLocation(), diag::note_previous_definition);
  2385. return New->setInvalidDecl();
  2386. }
  2387. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  2388. // FIXME: The test for external storage here seems wrong? We still
  2389. // need to check for mismatches.
  2390. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  2391. // Don't complain about out-of-line definitions of static members.
  2392. !(Old->getLexicalDeclContext()->isRecord() &&
  2393. !New->getLexicalDeclContext()->isRecord())) {
  2394. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  2395. Diag(Old->getLocation(), diag::note_previous_definition);
  2396. return New->setInvalidDecl();
  2397. }
  2398. if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
  2399. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  2400. Diag(Old->getLocation(), diag::note_previous_definition);
  2401. } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
  2402. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  2403. Diag(Old->getLocation(), diag::note_previous_definition);
  2404. }
  2405. // C++ doesn't have tentative definitions, so go right ahead and check here.
  2406. const VarDecl *Def;
  2407. if (getLangOpts().CPlusPlus &&
  2408. New->isThisDeclarationADefinition() == VarDecl::Definition &&
  2409. (Def = Old->getDefinition())) {
  2410. Diag(New->getLocation(), diag::err_redefinition)
  2411. << New->getDeclName();
  2412. Diag(Def->getLocation(), diag::note_previous_definition);
  2413. New->setInvalidDecl();
  2414. return;
  2415. }
  2416. if (!Old->hasCLanguageLinkage() && New->hasCLanguageLinkage()) {
  2417. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  2418. Diag(Old->getLocation(), diag::note_previous_definition);
  2419. New->setInvalidDecl();
  2420. return;
  2421. }
  2422. // c99 6.2.2 P4.
  2423. // For an identifier declared with the storage-class specifier extern in a
  2424. // scope in which a prior declaration of that identifier is visible, if
  2425. // the prior declaration specifies internal or external linkage, the linkage
  2426. // of the identifier at the later declaration is the same as the linkage
  2427. // specified at the prior declaration.
  2428. // FIXME. revisit this code.
  2429. if (New->hasExternalStorage() &&
  2430. Old->getLinkage() == InternalLinkage)
  2431. New->setStorageClass(Old->getStorageClass());
  2432. // Merge "used" flag.
  2433. if (Old->isUsed(false))
  2434. New->setUsed();
  2435. // Keep a chain of previous declarations.
  2436. New->setPreviousDeclaration(Old);
  2437. // Inherit access appropriately.
  2438. New->setAccess(Old->getAccess());
  2439. }
  2440. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  2441. /// no declarator (e.g. "struct foo;") is parsed.
  2442. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  2443. DeclSpec &DS) {
  2444. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
  2445. }
  2446. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  2447. /// no declarator (e.g. "struct foo;") is parsed. It also accopts template
  2448. /// parameters to cope with template friend declarations.
  2449. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  2450. DeclSpec &DS,
  2451. MultiTemplateParamsArg TemplateParams) {
  2452. Decl *TagD = 0;
  2453. TagDecl *Tag = 0;
  2454. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  2455. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  2456. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  2457. DS.getTypeSpecType() == DeclSpec::TST_union ||
  2458. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  2459. TagD = DS.getRepAsDecl();
  2460. if (!TagD) // We probably had an error
  2461. return 0;
  2462. // Note that the above type specs guarantee that the
  2463. // type rep is a Decl, whereas in many of the others
  2464. // it's a Type.
  2465. if (isa<TagDecl>(TagD))
  2466. Tag = cast<TagDecl>(TagD);
  2467. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  2468. Tag = CTD->getTemplatedDecl();
  2469. }
  2470. if (Tag) {
  2471. getASTContext().addUnnamedTag(Tag);
  2472. Tag->setFreeStanding();
  2473. if (Tag->isInvalidDecl())
  2474. return Tag;
  2475. }
  2476. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  2477. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  2478. // or incomplete types shall not be restrict-qualified."
  2479. if (TypeQuals & DeclSpec::TQ_restrict)
  2480. Diag(DS.getRestrictSpecLoc(),
  2481. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  2482. << DS.getSourceRange();
  2483. }
  2484. if (DS.isConstexprSpecified()) {
  2485. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  2486. // and definitions of functions and variables.
  2487. if (Tag)
  2488. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  2489. << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
  2490. DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
  2491. DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
  2492. DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
  2493. else
  2494. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  2495. // Don't emit warnings after this error.
  2496. return TagD;
  2497. }
  2498. if (DS.isFriendSpecified()) {
  2499. // If we're dealing with a decl but not a TagDecl, assume that
  2500. // whatever routines created it handled the friendship aspect.
  2501. if (TagD && !Tag)
  2502. return 0;
  2503. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  2504. }
  2505. // Track whether we warned about the fact that there aren't any
  2506. // declarators.
  2507. bool emittedWarning = false;
  2508. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  2509. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  2510. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  2511. if (getLangOpts().CPlusPlus ||
  2512. Record->getDeclContext()->isRecord())
  2513. return BuildAnonymousStructOrUnion(S, DS, AS, Record);
  2514. Diag(DS.getLocStart(), diag::ext_no_declarators)
  2515. << DS.getSourceRange();
  2516. emittedWarning = true;
  2517. }
  2518. }
  2519. // Check for Microsoft C extension: anonymous struct.
  2520. if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
  2521. CurContext->isRecord() &&
  2522. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  2523. // Handle 2 kinds of anonymous struct:
  2524. // struct STRUCT;
  2525. // and
  2526. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  2527. RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
  2528. if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
  2529. (DS.getTypeSpecType() == DeclSpec::TST_typename &&
  2530. DS.getRepAsType().get()->isStructureType())) {
  2531. Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
  2532. << DS.getSourceRange();
  2533. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  2534. }
  2535. }
  2536. if (getLangOpts().CPlusPlus &&
  2537. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  2538. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  2539. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  2540. !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
  2541. Diag(Enum->getLocation(), diag::ext_no_declarators)
  2542. << DS.getSourceRange();
  2543. emittedWarning = true;
  2544. }
  2545. // Skip all the checks below if we have a type error.
  2546. if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
  2547. if (!DS.isMissingDeclaratorOk()) {
  2548. // Warn about typedefs of enums without names, since this is an
  2549. // extension in both Microsoft and GNU.
  2550. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
  2551. Tag && isa<EnumDecl>(Tag)) {
  2552. Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
  2553. << DS.getSourceRange();
  2554. return Tag;
  2555. }
  2556. Diag(DS.getLocStart(), diag::ext_no_declarators)
  2557. << DS.getSourceRange();
  2558. emittedWarning = true;
  2559. }
  2560. // We're going to complain about a bunch of spurious specifiers;
  2561. // only do this if we're declaring a tag, because otherwise we
  2562. // should be getting diag::ext_no_declarators.
  2563. if (emittedWarning || (TagD && TagD->isInvalidDecl()))
  2564. return TagD;
  2565. // Note that a linkage-specification sets a storage class, but
  2566. // 'extern "C" struct foo;' is actually valid and not theoretically
  2567. // useless.
  2568. if (DeclSpec::SCS scs = DS.getStorageClassSpec())
  2569. if (!DS.isExternInLinkageSpec())
  2570. Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
  2571. << DeclSpec::getSpecifierName(scs);
  2572. if (DS.isThreadSpecified())
  2573. Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
  2574. if (DS.getTypeQualifiers()) {
  2575. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  2576. Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
  2577. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  2578. Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
  2579. // Restrict is covered above.
  2580. }
  2581. if (DS.isInlineSpecified())
  2582. Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
  2583. if (DS.isVirtualSpecified())
  2584. Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
  2585. if (DS.isExplicitSpecified())
  2586. Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
  2587. if (DS.isModulePrivateSpecified() &&
  2588. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  2589. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  2590. << Tag->getTagKind()
  2591. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  2592. // Warn about ignored type attributes, for example:
  2593. // __attribute__((aligned)) struct A;
  2594. // Attributes should be placed after tag to apply to type declaration.
  2595. if (!DS.getAttributes().empty()) {
  2596. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  2597. if (TypeSpecType == DeclSpec::TST_class ||
  2598. TypeSpecType == DeclSpec::TST_struct ||
  2599. TypeSpecType == DeclSpec::TST_interface ||
  2600. TypeSpecType == DeclSpec::TST_union ||
  2601. TypeSpecType == DeclSpec::TST_enum) {
  2602. AttributeList* attrs = DS.getAttributes().getList();
  2603. while (attrs) {
  2604. Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
  2605. << attrs->getName()
  2606. << (TypeSpecType == DeclSpec::TST_class ? 0 :
  2607. TypeSpecType == DeclSpec::TST_struct ? 1 :
  2608. TypeSpecType == DeclSpec::TST_union ? 2 :
  2609. TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
  2610. attrs = attrs->getNext();
  2611. }
  2612. }
  2613. }
  2614. ActOnDocumentableDecl(TagD);
  2615. return TagD;
  2616. }
  2617. /// We are trying to inject an anonymous member into the given scope;
  2618. /// check if there's an existing declaration that can't be overloaded.
  2619. ///
  2620. /// \return true if this is a forbidden redeclaration
  2621. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  2622. Scope *S,
  2623. DeclContext *Owner,
  2624. DeclarationName Name,
  2625. SourceLocation NameLoc,
  2626. unsigned diagnostic) {
  2627. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  2628. Sema::ForRedeclaration);
  2629. if (!SemaRef.LookupName(R, S)) return false;
  2630. if (R.getAsSingle<TagDecl>())
  2631. return false;
  2632. // Pick a representative declaration.
  2633. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  2634. assert(PrevDecl && "Expected a non-null Decl");
  2635. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  2636. return false;
  2637. SemaRef.Diag(NameLoc, diagnostic) << Name;
  2638. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  2639. return true;
  2640. }
  2641. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  2642. /// anonymous struct or union AnonRecord into the owning context Owner
  2643. /// and scope S. This routine will be invoked just after we realize
  2644. /// that an unnamed union or struct is actually an anonymous union or
  2645. /// struct, e.g.,
  2646. ///
  2647. /// @code
  2648. /// union {
  2649. /// int i;
  2650. /// float f;
  2651. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  2652. /// // f into the surrounding scope.x
  2653. /// @endcode
  2654. ///
  2655. /// This routine is recursive, injecting the names of nested anonymous
  2656. /// structs/unions into the owning context and scope as well.
  2657. static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
  2658. DeclContext *Owner,
  2659. RecordDecl *AnonRecord,
  2660. AccessSpecifier AS,
  2661. SmallVector<NamedDecl*, 2> &Chaining,
  2662. bool MSAnonStruct) {
  2663. unsigned diagKind
  2664. = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
  2665. : diag::err_anonymous_struct_member_redecl;
  2666. bool Invalid = false;
  2667. // Look every FieldDecl and IndirectFieldDecl with a name.
  2668. for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
  2669. DEnd = AnonRecord->decls_end();
  2670. D != DEnd; ++D) {
  2671. if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
  2672. cast<NamedDecl>(*D)->getDeclName()) {
  2673. ValueDecl *VD = cast<ValueDecl>(*D);
  2674. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  2675. VD->getLocation(), diagKind)) {
  2676. // C++ [class.union]p2:
  2677. // The names of the members of an anonymous union shall be
  2678. // distinct from the names of any other entity in the
  2679. // scope in which the anonymous union is declared.
  2680. Invalid = true;
  2681. } else {
  2682. // C++ [class.union]p2:
  2683. // For the purpose of name lookup, after the anonymous union
  2684. // definition, the members of the anonymous union are
  2685. // considered to have been defined in the scope in which the
  2686. // anonymous union is declared.
  2687. unsigned OldChainingSize = Chaining.size();
  2688. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  2689. for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
  2690. PE = IF->chain_end(); PI != PE; ++PI)
  2691. Chaining.push_back(*PI);
  2692. else
  2693. Chaining.push_back(VD);
  2694. assert(Chaining.size() >= 2);
  2695. NamedDecl **NamedChain =
  2696. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  2697. for (unsigned i = 0; i < Chaining.size(); i++)
  2698. NamedChain[i] = Chaining[i];
  2699. IndirectFieldDecl* IndirectField =
  2700. IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
  2701. VD->getIdentifier(), VD->getType(),
  2702. NamedChain, Chaining.size());
  2703. IndirectField->setAccess(AS);
  2704. IndirectField->setImplicit();
  2705. SemaRef.PushOnScopeChains(IndirectField, S);
  2706. // That includes picking up the appropriate access specifier.
  2707. if (AS != AS_none) IndirectField->setAccess(AS);
  2708. Chaining.resize(OldChainingSize);
  2709. }
  2710. }
  2711. }
  2712. return Invalid;
  2713. }
  2714. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  2715. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  2716. /// illegal input values are mapped to SC_None.
  2717. static StorageClass
  2718. StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
  2719. switch (StorageClassSpec) {
  2720. case DeclSpec::SCS_unspecified: return SC_None;
  2721. case DeclSpec::SCS_extern: return SC_Extern;
  2722. case DeclSpec::SCS_static: return SC_Static;
  2723. case DeclSpec::SCS_auto: return SC_Auto;
  2724. case DeclSpec::SCS_register: return SC_Register;
  2725. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  2726. // Illegal SCSs map to None: error reporting is up to the caller.
  2727. case DeclSpec::SCS_mutable: // Fall through.
  2728. case DeclSpec::SCS_typedef: return SC_None;
  2729. }
  2730. llvm_unreachable("unknown storage class specifier");
  2731. }
  2732. /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
  2733. /// a StorageClass. Any error reporting is up to the caller:
  2734. /// illegal input values are mapped to SC_None.
  2735. static StorageClass
  2736. StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
  2737. switch (StorageClassSpec) {
  2738. case DeclSpec::SCS_unspecified: return SC_None;
  2739. case DeclSpec::SCS_extern: return SC_Extern;
  2740. case DeclSpec::SCS_static: return SC_Static;
  2741. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  2742. // Illegal SCSs map to None: error reporting is up to the caller.
  2743. case DeclSpec::SCS_auto: // Fall through.
  2744. case DeclSpec::SCS_mutable: // Fall through.
  2745. case DeclSpec::SCS_register: // Fall through.
  2746. case DeclSpec::SCS_typedef: return SC_None;
  2747. }
  2748. llvm_unreachable("unknown storage class specifier");
  2749. }
  2750. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  2751. /// anonymous structure or union. Anonymous unions are a C++ feature
  2752. /// (C++ [class.union]) and a C11 feature; anonymous structures
  2753. /// are a C11 feature and GNU C++ extension.
  2754. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  2755. AccessSpecifier AS,
  2756. RecordDecl *Record) {
  2757. DeclContext *Owner = Record->getDeclContext();
  2758. // Diagnose whether this anonymous struct/union is an extension.
  2759. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  2760. Diag(Record->getLocation(), diag::ext_anonymous_union);
  2761. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  2762. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  2763. else if (!Record->isUnion() && !getLangOpts().C11)
  2764. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  2765. // C and C++ require different kinds of checks for anonymous
  2766. // structs/unions.
  2767. bool Invalid = false;
  2768. if (getLangOpts().CPlusPlus) {
  2769. const char* PrevSpec = 0;
  2770. unsigned DiagID;
  2771. if (Record->isUnion()) {
  2772. // C++ [class.union]p6:
  2773. // Anonymous unions declared in a named namespace or in the
  2774. // global namespace shall be declared static.
  2775. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  2776. (isa<TranslationUnitDecl>(Owner) ||
  2777. (isa<NamespaceDecl>(Owner) &&
  2778. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  2779. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  2780. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  2781. // Recover by adding 'static'.
  2782. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  2783. PrevSpec, DiagID);
  2784. }
  2785. // C++ [class.union]p6:
  2786. // A storage class is not allowed in a declaration of an
  2787. // anonymous union in a class scope.
  2788. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  2789. isa<RecordDecl>(Owner)) {
  2790. Diag(DS.getStorageClassSpecLoc(),
  2791. diag::err_anonymous_union_with_storage_spec)
  2792. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  2793. // Recover by removing the storage specifier.
  2794. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  2795. SourceLocation(),
  2796. PrevSpec, DiagID);
  2797. }
  2798. }
  2799. // Ignore const/volatile/restrict qualifiers.
  2800. if (DS.getTypeQualifiers()) {
  2801. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  2802. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  2803. << Record->isUnion() << 0
  2804. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  2805. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  2806. Diag(DS.getVolatileSpecLoc(),
  2807. diag::ext_anonymous_struct_union_qualified)
  2808. << Record->isUnion() << 1
  2809. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  2810. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  2811. Diag(DS.getRestrictSpecLoc(),
  2812. diag::ext_anonymous_struct_union_qualified)
  2813. << Record->isUnion() << 2
  2814. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  2815. DS.ClearTypeQualifiers();
  2816. }
  2817. // C++ [class.union]p2:
  2818. // The member-specification of an anonymous union shall only
  2819. // define non-static data members. [Note: nested types and
  2820. // functions cannot be declared within an anonymous union. ]
  2821. for (DeclContext::decl_iterator Mem = Record->decls_begin(),
  2822. MemEnd = Record->decls_end();
  2823. Mem != MemEnd; ++Mem) {
  2824. if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
  2825. // C++ [class.union]p3:
  2826. // An anonymous union shall not have private or protected
  2827. // members (clause 11).
  2828. assert(FD->getAccess() != AS_none);
  2829. if (FD->getAccess() != AS_public) {
  2830. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  2831. << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
  2832. Invalid = true;
  2833. }
  2834. // C++ [class.union]p1
  2835. // An object of a class with a non-trivial constructor, a non-trivial
  2836. // copy constructor, a non-trivial destructor, or a non-trivial copy
  2837. // assignment operator cannot be a member of a union, nor can an
  2838. // array of such objects.
  2839. if (CheckNontrivialField(FD))
  2840. Invalid = true;
  2841. } else if ((*Mem)->isImplicit()) {
  2842. // Any implicit members are fine.
  2843. } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
  2844. // This is a type that showed up in an
  2845. // elaborated-type-specifier inside the anonymous struct or
  2846. // union, but which actually declares a type outside of the
  2847. // anonymous struct or union. It's okay.
  2848. } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
  2849. if (!MemRecord->isAnonymousStructOrUnion() &&
  2850. MemRecord->getDeclName()) {
  2851. // Visual C++ allows type definition in anonymous struct or union.
  2852. if (getLangOpts().MicrosoftExt)
  2853. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  2854. << (int)Record->isUnion();
  2855. else {
  2856. // This is a nested type declaration.
  2857. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  2858. << (int)Record->isUnion();
  2859. Invalid = true;
  2860. }
  2861. } else {
  2862. // This is an anonymous type definition within another anonymous type.
  2863. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  2864. // not part of standard C++.
  2865. Diag(MemRecord->getLocation(),
  2866. diag::ext_anonymous_record_with_anonymous_type)
  2867. << (int)Record->isUnion();
  2868. }
  2869. } else if (isa<AccessSpecDecl>(*Mem)) {
  2870. // Any access specifier is fine.
  2871. } else {
  2872. // We have something that isn't a non-static data
  2873. // member. Complain about it.
  2874. unsigned DK = diag::err_anonymous_record_bad_member;
  2875. if (isa<TypeDecl>(*Mem))
  2876. DK = diag::err_anonymous_record_with_type;
  2877. else if (isa<FunctionDecl>(*Mem))
  2878. DK = diag::err_anonymous_record_with_function;
  2879. else if (isa<VarDecl>(*Mem))
  2880. DK = diag::err_anonymous_record_with_static;
  2881. // Visual C++ allows type definition in anonymous struct or union.
  2882. if (getLangOpts().MicrosoftExt &&
  2883. DK == diag::err_anonymous_record_with_type)
  2884. Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
  2885. << (int)Record->isUnion();
  2886. else {
  2887. Diag((*Mem)->getLocation(), DK)
  2888. << (int)Record->isUnion();
  2889. Invalid = true;
  2890. }
  2891. }
  2892. }
  2893. }
  2894. if (!Record->isUnion() && !Owner->isRecord()) {
  2895. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  2896. << (int)getLangOpts().CPlusPlus;
  2897. Invalid = true;
  2898. }
  2899. // Mock up a declarator.
  2900. Declarator Dc(DS, Declarator::MemberContext);
  2901. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  2902. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  2903. // Create a declaration for this anonymous struct/union.
  2904. NamedDecl *Anon = 0;
  2905. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  2906. Anon = FieldDecl::Create(Context, OwningClass,
  2907. DS.getLocStart(),
  2908. Record->getLocation(),
  2909. /*IdentifierInfo=*/0,
  2910. Context.getTypeDeclType(Record),
  2911. TInfo,
  2912. /*BitWidth=*/0, /*Mutable=*/false,
  2913. /*InitStyle=*/ICIS_NoInit);
  2914. Anon->setAccess(AS);
  2915. if (getLangOpts().CPlusPlus)
  2916. FieldCollector->Add(cast<FieldDecl>(Anon));
  2917. } else {
  2918. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  2919. assert(SCSpec != DeclSpec::SCS_typedef &&
  2920. "Parser allowed 'typedef' as storage class VarDecl.");
  2921. VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
  2922. if (SCSpec == DeclSpec::SCS_mutable) {
  2923. // mutable can only appear on non-static class members, so it's always
  2924. // an error here
  2925. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  2926. Invalid = true;
  2927. SC = SC_None;
  2928. }
  2929. SCSpec = DS.getStorageClassSpecAsWritten();
  2930. VarDecl::StorageClass SCAsWritten
  2931. = StorageClassSpecToVarDeclStorageClass(SCSpec);
  2932. Anon = VarDecl::Create(Context, Owner,
  2933. DS.getLocStart(),
  2934. Record->getLocation(), /*IdentifierInfo=*/0,
  2935. Context.getTypeDeclType(Record),
  2936. TInfo, SC, SCAsWritten);
  2937. // Default-initialize the implicit variable. This initialization will be
  2938. // trivial in almost all cases, except if a union member has an in-class
  2939. // initializer:
  2940. // union { int n = 0; };
  2941. ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
  2942. }
  2943. Anon->setImplicit();
  2944. // Add the anonymous struct/union object to the current
  2945. // context. We'll be referencing this object when we refer to one of
  2946. // its members.
  2947. Owner->addDecl(Anon);
  2948. // Inject the members of the anonymous struct/union into the owning
  2949. // context and into the identifier resolver chain for name lookup
  2950. // purposes.
  2951. SmallVector<NamedDecl*, 2> Chain;
  2952. Chain.push_back(Anon);
  2953. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
  2954. Chain, false))
  2955. Invalid = true;
  2956. // Mark this as an anonymous struct/union type. Note that we do not
  2957. // do this until after we have already checked and injected the
  2958. // members of this anonymous struct/union type, because otherwise
  2959. // the members could be injected twice: once by DeclContext when it
  2960. // builds its lookup table, and once by
  2961. // InjectAnonymousStructOrUnionMembers.
  2962. Record->setAnonymousStructOrUnion(true);
  2963. if (Invalid)
  2964. Anon->setInvalidDecl();
  2965. return Anon;
  2966. }
  2967. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  2968. /// Microsoft C anonymous structure.
  2969. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  2970. /// Example:
  2971. ///
  2972. /// struct A { int a; };
  2973. /// struct B { struct A; int b; };
  2974. ///
  2975. /// void foo() {
  2976. /// B var;
  2977. /// var.a = 3;
  2978. /// }
  2979. ///
  2980. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  2981. RecordDecl *Record) {
  2982. // If there is no Record, get the record via the typedef.
  2983. if (!Record)
  2984. Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
  2985. // Mock up a declarator.
  2986. Declarator Dc(DS, Declarator::TypeNameContext);
  2987. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  2988. assert(TInfo && "couldn't build declarator info for anonymous struct");
  2989. // Create a declaration for this anonymous struct.
  2990. NamedDecl* Anon = FieldDecl::Create(Context,
  2991. cast<RecordDecl>(CurContext),
  2992. DS.getLocStart(),
  2993. DS.getLocStart(),
  2994. /*IdentifierInfo=*/0,
  2995. Context.getTypeDeclType(Record),
  2996. TInfo,
  2997. /*BitWidth=*/0, /*Mutable=*/false,
  2998. /*InitStyle=*/ICIS_NoInit);
  2999. Anon->setImplicit();
  3000. // Add the anonymous struct object to the current context.
  3001. CurContext->addDecl(Anon);
  3002. // Inject the members of the anonymous struct into the current
  3003. // context and into the identifier resolver chain for name lookup
  3004. // purposes.
  3005. SmallVector<NamedDecl*, 2> Chain;
  3006. Chain.push_back(Anon);
  3007. RecordDecl *RecordDef = Record->getDefinition();
  3008. if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
  3009. RecordDef, AS_none,
  3010. Chain, true))
  3011. Anon->setInvalidDecl();
  3012. return Anon;
  3013. }
  3014. /// GetNameForDeclarator - Determine the full declaration name for the
  3015. /// given Declarator.
  3016. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  3017. return GetNameFromUnqualifiedId(D.getName());
  3018. }
  3019. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  3020. DeclarationNameInfo
  3021. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  3022. DeclarationNameInfo NameInfo;
  3023. NameInfo.setLoc(Name.StartLocation);
  3024. switch (Name.getKind()) {
  3025. case UnqualifiedId::IK_ImplicitSelfParam:
  3026. case UnqualifiedId::IK_Identifier:
  3027. NameInfo.setName(Name.Identifier);
  3028. NameInfo.setLoc(Name.StartLocation);
  3029. return NameInfo;
  3030. case UnqualifiedId::IK_OperatorFunctionId:
  3031. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  3032. Name.OperatorFunctionId.Operator));
  3033. NameInfo.setLoc(Name.StartLocation);
  3034. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  3035. = Name.OperatorFunctionId.SymbolLocations[0];
  3036. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  3037. = Name.EndLocation.getRawEncoding();
  3038. return NameInfo;
  3039. case UnqualifiedId::IK_LiteralOperatorId:
  3040. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  3041. Name.Identifier));
  3042. NameInfo.setLoc(Name.StartLocation);
  3043. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  3044. return NameInfo;
  3045. case UnqualifiedId::IK_ConversionFunctionId: {
  3046. TypeSourceInfo *TInfo;
  3047. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  3048. if (Ty.isNull())
  3049. return DeclarationNameInfo();
  3050. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  3051. Context.getCanonicalType(Ty)));
  3052. NameInfo.setLoc(Name.StartLocation);
  3053. NameInfo.setNamedTypeInfo(TInfo);
  3054. return NameInfo;
  3055. }
  3056. case UnqualifiedId::IK_ConstructorName: {
  3057. TypeSourceInfo *TInfo;
  3058. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  3059. if (Ty.isNull())
  3060. return DeclarationNameInfo();
  3061. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  3062. Context.getCanonicalType(Ty)));
  3063. NameInfo.setLoc(Name.StartLocation);
  3064. NameInfo.setNamedTypeInfo(TInfo);
  3065. return NameInfo;
  3066. }
  3067. case UnqualifiedId::IK_ConstructorTemplateId: {
  3068. // In well-formed code, we can only have a constructor
  3069. // template-id that refers to the current context, so go there
  3070. // to find the actual type being constructed.
  3071. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  3072. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  3073. return DeclarationNameInfo();
  3074. // Determine the type of the class being constructed.
  3075. QualType CurClassType = Context.getTypeDeclType(CurClass);
  3076. // FIXME: Check two things: that the template-id names the same type as
  3077. // CurClassType, and that the template-id does not occur when the name
  3078. // was qualified.
  3079. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  3080. Context.getCanonicalType(CurClassType)));
  3081. NameInfo.setLoc(Name.StartLocation);
  3082. // FIXME: should we retrieve TypeSourceInfo?
  3083. NameInfo.setNamedTypeInfo(0);
  3084. return NameInfo;
  3085. }
  3086. case UnqualifiedId::IK_DestructorName: {
  3087. TypeSourceInfo *TInfo;
  3088. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  3089. if (Ty.isNull())
  3090. return DeclarationNameInfo();
  3091. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  3092. Context.getCanonicalType(Ty)));
  3093. NameInfo.setLoc(Name.StartLocation);
  3094. NameInfo.setNamedTypeInfo(TInfo);
  3095. return NameInfo;
  3096. }
  3097. case UnqualifiedId::IK_TemplateId: {
  3098. TemplateName TName = Name.TemplateId->Template.get();
  3099. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  3100. return Context.getNameForTemplate(TName, TNameLoc);
  3101. }
  3102. } // switch (Name.getKind())
  3103. llvm_unreachable("Unknown name kind");
  3104. }
  3105. static QualType getCoreType(QualType Ty) {
  3106. do {
  3107. if (Ty->isPointerType() || Ty->isReferenceType())
  3108. Ty = Ty->getPointeeType();
  3109. else if (Ty->isArrayType())
  3110. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  3111. else
  3112. return Ty.withoutLocalFastQualifiers();
  3113. } while (true);
  3114. }
  3115. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  3116. /// and Definition have "nearly" matching parameters. This heuristic is
  3117. /// used to improve diagnostics in the case where an out-of-line function
  3118. /// definition doesn't match any declaration within the class or namespace.
  3119. /// Also sets Params to the list of indices to the parameters that differ
  3120. /// between the declaration and the definition. If hasSimilarParameters
  3121. /// returns true and Params is empty, then all of the parameters match.
  3122. static bool hasSimilarParameters(ASTContext &Context,
  3123. FunctionDecl *Declaration,
  3124. FunctionDecl *Definition,
  3125. SmallVectorImpl<unsigned> &Params) {
  3126. Params.clear();
  3127. if (Declaration->param_size() != Definition->param_size())
  3128. return false;
  3129. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  3130. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  3131. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  3132. // The parameter types are identical
  3133. if (Context.hasSameType(DefParamTy, DeclParamTy))
  3134. continue;
  3135. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  3136. QualType DefParamBaseTy = getCoreType(DefParamTy);
  3137. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  3138. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  3139. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  3140. (DeclTyName && DeclTyName == DefTyName))
  3141. Params.push_back(Idx);
  3142. else // The two parameters aren't even close
  3143. return false;
  3144. }
  3145. return true;
  3146. }
  3147. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  3148. /// declarator needs to be rebuilt in the current instantiation.
  3149. /// Any bits of declarator which appear before the name are valid for
  3150. /// consideration here. That's specifically the type in the decl spec
  3151. /// and the base type in any member-pointer chunks.
  3152. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  3153. DeclarationName Name) {
  3154. // The types we specifically need to rebuild are:
  3155. // - typenames, typeofs, and decltypes
  3156. // - types which will become injected class names
  3157. // Of course, we also need to rebuild any type referencing such a
  3158. // type. It's safest to just say "dependent", but we call out a
  3159. // few cases here.
  3160. DeclSpec &DS = D.getMutableDeclSpec();
  3161. switch (DS.getTypeSpecType()) {
  3162. case DeclSpec::TST_typename:
  3163. case DeclSpec::TST_typeofType:
  3164. case DeclSpec::TST_underlyingType:
  3165. case DeclSpec::TST_atomic: {
  3166. // Grab the type from the parser.
  3167. TypeSourceInfo *TSI = 0;
  3168. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  3169. if (T.isNull() || !T->isDependentType()) break;
  3170. // Make sure there's a type source info. This isn't really much
  3171. // of a waste; most dependent types should have type source info
  3172. // attached already.
  3173. if (!TSI)
  3174. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  3175. // Rebuild the type in the current instantiation.
  3176. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  3177. if (!TSI) return true;
  3178. // Store the new type back in the decl spec.
  3179. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  3180. DS.UpdateTypeRep(LocType);
  3181. break;
  3182. }
  3183. case DeclSpec::TST_decltype:
  3184. case DeclSpec::TST_typeofExpr: {
  3185. Expr *E = DS.getRepAsExpr();
  3186. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  3187. if (Result.isInvalid()) return true;
  3188. DS.UpdateExprRep(Result.get());
  3189. break;
  3190. }
  3191. default:
  3192. // Nothing to do for these decl specs.
  3193. break;
  3194. }
  3195. // It doesn't matter what order we do this in.
  3196. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  3197. DeclaratorChunk &Chunk = D.getTypeObject(I);
  3198. // The only type information in the declarator which can come
  3199. // before the declaration name is the base type of a member
  3200. // pointer.
  3201. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  3202. continue;
  3203. // Rebuild the scope specifier in-place.
  3204. CXXScopeSpec &SS = Chunk.Mem.Scope();
  3205. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  3206. return true;
  3207. }
  3208. return false;
  3209. }
  3210. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  3211. D.setFunctionDefinitionKind(FDK_Declaration);
  3212. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  3213. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  3214. Dcl && Dcl->getDeclContext()->isFileContext())
  3215. Dcl->setTopLevelDeclInObjCContainer();
  3216. return Dcl;
  3217. }
  3218. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  3219. /// If T is the name of a class, then each of the following shall have a
  3220. /// name different from T:
  3221. /// - every static data member of class T;
  3222. /// - every member function of class T
  3223. /// - every member of class T that is itself a type;
  3224. /// \returns true if the declaration name violates these rules.
  3225. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  3226. DeclarationNameInfo NameInfo) {
  3227. DeclarationName Name = NameInfo.getName();
  3228. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  3229. if (Record->getIdentifier() && Record->getDeclName() == Name) {
  3230. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  3231. return true;
  3232. }
  3233. return false;
  3234. }
  3235. /// \brief Diagnose a declaration whose declarator-id has the given
  3236. /// nested-name-specifier.
  3237. ///
  3238. /// \param SS The nested-name-specifier of the declarator-id.
  3239. ///
  3240. /// \param DC The declaration context to which the nested-name-specifier
  3241. /// resolves.
  3242. ///
  3243. /// \param Name The name of the entity being declared.
  3244. ///
  3245. /// \param Loc The location of the name of the entity being declared.
  3246. ///
  3247. /// \returns true if we cannot safely recover from this error, false otherwise.
  3248. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  3249. DeclarationName Name,
  3250. SourceLocation Loc) {
  3251. DeclContext *Cur = CurContext;
  3252. while (isa<LinkageSpecDecl>(Cur))
  3253. Cur = Cur->getParent();
  3254. // C++ [dcl.meaning]p1:
  3255. // A declarator-id shall not be qualified except for the definition
  3256. // of a member function (9.3) or static data member (9.4) outside of
  3257. // its class, the definition or explicit instantiation of a function
  3258. // or variable member of a namespace outside of its namespace, or the
  3259. // definition of an explicit specialization outside of its namespace,
  3260. // or the declaration of a friend function that is a member of
  3261. // another class or namespace (11.3). [...]
  3262. // The user provided a superfluous scope specifier that refers back to the
  3263. // class or namespaces in which the entity is already declared.
  3264. //
  3265. // class X {
  3266. // void X::f();
  3267. // };
  3268. if (Cur->Equals(DC)) {
  3269. Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
  3270. : diag::err_member_extra_qualification)
  3271. << Name << FixItHint::CreateRemoval(SS.getRange());
  3272. SS.clear();
  3273. return false;
  3274. }
  3275. // Check whether the qualifying scope encloses the scope of the original
  3276. // declaration.
  3277. if (!Cur->Encloses(DC)) {
  3278. if (Cur->isRecord())
  3279. Diag(Loc, diag::err_member_qualification)
  3280. << Name << SS.getRange();
  3281. else if (isa<TranslationUnitDecl>(DC))
  3282. Diag(Loc, diag::err_invalid_declarator_global_scope)
  3283. << Name << SS.getRange();
  3284. else if (isa<FunctionDecl>(Cur))
  3285. Diag(Loc, diag::err_invalid_declarator_in_function)
  3286. << Name << SS.getRange();
  3287. else
  3288. Diag(Loc, diag::err_invalid_declarator_scope)
  3289. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  3290. return true;
  3291. }
  3292. if (Cur->isRecord()) {
  3293. // Cannot qualify members within a class.
  3294. Diag(Loc, diag::err_member_qualification)
  3295. << Name << SS.getRange();
  3296. SS.clear();
  3297. // C++ constructors and destructors with incorrect scopes can break
  3298. // our AST invariants by having the wrong underlying types. If
  3299. // that's the case, then drop this declaration entirely.
  3300. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  3301. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  3302. !Context.hasSameType(Name.getCXXNameType(),
  3303. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  3304. return true;
  3305. return false;
  3306. }
  3307. // C++11 [dcl.meaning]p1:
  3308. // [...] "The nested-name-specifier of the qualified declarator-id shall
  3309. // not begin with a decltype-specifer"
  3310. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  3311. while (SpecLoc.getPrefix())
  3312. SpecLoc = SpecLoc.getPrefix();
  3313. if (dyn_cast_or_null<DecltypeType>(
  3314. SpecLoc.getNestedNameSpecifier()->getAsType()))
  3315. Diag(Loc, diag::err_decltype_in_declarator)
  3316. << SpecLoc.getTypeLoc().getSourceRange();
  3317. return false;
  3318. }
  3319. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  3320. MultiTemplateParamsArg TemplateParamLists) {
  3321. // TODO: consider using NameInfo for diagnostic.
  3322. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  3323. DeclarationName Name = NameInfo.getName();
  3324. // All of these full declarators require an identifier. If it doesn't have
  3325. // one, the ParsedFreeStandingDeclSpec action should be used.
  3326. if (!Name) {
  3327. if (!D.isInvalidType()) // Reject this if we think it is valid.
  3328. Diag(D.getDeclSpec().getLocStart(),
  3329. diag::err_declarator_need_ident)
  3330. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  3331. return 0;
  3332. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  3333. return 0;
  3334. // The scope passed in may not be a decl scope. Zip up the scope tree until
  3335. // we find one that is.
  3336. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  3337. (S->getFlags() & Scope::TemplateParamScope) != 0)
  3338. S = S->getParent();
  3339. DeclContext *DC = CurContext;
  3340. if (D.getCXXScopeSpec().isInvalid())
  3341. D.setInvalidType();
  3342. else if (D.getCXXScopeSpec().isSet()) {
  3343. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  3344. UPPC_DeclarationQualifier))
  3345. return 0;
  3346. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  3347. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  3348. if (!DC) {
  3349. // If we could not compute the declaration context, it's because the
  3350. // declaration context is dependent but does not refer to a class,
  3351. // class template, or class template partial specialization. Complain
  3352. // and return early, to avoid the coming semantic disaster.
  3353. Diag(D.getIdentifierLoc(),
  3354. diag::err_template_qualified_declarator_no_match)
  3355. << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
  3356. << D.getCXXScopeSpec().getRange();
  3357. return 0;
  3358. }
  3359. bool IsDependentContext = DC->isDependentContext();
  3360. if (!IsDependentContext &&
  3361. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  3362. return 0;
  3363. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  3364. Diag(D.getIdentifierLoc(),
  3365. diag::err_member_def_undefined_record)
  3366. << Name << DC << D.getCXXScopeSpec().getRange();
  3367. D.setInvalidType();
  3368. } else if (!D.getDeclSpec().isFriendSpecified()) {
  3369. if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
  3370. Name, D.getIdentifierLoc())) {
  3371. if (DC->isRecord())
  3372. return 0;
  3373. D.setInvalidType();
  3374. }
  3375. }
  3376. // Check whether we need to rebuild the type of the given
  3377. // declaration in the current instantiation.
  3378. if (EnteringContext && IsDependentContext &&
  3379. TemplateParamLists.size() != 0) {
  3380. ContextRAII SavedContext(*this, DC);
  3381. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  3382. D.setInvalidType();
  3383. }
  3384. }
  3385. if (DiagnoseClassNameShadow(DC, NameInfo))
  3386. // If this is a typedef, we'll end up spewing multiple diagnostics.
  3387. // Just return early; it's safer.
  3388. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  3389. return 0;
  3390. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  3391. QualType R = TInfo->getType();
  3392. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  3393. UPPC_DeclarationType))
  3394. D.setInvalidType();
  3395. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  3396. ForRedeclaration);
  3397. // See if this is a redefinition of a variable in the same scope.
  3398. if (!D.getCXXScopeSpec().isSet()) {
  3399. bool IsLinkageLookup = false;
  3400. // If the declaration we're planning to build will be a function
  3401. // or object with linkage, then look for another declaration with
  3402. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  3403. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  3404. /* Do nothing*/;
  3405. else if (R->isFunctionType()) {
  3406. if (CurContext->isFunctionOrMethod() ||
  3407. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  3408. IsLinkageLookup = true;
  3409. } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
  3410. IsLinkageLookup = true;
  3411. else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  3412. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  3413. IsLinkageLookup = true;
  3414. if (IsLinkageLookup)
  3415. Previous.clear(LookupRedeclarationWithLinkage);
  3416. LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
  3417. } else { // Something like "int foo::x;"
  3418. LookupQualifiedName(Previous, DC);
  3419. // C++ [dcl.meaning]p1:
  3420. // When the declarator-id is qualified, the declaration shall refer to a
  3421. // previously declared member of the class or namespace to which the
  3422. // qualifier refers (or, in the case of a namespace, of an element of the
  3423. // inline namespace set of that namespace (7.3.1)) or to a specialization
  3424. // thereof; [...]
  3425. //
  3426. // Note that we already checked the context above, and that we do not have
  3427. // enough information to make sure that Previous contains the declaration
  3428. // we want to match. For example, given:
  3429. //
  3430. // class X {
  3431. // void f();
  3432. // void f(float);
  3433. // };
  3434. //
  3435. // void X::f(int) { } // ill-formed
  3436. //
  3437. // In this case, Previous will point to the overload set
  3438. // containing the two f's declared in X, but neither of them
  3439. // matches.
  3440. // C++ [dcl.meaning]p1:
  3441. // [...] the member shall not merely have been introduced by a
  3442. // using-declaration in the scope of the class or namespace nominated by
  3443. // the nested-name-specifier of the declarator-id.
  3444. RemoveUsingDecls(Previous);
  3445. }
  3446. if (Previous.isSingleResult() &&
  3447. Previous.getFoundDecl()->isTemplateParameter()) {
  3448. // Maybe we will complain about the shadowed template parameter.
  3449. if (!D.isInvalidType())
  3450. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  3451. Previous.getFoundDecl());
  3452. // Just pretend that we didn't see the previous declaration.
  3453. Previous.clear();
  3454. }
  3455. // In C++, the previous declaration we find might be a tag type
  3456. // (class or enum). In this case, the new declaration will hide the
  3457. // tag type. Note that this does does not apply if we're declaring a
  3458. // typedef (C++ [dcl.typedef]p4).
  3459. if (Previous.isSingleTagDecl() &&
  3460. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
  3461. Previous.clear();
  3462. NamedDecl *New;
  3463. bool AddToScope = true;
  3464. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  3465. if (TemplateParamLists.size()) {
  3466. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  3467. return 0;
  3468. }
  3469. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  3470. } else if (R->isFunctionType()) {
  3471. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  3472. TemplateParamLists,
  3473. AddToScope);
  3474. } else {
  3475. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
  3476. TemplateParamLists);
  3477. }
  3478. if (New == 0)
  3479. return 0;
  3480. // If this has an identifier and is not an invalid redeclaration or
  3481. // function template specialization, add it to the scope stack.
  3482. if (New->getDeclName() && AddToScope &&
  3483. !(D.isRedeclaration() && New->isInvalidDecl()))
  3484. PushOnScopeChains(New, S);
  3485. return New;
  3486. }
  3487. /// Helper method to turn variable array types into constant array
  3488. /// types in certain situations which would otherwise be errors (for
  3489. /// GCC compatibility).
  3490. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  3491. ASTContext &Context,
  3492. bool &SizeIsNegative,
  3493. llvm::APSInt &Oversized) {
  3494. // This method tries to turn a variable array into a constant
  3495. // array even when the size isn't an ICE. This is necessary
  3496. // for compatibility with code that depends on gcc's buggy
  3497. // constant expression folding, like struct {char x[(int)(char*)2];}
  3498. SizeIsNegative = false;
  3499. Oversized = 0;
  3500. if (T->isDependentType())
  3501. return QualType();
  3502. QualifierCollector Qs;
  3503. const Type *Ty = Qs.strip(T);
  3504. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  3505. QualType Pointee = PTy->getPointeeType();
  3506. QualType FixedType =
  3507. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  3508. Oversized);
  3509. if (FixedType.isNull()) return FixedType;
  3510. FixedType = Context.getPointerType(FixedType);
  3511. return Qs.apply(Context, FixedType);
  3512. }
  3513. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  3514. QualType Inner = PTy->getInnerType();
  3515. QualType FixedType =
  3516. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  3517. Oversized);
  3518. if (FixedType.isNull()) return FixedType;
  3519. FixedType = Context.getParenType(FixedType);
  3520. return Qs.apply(Context, FixedType);
  3521. }
  3522. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  3523. if (!VLATy)
  3524. return QualType();
  3525. // FIXME: We should probably handle this case
  3526. if (VLATy->getElementType()->isVariablyModifiedType())
  3527. return QualType();
  3528. llvm::APSInt Res;
  3529. if (!VLATy->getSizeExpr() ||
  3530. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  3531. return QualType();
  3532. // Check whether the array size is negative.
  3533. if (Res.isSigned() && Res.isNegative()) {
  3534. SizeIsNegative = true;
  3535. return QualType();
  3536. }
  3537. // Check whether the array is too large to be addressed.
  3538. unsigned ActiveSizeBits
  3539. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  3540. Res);
  3541. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  3542. Oversized = Res;
  3543. return QualType();
  3544. }
  3545. return Context.getConstantArrayType(VLATy->getElementType(),
  3546. Res, ArrayType::Normal, 0);
  3547. }
  3548. static void
  3549. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  3550. if (PointerTypeLoc* SrcPTL = dyn_cast<PointerTypeLoc>(&SrcTL)) {
  3551. PointerTypeLoc* DstPTL = cast<PointerTypeLoc>(&DstTL);
  3552. FixInvalidVariablyModifiedTypeLoc(SrcPTL->getPointeeLoc(),
  3553. DstPTL->getPointeeLoc());
  3554. DstPTL->setStarLoc(SrcPTL->getStarLoc());
  3555. return;
  3556. }
  3557. if (ParenTypeLoc* SrcPTL = dyn_cast<ParenTypeLoc>(&SrcTL)) {
  3558. ParenTypeLoc* DstPTL = cast<ParenTypeLoc>(&DstTL);
  3559. FixInvalidVariablyModifiedTypeLoc(SrcPTL->getInnerLoc(),
  3560. DstPTL->getInnerLoc());
  3561. DstPTL->setLParenLoc(SrcPTL->getLParenLoc());
  3562. DstPTL->setRParenLoc(SrcPTL->getRParenLoc());
  3563. return;
  3564. }
  3565. ArrayTypeLoc* SrcATL = cast<ArrayTypeLoc>(&SrcTL);
  3566. ArrayTypeLoc* DstATL = cast<ArrayTypeLoc>(&DstTL);
  3567. TypeLoc SrcElemTL = SrcATL->getElementLoc();
  3568. TypeLoc DstElemTL = DstATL->getElementLoc();
  3569. DstElemTL.initializeFullCopy(SrcElemTL);
  3570. DstATL->setLBracketLoc(SrcATL->getLBracketLoc());
  3571. DstATL->setSizeExpr(SrcATL->getSizeExpr());
  3572. DstATL->setRBracketLoc(SrcATL->getRBracketLoc());
  3573. }
  3574. /// Helper method to turn variable array types into constant array
  3575. /// types in certain situations which would otherwise be errors (for
  3576. /// GCC compatibility).
  3577. static TypeSourceInfo*
  3578. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  3579. ASTContext &Context,
  3580. bool &SizeIsNegative,
  3581. llvm::APSInt &Oversized) {
  3582. QualType FixedTy
  3583. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  3584. SizeIsNegative, Oversized);
  3585. if (FixedTy.isNull())
  3586. return 0;
  3587. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  3588. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  3589. FixedTInfo->getTypeLoc());
  3590. return FixedTInfo;
  3591. }
  3592. /// \brief Register the given locally-scoped extern "C" declaration so
  3593. /// that it can be found later for redeclarations
  3594. void
  3595. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
  3596. const LookupResult &Previous,
  3597. Scope *S) {
  3598. assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
  3599. "Decl is not a locally-scoped decl!");
  3600. // Note that we have a locally-scoped external with this name.
  3601. LocallyScopedExternCDecls[ND->getDeclName()] = ND;
  3602. if (!Previous.isSingleResult())
  3603. return;
  3604. NamedDecl *PrevDecl = Previous.getFoundDecl();
  3605. // If there was a previous declaration of this entity, it may be in
  3606. // our identifier chain. Update the identifier chain with the new
  3607. // declaration.
  3608. if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
  3609. // The previous declaration was found on the identifer resolver
  3610. // chain, so remove it from its scope.
  3611. if (S->isDeclScope(PrevDecl)) {
  3612. // Special case for redeclarations in the SAME scope.
  3613. // Because this declaration is going to be added to the identifier chain
  3614. // later, we should temporarily take it OFF the chain.
  3615. IdResolver.RemoveDecl(ND);
  3616. } else {
  3617. // Find the scope for the original declaration.
  3618. while (S && !S->isDeclScope(PrevDecl))
  3619. S = S->getParent();
  3620. }
  3621. if (S)
  3622. S->RemoveDecl(PrevDecl);
  3623. }
  3624. }
  3625. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
  3626. Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  3627. if (ExternalSource) {
  3628. // Load locally-scoped external decls from the external source.
  3629. SmallVector<NamedDecl *, 4> Decls;
  3630. ExternalSource->ReadLocallyScopedExternCDecls(Decls);
  3631. for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
  3632. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  3633. = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
  3634. if (Pos == LocallyScopedExternCDecls.end())
  3635. LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
  3636. }
  3637. }
  3638. return LocallyScopedExternCDecls.find(Name);
  3639. }
  3640. /// \brief Diagnose function specifiers on a declaration of an identifier that
  3641. /// does not identify a function.
  3642. void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
  3643. // FIXME: We should probably indicate the identifier in question to avoid
  3644. // confusion for constructs like "inline int a(), b;"
  3645. if (D.getDeclSpec().isInlineSpecified())
  3646. Diag(D.getDeclSpec().getInlineSpecLoc(),
  3647. diag::err_inline_non_function);
  3648. if (D.getDeclSpec().isVirtualSpecified())
  3649. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  3650. diag::err_virtual_non_function);
  3651. if (D.getDeclSpec().isExplicitSpecified())
  3652. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  3653. diag::err_explicit_non_function);
  3654. if (D.getDeclSpec().isNoreturnSpecified())
  3655. Diag(D.getDeclSpec().getNoreturnSpecLoc(),
  3656. diag::err_noreturn_non_function);
  3657. }
  3658. NamedDecl*
  3659. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  3660. TypeSourceInfo *TInfo, LookupResult &Previous) {
  3661. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  3662. if (D.getCXXScopeSpec().isSet()) {
  3663. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  3664. << D.getCXXScopeSpec().getRange();
  3665. D.setInvalidType();
  3666. // Pretend we didn't see the scope specifier.
  3667. DC = CurContext;
  3668. Previous.clear();
  3669. }
  3670. if (getLangOpts().CPlusPlus) {
  3671. // Check that there are no default arguments (C++ only).
  3672. CheckExtraCXXDefaultArguments(D);
  3673. }
  3674. DiagnoseFunctionSpecifiers(D);
  3675. if (D.getDeclSpec().isThreadSpecified())
  3676. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  3677. if (D.getDeclSpec().isConstexprSpecified())
  3678. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  3679. << 1;
  3680. if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
  3681. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  3682. << D.getName().getSourceRange();
  3683. return 0;
  3684. }
  3685. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  3686. if (!NewTD) return 0;
  3687. // Handle attributes prior to checking for duplicates in MergeVarDecl
  3688. ProcessDeclAttributes(S, NewTD, D);
  3689. CheckTypedefForVariablyModifiedType(S, NewTD);
  3690. bool Redeclaration = D.isRedeclaration();
  3691. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  3692. D.setRedeclaration(Redeclaration);
  3693. return ND;
  3694. }
  3695. void
  3696. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  3697. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  3698. // then it shall have block scope.
  3699. // Note that variably modified types must be fixed before merging the decl so
  3700. // that redeclarations will match.
  3701. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  3702. QualType T = TInfo->getType();
  3703. if (T->isVariablyModifiedType()) {
  3704. getCurFunction()->setHasBranchProtectedScope();
  3705. if (S->getFnParent() == 0) {
  3706. bool SizeIsNegative;
  3707. llvm::APSInt Oversized;
  3708. TypeSourceInfo *FixedTInfo =
  3709. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  3710. SizeIsNegative,
  3711. Oversized);
  3712. if (FixedTInfo) {
  3713. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  3714. NewTD->setTypeSourceInfo(FixedTInfo);
  3715. } else {
  3716. if (SizeIsNegative)
  3717. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  3718. else if (T->isVariableArrayType())
  3719. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  3720. else if (Oversized.getBoolValue())
  3721. Diag(NewTD->getLocation(), diag::err_array_too_large)
  3722. << Oversized.toString(10);
  3723. else
  3724. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  3725. NewTD->setInvalidDecl();
  3726. }
  3727. }
  3728. }
  3729. }
  3730. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  3731. /// declares a typedef-name, either using the 'typedef' type specifier or via
  3732. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  3733. NamedDecl*
  3734. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  3735. LookupResult &Previous, bool &Redeclaration) {
  3736. // Merge the decl with the existing one if appropriate. If the decl is
  3737. // in an outer scope, it isn't the same thing.
  3738. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
  3739. /*ExplicitInstantiationOrSpecialization=*/false);
  3740. filterNonConflictingPreviousDecls(Context, NewTD, Previous);
  3741. if (!Previous.empty()) {
  3742. Redeclaration = true;
  3743. MergeTypedefNameDecl(NewTD, Previous);
  3744. }
  3745. // If this is the C FILE type, notify the AST context.
  3746. if (IdentifierInfo *II = NewTD->getIdentifier())
  3747. if (!NewTD->isInvalidDecl() &&
  3748. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  3749. if (II->isStr("FILE"))
  3750. Context.setFILEDecl(NewTD);
  3751. else if (II->isStr("jmp_buf"))
  3752. Context.setjmp_bufDecl(NewTD);
  3753. else if (II->isStr("sigjmp_buf"))
  3754. Context.setsigjmp_bufDecl(NewTD);
  3755. else if (II->isStr("ucontext_t"))
  3756. Context.setucontext_tDecl(NewTD);
  3757. }
  3758. return NewTD;
  3759. }
  3760. /// \brief Determines whether the given declaration is an out-of-scope
  3761. /// previous declaration.
  3762. ///
  3763. /// This routine should be invoked when name lookup has found a
  3764. /// previous declaration (PrevDecl) that is not in the scope where a
  3765. /// new declaration by the same name is being introduced. If the new
  3766. /// declaration occurs in a local scope, previous declarations with
  3767. /// linkage may still be considered previous declarations (C99
  3768. /// 6.2.2p4-5, C++ [basic.link]p6).
  3769. ///
  3770. /// \param PrevDecl the previous declaration found by name
  3771. /// lookup
  3772. ///
  3773. /// \param DC the context in which the new declaration is being
  3774. /// declared.
  3775. ///
  3776. /// \returns true if PrevDecl is an out-of-scope previous declaration
  3777. /// for a new delcaration with the same name.
  3778. static bool
  3779. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  3780. ASTContext &Context) {
  3781. if (!PrevDecl)
  3782. return false;
  3783. if (!PrevDecl->hasLinkage())
  3784. return false;
  3785. if (Context.getLangOpts().CPlusPlus) {
  3786. // C++ [basic.link]p6:
  3787. // If there is a visible declaration of an entity with linkage
  3788. // having the same name and type, ignoring entities declared
  3789. // outside the innermost enclosing namespace scope, the block
  3790. // scope declaration declares that same entity and receives the
  3791. // linkage of the previous declaration.
  3792. DeclContext *OuterContext = DC->getRedeclContext();
  3793. if (!OuterContext->isFunctionOrMethod())
  3794. // This rule only applies to block-scope declarations.
  3795. return false;
  3796. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  3797. if (PrevOuterContext->isRecord())
  3798. // We found a member function: ignore it.
  3799. return false;
  3800. // Find the innermost enclosing namespace for the new and
  3801. // previous declarations.
  3802. OuterContext = OuterContext->getEnclosingNamespaceContext();
  3803. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  3804. // The previous declaration is in a different namespace, so it
  3805. // isn't the same function.
  3806. if (!OuterContext->Equals(PrevOuterContext))
  3807. return false;
  3808. }
  3809. return true;
  3810. }
  3811. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  3812. CXXScopeSpec &SS = D.getCXXScopeSpec();
  3813. if (!SS.isSet()) return;
  3814. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  3815. }
  3816. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  3817. QualType type = decl->getType();
  3818. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  3819. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  3820. // Various kinds of declaration aren't allowed to be __autoreleasing.
  3821. unsigned kind = -1U;
  3822. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  3823. if (var->hasAttr<BlocksAttr>())
  3824. kind = 0; // __block
  3825. else if (!var->hasLocalStorage())
  3826. kind = 1; // global
  3827. } else if (isa<ObjCIvarDecl>(decl)) {
  3828. kind = 3; // ivar
  3829. } else if (isa<FieldDecl>(decl)) {
  3830. kind = 2; // field
  3831. }
  3832. if (kind != -1U) {
  3833. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  3834. << kind;
  3835. }
  3836. } else if (lifetime == Qualifiers::OCL_None) {
  3837. // Try to infer lifetime.
  3838. if (!type->isObjCLifetimeType())
  3839. return false;
  3840. lifetime = type->getObjCARCImplicitLifetime();
  3841. type = Context.getLifetimeQualifiedType(type, lifetime);
  3842. decl->setType(type);
  3843. }
  3844. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  3845. // Thread-local variables cannot have lifetime.
  3846. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  3847. var->isThreadSpecified()) {
  3848. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  3849. << var->getType();
  3850. return true;
  3851. }
  3852. }
  3853. return false;
  3854. }
  3855. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  3856. // 'weak' only applies to declarations with external linkage.
  3857. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  3858. if (ND.getLinkage() != ExternalLinkage) {
  3859. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  3860. ND.dropAttr<WeakAttr>();
  3861. }
  3862. }
  3863. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  3864. if (ND.getLinkage() == ExternalLinkage) {
  3865. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  3866. ND.dropAttr<WeakRefAttr>();
  3867. }
  3868. }
  3869. }
  3870. NamedDecl*
  3871. Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  3872. TypeSourceInfo *TInfo, LookupResult &Previous,
  3873. MultiTemplateParamsArg TemplateParamLists) {
  3874. QualType R = TInfo->getType();
  3875. DeclarationName Name = GetNameForDeclarator(D).getName();
  3876. // Check that there are no default arguments (C++ only).
  3877. if (getLangOpts().CPlusPlus)
  3878. CheckExtraCXXDefaultArguments(D);
  3879. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  3880. assert(SCSpec != DeclSpec::SCS_typedef &&
  3881. "Parser allowed 'typedef' as storage class VarDecl.");
  3882. VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
  3883. if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16)
  3884. {
  3885. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  3886. // half array type (unless the cl_khr_fp16 extension is enabled).
  3887. if (Context.getBaseElementType(R)->isHalfType()) {
  3888. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  3889. D.setInvalidType();
  3890. }
  3891. }
  3892. if (SCSpec == DeclSpec::SCS_mutable) {
  3893. // mutable can only appear on non-static class members, so it's always
  3894. // an error here
  3895. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  3896. D.setInvalidType();
  3897. SC = SC_None;
  3898. }
  3899. SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
  3900. VarDecl::StorageClass SCAsWritten
  3901. = StorageClassSpecToVarDeclStorageClass(SCSpec);
  3902. IdentifierInfo *II = Name.getAsIdentifierInfo();
  3903. if (!II) {
  3904. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
  3905. << Name;
  3906. return 0;
  3907. }
  3908. DiagnoseFunctionSpecifiers(D);
  3909. if (!DC->isRecord() && S->getFnParent() == 0) {
  3910. // C99 6.9p2: The storage-class specifiers auto and register shall not
  3911. // appear in the declaration specifiers in an external declaration.
  3912. if (SC == SC_Auto || SC == SC_Register) {
  3913. // If this is a register variable with an asm label specified, then this
  3914. // is a GNU extension.
  3915. if (SC == SC_Register && D.getAsmLabel())
  3916. Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
  3917. else
  3918. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  3919. D.setInvalidType();
  3920. }
  3921. }
  3922. if (getLangOpts().OpenCL) {
  3923. // Set up the special work-group-local storage class for variables in the
  3924. // OpenCL __local address space.
  3925. if (R.getAddressSpace() == LangAS::opencl_local) {
  3926. SC = SC_OpenCLWorkGroupLocal;
  3927. SCAsWritten = SC_OpenCLWorkGroupLocal;
  3928. }
  3929. // OpenCL v1.2 s6.9.b p4:
  3930. // The sampler type cannot be used with the __local and __global address
  3931. // space qualifiers.
  3932. if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
  3933. R.getAddressSpace() == LangAS::opencl_global)) {
  3934. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  3935. }
  3936. // OpenCL 1.2 spec, p6.9 r:
  3937. // The event type cannot be used to declare a program scope variable.
  3938. // The event type cannot be used with the __local, __constant and __global
  3939. // address space qualifiers.
  3940. if (R->isEventT()) {
  3941. if (S->getParent() == 0) {
  3942. Diag(D.getLocStart(), diag::err_event_t_global_var);
  3943. D.setInvalidType();
  3944. }
  3945. if (R.getAddressSpace()) {
  3946. Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
  3947. D.setInvalidType();
  3948. }
  3949. }
  3950. }
  3951. bool isExplicitSpecialization = false;
  3952. VarDecl *NewVD;
  3953. if (!getLangOpts().CPlusPlus) {
  3954. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  3955. D.getIdentifierLoc(), II,
  3956. R, TInfo, SC, SCAsWritten);
  3957. if (D.isInvalidType())
  3958. NewVD->setInvalidDecl();
  3959. } else {
  3960. if (DC->isRecord() && !CurContext->isRecord()) {
  3961. // This is an out-of-line definition of a static data member.
  3962. if (SC == SC_Static) {
  3963. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  3964. diag::err_static_out_of_line)
  3965. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  3966. } else if (SC == SC_None)
  3967. SC = SC_Static;
  3968. }
  3969. if (SC == SC_Static && CurContext->isRecord()) {
  3970. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  3971. if (RD->isLocalClass())
  3972. Diag(D.getIdentifierLoc(),
  3973. diag::err_static_data_member_not_allowed_in_local_class)
  3974. << Name << RD->getDeclName();
  3975. // C++98 [class.union]p1: If a union contains a static data member,
  3976. // the program is ill-formed. C++11 drops this restriction.
  3977. if (RD->isUnion())
  3978. Diag(D.getIdentifierLoc(),
  3979. getLangOpts().CPlusPlus11
  3980. ? diag::warn_cxx98_compat_static_data_member_in_union
  3981. : diag::ext_static_data_member_in_union) << Name;
  3982. // We conservatively disallow static data members in anonymous structs.
  3983. else if (!RD->getDeclName())
  3984. Diag(D.getIdentifierLoc(),
  3985. diag::err_static_data_member_not_allowed_in_anon_struct)
  3986. << Name << RD->isUnion();
  3987. }
  3988. }
  3989. // Match up the template parameter lists with the scope specifier, then
  3990. // determine whether we have a template or a template specialization.
  3991. isExplicitSpecialization = false;
  3992. bool Invalid = false;
  3993. if (TemplateParameterList *TemplateParams
  3994. = MatchTemplateParametersToScopeSpecifier(
  3995. D.getDeclSpec().getLocStart(),
  3996. D.getIdentifierLoc(),
  3997. D.getCXXScopeSpec(),
  3998. TemplateParamLists.data(),
  3999. TemplateParamLists.size(),
  4000. /*never a friend*/ false,
  4001. isExplicitSpecialization,
  4002. Invalid)) {
  4003. if (TemplateParams->size() > 0) {
  4004. // There is no such thing as a variable template.
  4005. Diag(D.getIdentifierLoc(), diag::err_template_variable)
  4006. << II
  4007. << SourceRange(TemplateParams->getTemplateLoc(),
  4008. TemplateParams->getRAngleLoc());
  4009. return 0;
  4010. } else {
  4011. // There is an extraneous 'template<>' for this variable. Complain
  4012. // about it, but allow the declaration of the variable.
  4013. Diag(TemplateParams->getTemplateLoc(),
  4014. diag::err_template_variable_noparams)
  4015. << II
  4016. << SourceRange(TemplateParams->getTemplateLoc(),
  4017. TemplateParams->getRAngleLoc());
  4018. }
  4019. }
  4020. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  4021. D.getIdentifierLoc(), II,
  4022. R, TInfo, SC, SCAsWritten);
  4023. // If this decl has an auto type in need of deduction, make a note of the
  4024. // Decl so we can diagnose uses of it in its own initializer.
  4025. if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
  4026. R->getContainedAutoType())
  4027. ParsingInitForAutoVars.insert(NewVD);
  4028. if (D.isInvalidType() || Invalid)
  4029. NewVD->setInvalidDecl();
  4030. SetNestedNameSpecifier(NewVD, D);
  4031. if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
  4032. NewVD->setTemplateParameterListsInfo(Context,
  4033. TemplateParamLists.size(),
  4034. TemplateParamLists.data());
  4035. }
  4036. if (D.getDeclSpec().isConstexprSpecified())
  4037. NewVD->setConstexpr(true);
  4038. }
  4039. // Set the lexical context. If the declarator has a C++ scope specifier, the
  4040. // lexical context will be different from the semantic context.
  4041. NewVD->setLexicalDeclContext(CurContext);
  4042. if (D.getDeclSpec().isThreadSpecified()) {
  4043. if (NewVD->hasLocalStorage())
  4044. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
  4045. else if (!Context.getTargetInfo().isTLSSupported())
  4046. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
  4047. else
  4048. NewVD->setThreadSpecified(true);
  4049. }
  4050. if (D.getDeclSpec().isModulePrivateSpecified()) {
  4051. if (isExplicitSpecialization)
  4052. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  4053. << 2
  4054. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  4055. else if (NewVD->hasLocalStorage())
  4056. Diag(NewVD->getLocation(), diag::err_module_private_local)
  4057. << 0 << NewVD->getDeclName()
  4058. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  4059. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  4060. else
  4061. NewVD->setModulePrivate();
  4062. }
  4063. // Handle attributes prior to checking for duplicates in MergeVarDecl
  4064. ProcessDeclAttributes(S, NewVD, D);
  4065. if (NewVD->hasAttrs())
  4066. CheckAlignasUnderalignment(NewVD);
  4067. if (getLangOpts().CUDA) {
  4068. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  4069. // storage [duration]."
  4070. if (SC == SC_None && S->getFnParent() != 0 &&
  4071. (NewVD->hasAttr<CUDASharedAttr>() ||
  4072. NewVD->hasAttr<CUDAConstantAttr>())) {
  4073. NewVD->setStorageClass(SC_Static);
  4074. NewVD->setStorageClassAsWritten(SC_Static);
  4075. }
  4076. }
  4077. // In auto-retain/release, infer strong retension for variables of
  4078. // retainable type.
  4079. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  4080. NewVD->setInvalidDecl();
  4081. // Handle GNU asm-label extension (encoded as an attribute).
  4082. if (Expr *E = (Expr*)D.getAsmLabel()) {
  4083. // The parser guarantees this is a string.
  4084. StringLiteral *SE = cast<StringLiteral>(E);
  4085. StringRef Label = SE->getString();
  4086. if (S->getFnParent() != 0) {
  4087. switch (SC) {
  4088. case SC_None:
  4089. case SC_Auto:
  4090. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  4091. break;
  4092. case SC_Register:
  4093. if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
  4094. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  4095. break;
  4096. case SC_Static:
  4097. case SC_Extern:
  4098. case SC_PrivateExtern:
  4099. case SC_OpenCLWorkGroupLocal:
  4100. break;
  4101. }
  4102. }
  4103. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  4104. Context, Label));
  4105. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  4106. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  4107. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  4108. if (I != ExtnameUndeclaredIdentifiers.end()) {
  4109. NewVD->addAttr(I->second);
  4110. ExtnameUndeclaredIdentifiers.erase(I);
  4111. }
  4112. }
  4113. // Diagnose shadowed variables before filtering for scope.
  4114. if (!D.getCXXScopeSpec().isSet())
  4115. CheckShadow(S, NewVD, Previous);
  4116. // Don't consider existing declarations that are in a different
  4117. // scope and are out-of-semantic-context declarations (if the new
  4118. // declaration has linkage).
  4119. FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
  4120. isExplicitSpecialization);
  4121. if (!getLangOpts().CPlusPlus) {
  4122. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  4123. } else {
  4124. // Merge the decl with the existing one if appropriate.
  4125. if (!Previous.empty()) {
  4126. if (Previous.isSingleResult() &&
  4127. isa<FieldDecl>(Previous.getFoundDecl()) &&
  4128. D.getCXXScopeSpec().isSet()) {
  4129. // The user tried to define a non-static data member
  4130. // out-of-line (C++ [dcl.meaning]p1).
  4131. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  4132. << D.getCXXScopeSpec().getRange();
  4133. Previous.clear();
  4134. NewVD->setInvalidDecl();
  4135. }
  4136. } else if (D.getCXXScopeSpec().isSet()) {
  4137. // No previous declaration in the qualifying scope.
  4138. Diag(D.getIdentifierLoc(), diag::err_no_member)
  4139. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  4140. << D.getCXXScopeSpec().getRange();
  4141. NewVD->setInvalidDecl();
  4142. }
  4143. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  4144. // This is an explicit specialization of a static data member. Check it.
  4145. if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
  4146. CheckMemberSpecialization(NewVD, Previous))
  4147. NewVD->setInvalidDecl();
  4148. }
  4149. checkAttributesAfterMerging(*this, *NewVD);
  4150. // If this is a locally-scoped extern C variable, update the map of
  4151. // such variables.
  4152. if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
  4153. !NewVD->isInvalidDecl())
  4154. RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
  4155. // If there's a #pragma GCC visibility in scope, and this isn't a class
  4156. // member, set the visibility of this variable.
  4157. if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
  4158. AddPushedVisibilityAttribute(NewVD);
  4159. return NewVD;
  4160. }
  4161. /// \brief Diagnose variable or built-in function shadowing. Implements
  4162. /// -Wshadow.
  4163. ///
  4164. /// This method is called whenever a VarDecl is added to a "useful"
  4165. /// scope.
  4166. ///
  4167. /// \param S the scope in which the shadowing name is being declared
  4168. /// \param R the lookup of the name
  4169. ///
  4170. void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
  4171. // Return if warning is ignored.
  4172. if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
  4173. DiagnosticsEngine::Ignored)
  4174. return;
  4175. // Don't diagnose declarations at file scope.
  4176. if (D->hasGlobalStorage())
  4177. return;
  4178. DeclContext *NewDC = D->getDeclContext();
  4179. // Only diagnose if we're shadowing an unambiguous field or variable.
  4180. if (R.getResultKind() != LookupResult::Found)
  4181. return;
  4182. NamedDecl* ShadowedDecl = R.getFoundDecl();
  4183. if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
  4184. return;
  4185. // Fields are not shadowed by variables in C++ static methods.
  4186. if (isa<FieldDecl>(ShadowedDecl))
  4187. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  4188. if (MD->isStatic())
  4189. return;
  4190. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  4191. if (shadowedVar->isExternC()) {
  4192. // For shadowing external vars, make sure that we point to the global
  4193. // declaration, not a locally scoped extern declaration.
  4194. for (VarDecl::redecl_iterator
  4195. I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
  4196. I != E; ++I)
  4197. if (I->isFileVarDecl()) {
  4198. ShadowedDecl = *I;
  4199. break;
  4200. }
  4201. }
  4202. DeclContext *OldDC = ShadowedDecl->getDeclContext();
  4203. // Only warn about certain kinds of shadowing for class members.
  4204. if (NewDC && NewDC->isRecord()) {
  4205. // In particular, don't warn about shadowing non-class members.
  4206. if (!OldDC->isRecord())
  4207. return;
  4208. // TODO: should we warn about static data members shadowing
  4209. // static data members from base classes?
  4210. // TODO: don't diagnose for inaccessible shadowed members.
  4211. // This is hard to do perfectly because we might friend the
  4212. // shadowing context, but that's just a false negative.
  4213. }
  4214. // Determine what kind of declaration we're shadowing.
  4215. unsigned Kind;
  4216. if (isa<RecordDecl>(OldDC)) {
  4217. if (isa<FieldDecl>(ShadowedDecl))
  4218. Kind = 3; // field
  4219. else
  4220. Kind = 2; // static data member
  4221. } else if (OldDC->isFileContext())
  4222. Kind = 1; // global
  4223. else
  4224. Kind = 0; // local
  4225. DeclarationName Name = R.getLookupName();
  4226. // Emit warning and note.
  4227. Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
  4228. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  4229. }
  4230. /// \brief Check -Wshadow without the advantage of a previous lookup.
  4231. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  4232. if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
  4233. DiagnosticsEngine::Ignored)
  4234. return;
  4235. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  4236. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  4237. LookupName(R, S);
  4238. CheckShadow(S, D, R);
  4239. }
  4240. template<typename T>
  4241. static bool mayConflictWithNonVisibleExternC(const T *ND) {
  4242. VarDecl::StorageClass SC = ND->getStorageClass();
  4243. if (ND->hasCLanguageLinkage() && (SC == SC_Extern || SC == SC_PrivateExtern))
  4244. return true;
  4245. return ND->getDeclContext()->isTranslationUnit();
  4246. }
  4247. /// \brief Perform semantic checking on a newly-created variable
  4248. /// declaration.
  4249. ///
  4250. /// This routine performs all of the type-checking required for a
  4251. /// variable declaration once it has been built. It is used both to
  4252. /// check variables after they have been parsed and their declarators
  4253. /// have been translated into a declaration, and to check variables
  4254. /// that have been instantiated from a template.
  4255. ///
  4256. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  4257. ///
  4258. /// Returns true if the variable declaration is a redeclaration.
  4259. bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
  4260. LookupResult &Previous) {
  4261. // If the decl is already known invalid, don't check it.
  4262. if (NewVD->isInvalidDecl())
  4263. return false;
  4264. TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
  4265. QualType T = TInfo->getType();
  4266. if (T->isObjCObjectType()) {
  4267. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  4268. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  4269. T = Context.getObjCObjectPointerType(T);
  4270. NewVD->setType(T);
  4271. }
  4272. // Emit an error if an address space was applied to decl with local storage.
  4273. // This includes arrays of objects with address space qualifiers, but not
  4274. // automatic variables that point to other address spaces.
  4275. // ISO/IEC TR 18037 S5.1.2
  4276. if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
  4277. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
  4278. NewVD->setInvalidDecl();
  4279. return false;
  4280. }
  4281. // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
  4282. // scope.
  4283. if ((getLangOpts().OpenCLVersion >= 120)
  4284. && NewVD->isStaticLocal()) {
  4285. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  4286. NewVD->setInvalidDecl();
  4287. return false;
  4288. }
  4289. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  4290. && !NewVD->hasAttr<BlocksAttr>()) {
  4291. if (getLangOpts().getGC() != LangOptions::NonGC)
  4292. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  4293. else {
  4294. assert(!getLangOpts().ObjCAutoRefCount);
  4295. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  4296. }
  4297. }
  4298. bool isVM = T->isVariablyModifiedType();
  4299. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  4300. NewVD->hasAttr<BlocksAttr>())
  4301. getCurFunction()->setHasBranchProtectedScope();
  4302. if ((isVM && NewVD->hasLinkage()) ||
  4303. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  4304. bool SizeIsNegative;
  4305. llvm::APSInt Oversized;
  4306. TypeSourceInfo *FixedTInfo =
  4307. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  4308. SizeIsNegative, Oversized);
  4309. if (FixedTInfo == 0 && T->isVariableArrayType()) {
  4310. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  4311. // FIXME: This won't give the correct result for
  4312. // int a[10][n];
  4313. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  4314. if (NewVD->isFileVarDecl())
  4315. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  4316. << SizeRange;
  4317. else if (NewVD->getStorageClass() == SC_Static)
  4318. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  4319. << SizeRange;
  4320. else
  4321. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  4322. << SizeRange;
  4323. NewVD->setInvalidDecl();
  4324. return false;
  4325. }
  4326. if (FixedTInfo == 0) {
  4327. if (NewVD->isFileVarDecl())
  4328. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  4329. else
  4330. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  4331. NewVD->setInvalidDecl();
  4332. return false;
  4333. }
  4334. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  4335. NewVD->setType(FixedTInfo->getType());
  4336. NewVD->setTypeSourceInfo(FixedTInfo);
  4337. }
  4338. if (Previous.empty() && mayConflictWithNonVisibleExternC(NewVD)) {
  4339. // Since we did not find anything by this name, look for a non-visible
  4340. // extern "C" declaration with the same name.
  4341. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  4342. = findLocallyScopedExternCDecl(NewVD->getDeclName());
  4343. if (Pos != LocallyScopedExternCDecls.end())
  4344. Previous.addDecl(Pos->second);
  4345. }
  4346. // Filter out any non-conflicting previous declarations.
  4347. filterNonConflictingPreviousDecls(Context, NewVD, Previous);
  4348. if (T->isVoidType() && !NewVD->hasExternalStorage()) {
  4349. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  4350. << T;
  4351. NewVD->setInvalidDecl();
  4352. return false;
  4353. }
  4354. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  4355. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  4356. NewVD->setInvalidDecl();
  4357. return false;
  4358. }
  4359. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  4360. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  4361. NewVD->setInvalidDecl();
  4362. return false;
  4363. }
  4364. if (NewVD->isConstexpr() && !T->isDependentType() &&
  4365. RequireLiteralType(NewVD->getLocation(), T,
  4366. diag::err_constexpr_var_non_literal)) {
  4367. NewVD->setInvalidDecl();
  4368. return false;
  4369. }
  4370. if (!Previous.empty()) {
  4371. MergeVarDecl(NewVD, Previous);
  4372. return true;
  4373. }
  4374. return false;
  4375. }
  4376. /// \brief Data used with FindOverriddenMethod
  4377. struct FindOverriddenMethodData {
  4378. Sema *S;
  4379. CXXMethodDecl *Method;
  4380. };
  4381. /// \brief Member lookup function that determines whether a given C++
  4382. /// method overrides a method in a base class, to be used with
  4383. /// CXXRecordDecl::lookupInBases().
  4384. static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
  4385. CXXBasePath &Path,
  4386. void *UserData) {
  4387. RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
  4388. FindOverriddenMethodData *Data
  4389. = reinterpret_cast<FindOverriddenMethodData*>(UserData);
  4390. DeclarationName Name = Data->Method->getDeclName();
  4391. // FIXME: Do we care about other names here too?
  4392. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  4393. // We really want to find the base class destructor here.
  4394. QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
  4395. CanQualType CT = Data->S->Context.getCanonicalType(T);
  4396. Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
  4397. }
  4398. for (Path.Decls = BaseRecord->lookup(Name);
  4399. !Path.Decls.empty();
  4400. Path.Decls = Path.Decls.slice(1)) {
  4401. NamedDecl *D = Path.Decls.front();
  4402. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  4403. if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
  4404. return true;
  4405. }
  4406. }
  4407. return false;
  4408. }
  4409. namespace {
  4410. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  4411. }
  4412. /// \brief Report an error regarding overriding, along with any relevant
  4413. /// overriden methods.
  4414. ///
  4415. /// \param DiagID the primary error to report.
  4416. /// \param MD the overriding method.
  4417. /// \param OEK which overrides to include as notes.
  4418. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  4419. OverrideErrorKind OEK = OEK_All) {
  4420. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  4421. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  4422. E = MD->end_overridden_methods();
  4423. I != E; ++I) {
  4424. // This check (& the OEK parameter) could be replaced by a predicate, but
  4425. // without lambdas that would be overkill. This is still nicer than writing
  4426. // out the diag loop 3 times.
  4427. if ((OEK == OEK_All) ||
  4428. (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
  4429. (OEK == OEK_Deleted && (*I)->isDeleted()))
  4430. S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
  4431. }
  4432. }
  4433. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  4434. /// and if so, check that it's a valid override and remember it.
  4435. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  4436. // Look for virtual methods in base classes that this method might override.
  4437. CXXBasePaths Paths;
  4438. FindOverriddenMethodData Data;
  4439. Data.Method = MD;
  4440. Data.S = this;
  4441. bool hasDeletedOverridenMethods = false;
  4442. bool hasNonDeletedOverridenMethods = false;
  4443. bool AddedAny = false;
  4444. if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
  4445. for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
  4446. E = Paths.found_decls_end(); I != E; ++I) {
  4447. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
  4448. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  4449. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  4450. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  4451. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  4452. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  4453. hasDeletedOverridenMethods |= OldMD->isDeleted();
  4454. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  4455. AddedAny = true;
  4456. }
  4457. }
  4458. }
  4459. }
  4460. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  4461. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  4462. }
  4463. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  4464. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  4465. }
  4466. return AddedAny;
  4467. }
  4468. namespace {
  4469. // Struct for holding all of the extra arguments needed by
  4470. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  4471. struct ActOnFDArgs {
  4472. Scope *S;
  4473. Declarator &D;
  4474. MultiTemplateParamsArg TemplateParamLists;
  4475. bool AddToScope;
  4476. };
  4477. }
  4478. namespace {
  4479. // Callback to only accept typo corrections that have a non-zero edit distance.
  4480. // Also only accept corrections that have the same parent decl.
  4481. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  4482. public:
  4483. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  4484. CXXRecordDecl *Parent)
  4485. : Context(Context), OriginalFD(TypoFD),
  4486. ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
  4487. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  4488. if (candidate.getEditDistance() == 0)
  4489. return false;
  4490. SmallVector<unsigned, 1> MismatchedParams;
  4491. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  4492. CDeclEnd = candidate.end();
  4493. CDecl != CDeclEnd; ++CDecl) {
  4494. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  4495. if (FD && !FD->hasBody() &&
  4496. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  4497. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  4498. CXXRecordDecl *Parent = MD->getParent();
  4499. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  4500. return true;
  4501. } else if (!ExpectedParent) {
  4502. return true;
  4503. }
  4504. }
  4505. }
  4506. return false;
  4507. }
  4508. private:
  4509. ASTContext &Context;
  4510. FunctionDecl *OriginalFD;
  4511. CXXRecordDecl *ExpectedParent;
  4512. };
  4513. }
  4514. /// \brief Generate diagnostics for an invalid function redeclaration.
  4515. ///
  4516. /// This routine handles generating the diagnostic messages for an invalid
  4517. /// function redeclaration, including finding possible similar declarations
  4518. /// or performing typo correction if there are no previous declarations with
  4519. /// the same name.
  4520. ///
  4521. /// Returns a NamedDecl iff typo correction was performed and substituting in
  4522. /// the new declaration name does not cause new errors.
  4523. static NamedDecl* DiagnoseInvalidRedeclaration(
  4524. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  4525. ActOnFDArgs &ExtraArgs) {
  4526. NamedDecl *Result = NULL;
  4527. DeclarationName Name = NewFD->getDeclName();
  4528. DeclContext *NewDC = NewFD->getDeclContext();
  4529. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  4530. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  4531. SmallVector<unsigned, 1> MismatchedParams;
  4532. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  4533. TypoCorrection Correction;
  4534. bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
  4535. ExtraArgs.D.getDeclSpec().isFriendSpecified());
  4536. unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
  4537. : diag::err_member_def_does_not_match;
  4538. NewFD->setInvalidDecl();
  4539. SemaRef.LookupQualifiedName(Prev, NewDC);
  4540. assert(!Prev.isAmbiguous() &&
  4541. "Cannot have an ambiguity in previous-declaration lookup");
  4542. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  4543. DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
  4544. MD ? MD->getParent() : 0);
  4545. if (!Prev.empty()) {
  4546. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  4547. Func != FuncEnd; ++Func) {
  4548. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  4549. if (FD &&
  4550. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  4551. // Add 1 to the index so that 0 can mean the mismatch didn't
  4552. // involve a parameter
  4553. unsigned ParamNum =
  4554. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  4555. NearMatches.push_back(std::make_pair(FD, ParamNum));
  4556. }
  4557. }
  4558. // If the qualified name lookup yielded nothing, try typo correction
  4559. } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
  4560. Prev.getLookupKind(), 0, 0,
  4561. Validator, NewDC))) {
  4562. // Trap errors.
  4563. Sema::SFINAETrap Trap(SemaRef);
  4564. // Set up everything for the call to ActOnFunctionDeclarator
  4565. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  4566. ExtraArgs.D.getIdentifierLoc());
  4567. Previous.clear();
  4568. Previous.setLookupName(Correction.getCorrection());
  4569. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  4570. CDeclEnd = Correction.end();
  4571. CDecl != CDeclEnd; ++CDecl) {
  4572. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  4573. if (FD && !FD->hasBody() &&
  4574. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  4575. Previous.addDecl(FD);
  4576. }
  4577. }
  4578. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  4579. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  4580. // pieces need to verify the typo-corrected C++ declaraction and hopefully
  4581. // eliminate the need for the parameter pack ExtraArgs.
  4582. Result = SemaRef.ActOnFunctionDeclarator(
  4583. ExtraArgs.S, ExtraArgs.D,
  4584. Correction.getCorrectionDecl()->getDeclContext(),
  4585. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  4586. ExtraArgs.AddToScope);
  4587. if (Trap.hasErrorOccurred()) {
  4588. // Pretend the typo correction never occurred
  4589. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  4590. ExtraArgs.D.getIdentifierLoc());
  4591. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  4592. Previous.clear();
  4593. Previous.setLookupName(Name);
  4594. Result = NULL;
  4595. } else {
  4596. for (LookupResult::iterator Func = Previous.begin(),
  4597. FuncEnd = Previous.end();
  4598. Func != FuncEnd; ++Func) {
  4599. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
  4600. NearMatches.push_back(std::make_pair(FD, 0));
  4601. }
  4602. }
  4603. if (NearMatches.empty()) {
  4604. // Ignore the correction if it didn't yield any close FunctionDecl matches
  4605. Correction = TypoCorrection();
  4606. } else {
  4607. DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
  4608. : diag::err_member_def_does_not_match_suggest;
  4609. }
  4610. }
  4611. if (Correction) {
  4612. // FIXME: use Correction.getCorrectionRange() instead of computing the range
  4613. // here. This requires passing in the CXXScopeSpec to CorrectTypo which in
  4614. // turn causes the correction to fully qualify the name. If we fix
  4615. // CorrectTypo to minimally qualify then this change should be good.
  4616. SourceRange FixItLoc(NewFD->getLocation());
  4617. CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec();
  4618. if (Correction.getCorrectionSpecifier() && SS.isValid())
  4619. FixItLoc.setBegin(SS.getBeginLoc());
  4620. SemaRef.Diag(NewFD->getLocStart(), DiagMsg)
  4621. << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
  4622. << FixItHint::CreateReplacement(
  4623. FixItLoc, Correction.getAsString(SemaRef.getLangOpts()));
  4624. } else {
  4625. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  4626. << Name << NewDC << NewFD->getLocation();
  4627. }
  4628. bool NewFDisConst = false;
  4629. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  4630. NewFDisConst = NewMD->isConst();
  4631. for (SmallVector<std::pair<FunctionDecl *, unsigned>, 1>::iterator
  4632. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  4633. NearMatch != NearMatchEnd; ++NearMatch) {
  4634. FunctionDecl *FD = NearMatch->first;
  4635. bool FDisConst = false;
  4636. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  4637. FDisConst = MD->isConst();
  4638. if (unsigned Idx = NearMatch->second) {
  4639. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  4640. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  4641. if (Loc.isInvalid()) Loc = FD->getLocation();
  4642. SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
  4643. << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
  4644. } else if (Correction) {
  4645. SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
  4646. << Correction.getQuoted(SemaRef.getLangOpts());
  4647. } else if (FDisConst != NewFDisConst) {
  4648. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  4649. << NewFDisConst << FD->getSourceRange().getEnd();
  4650. } else
  4651. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
  4652. }
  4653. return Result;
  4654. }
  4655. static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
  4656. Declarator &D) {
  4657. switch (D.getDeclSpec().getStorageClassSpec()) {
  4658. default: llvm_unreachable("Unknown storage class!");
  4659. case DeclSpec::SCS_auto:
  4660. case DeclSpec::SCS_register:
  4661. case DeclSpec::SCS_mutable:
  4662. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4663. diag::err_typecheck_sclass_func);
  4664. D.setInvalidType();
  4665. break;
  4666. case DeclSpec::SCS_unspecified: break;
  4667. case DeclSpec::SCS_extern: return SC_Extern;
  4668. case DeclSpec::SCS_static: {
  4669. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  4670. // C99 6.7.1p5:
  4671. // The declaration of an identifier for a function that has
  4672. // block scope shall have no explicit storage-class specifier
  4673. // other than extern
  4674. // See also (C++ [dcl.stc]p4).
  4675. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4676. diag::err_static_block_func);
  4677. break;
  4678. } else
  4679. return SC_Static;
  4680. }
  4681. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4682. }
  4683. // No explicit storage class has already been returned
  4684. return SC_None;
  4685. }
  4686. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  4687. DeclContext *DC, QualType &R,
  4688. TypeSourceInfo *TInfo,
  4689. FunctionDecl::StorageClass SC,
  4690. bool &IsVirtualOkay) {
  4691. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  4692. DeclarationName Name = NameInfo.getName();
  4693. FunctionDecl *NewFD = 0;
  4694. bool isInline = D.getDeclSpec().isInlineSpecified();
  4695. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
  4696. FunctionDecl::StorageClass SCAsWritten
  4697. = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
  4698. if (!SemaRef.getLangOpts().CPlusPlus) {
  4699. // Determine whether the function was written with a
  4700. // prototype. This true when:
  4701. // - there is a prototype in the declarator, or
  4702. // - the type R of the function is some kind of typedef or other reference
  4703. // to a type name (which eventually refers to a function type).
  4704. bool HasPrototype =
  4705. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  4706. (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
  4707. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  4708. D.getLocStart(), NameInfo, R,
  4709. TInfo, SC, SCAsWritten, isInline,
  4710. HasPrototype);
  4711. if (D.isInvalidType())
  4712. NewFD->setInvalidDecl();
  4713. // Set the lexical context.
  4714. NewFD->setLexicalDeclContext(SemaRef.CurContext);
  4715. return NewFD;
  4716. }
  4717. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  4718. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  4719. // Check that the return type is not an abstract class type.
  4720. // For record types, this is done by the AbstractClassUsageDiagnoser once
  4721. // the class has been completely parsed.
  4722. if (!DC->isRecord() &&
  4723. SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
  4724. R->getAs<FunctionType>()->getResultType(),
  4725. diag::err_abstract_type_in_decl,
  4726. SemaRef.AbstractReturnType))
  4727. D.setInvalidType();
  4728. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  4729. // This is a C++ constructor declaration.
  4730. assert(DC->isRecord() &&
  4731. "Constructors can only be declared in a member context");
  4732. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  4733. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4734. D.getLocStart(), NameInfo,
  4735. R, TInfo, isExplicit, isInline,
  4736. /*isImplicitlyDeclared=*/false,
  4737. isConstexpr);
  4738. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  4739. // This is a C++ destructor declaration.
  4740. if (DC->isRecord()) {
  4741. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  4742. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  4743. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  4744. SemaRef.Context, Record,
  4745. D.getLocStart(),
  4746. NameInfo, R, TInfo, isInline,
  4747. /*isImplicitlyDeclared=*/false);
  4748. // If the class is complete, then we now create the implicit exception
  4749. // specification. If the class is incomplete or dependent, we can't do
  4750. // it yet.
  4751. if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
  4752. Record->getDefinition() && !Record->isBeingDefined() &&
  4753. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  4754. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  4755. }
  4756. IsVirtualOkay = true;
  4757. return NewDD;
  4758. } else {
  4759. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  4760. D.setInvalidType();
  4761. // Create a FunctionDecl to satisfy the function definition parsing
  4762. // code path.
  4763. return FunctionDecl::Create(SemaRef.Context, DC,
  4764. D.getLocStart(),
  4765. D.getIdentifierLoc(), Name, R, TInfo,
  4766. SC, SCAsWritten, isInline,
  4767. /*hasPrototype=*/true, isConstexpr);
  4768. }
  4769. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  4770. if (!DC->isRecord()) {
  4771. SemaRef.Diag(D.getIdentifierLoc(),
  4772. diag::err_conv_function_not_member);
  4773. return 0;
  4774. }
  4775. SemaRef.CheckConversionDeclarator(D, R, SC);
  4776. IsVirtualOkay = true;
  4777. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4778. D.getLocStart(), NameInfo,
  4779. R, TInfo, isInline, isExplicit,
  4780. isConstexpr, SourceLocation());
  4781. } else if (DC->isRecord()) {
  4782. // If the name of the function is the same as the name of the record,
  4783. // then this must be an invalid constructor that has a return type.
  4784. // (The parser checks for a return type and makes the declarator a
  4785. // constructor if it has no return type).
  4786. if (Name.getAsIdentifierInfo() &&
  4787. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  4788. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  4789. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  4790. << SourceRange(D.getIdentifierLoc());
  4791. return 0;
  4792. }
  4793. bool isStatic = SC == SC_Static;
  4794. // [class.free]p1:
  4795. // Any allocation function for a class T is a static member
  4796. // (even if not explicitly declared static).
  4797. if (Name.getCXXOverloadedOperator() == OO_New ||
  4798. Name.getCXXOverloadedOperator() == OO_Array_New)
  4799. isStatic = true;
  4800. // [class.free]p6 Any deallocation function for a class X is a static member
  4801. // (even if not explicitly declared static).
  4802. if (Name.getCXXOverloadedOperator() == OO_Delete ||
  4803. Name.getCXXOverloadedOperator() == OO_Array_Delete)
  4804. isStatic = true;
  4805. IsVirtualOkay = !isStatic;
  4806. // This is a C++ method declaration.
  4807. return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4808. D.getLocStart(), NameInfo, R,
  4809. TInfo, isStatic, SCAsWritten, isInline,
  4810. isConstexpr, SourceLocation());
  4811. } else {
  4812. // Determine whether the function was written with a
  4813. // prototype. This true when:
  4814. // - we're in C++ (where every function has a prototype),
  4815. return FunctionDecl::Create(SemaRef.Context, DC,
  4816. D.getLocStart(),
  4817. NameInfo, R, TInfo, SC, SCAsWritten, isInline,
  4818. true/*HasPrototype*/, isConstexpr);
  4819. }
  4820. }
  4821. void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
  4822. // In C++, the empty parameter-type-list must be spelled "void"; a
  4823. // typedef of void is not permitted.
  4824. if (getLangOpts().CPlusPlus &&
  4825. Param->getType().getUnqualifiedType() != Context.VoidTy) {
  4826. bool IsTypeAlias = false;
  4827. if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
  4828. IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
  4829. else if (const TemplateSpecializationType *TST =
  4830. Param->getType()->getAs<TemplateSpecializationType>())
  4831. IsTypeAlias = TST->isTypeAlias();
  4832. Diag(Param->getLocation(), diag::err_param_typedef_of_void)
  4833. << IsTypeAlias;
  4834. }
  4835. }
  4836. NamedDecl*
  4837. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  4838. TypeSourceInfo *TInfo, LookupResult &Previous,
  4839. MultiTemplateParamsArg TemplateParamLists,
  4840. bool &AddToScope) {
  4841. QualType R = TInfo->getType();
  4842. assert(R.getTypePtr()->isFunctionType());
  4843. // TODO: consider using NameInfo for diagnostic.
  4844. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4845. DeclarationName Name = NameInfo.getName();
  4846. FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
  4847. if (D.getDeclSpec().isThreadSpecified())
  4848. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  4849. // Do not allow returning a objc interface by-value.
  4850. if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
  4851. Diag(D.getIdentifierLoc(),
  4852. diag::err_object_cannot_be_passed_returned_by_value) << 0
  4853. << R->getAs<FunctionType>()->getResultType()
  4854. << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
  4855. QualType T = R->getAs<FunctionType>()->getResultType();
  4856. T = Context.getObjCObjectPointerType(T);
  4857. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
  4858. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  4859. R = Context.getFunctionType(T, FPT->arg_type_begin(),
  4860. FPT->getNumArgs(), EPI);
  4861. }
  4862. else if (isa<FunctionNoProtoType>(R))
  4863. R = Context.getFunctionNoProtoType(T);
  4864. }
  4865. bool isFriend = false;
  4866. FunctionTemplateDecl *FunctionTemplate = 0;
  4867. bool isExplicitSpecialization = false;
  4868. bool isFunctionTemplateSpecialization = false;
  4869. bool isDependentClassScopeExplicitSpecialization = false;
  4870. bool HasExplicitTemplateArgs = false;
  4871. TemplateArgumentListInfo TemplateArgs;
  4872. bool isVirtualOkay = false;
  4873. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  4874. isVirtualOkay);
  4875. if (!NewFD) return 0;
  4876. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  4877. NewFD->setTopLevelDeclInObjCContainer();
  4878. if (getLangOpts().CPlusPlus) {
  4879. bool isInline = D.getDeclSpec().isInlineSpecified();
  4880. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  4881. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  4882. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  4883. isFriend = D.getDeclSpec().isFriendSpecified();
  4884. if (isFriend && !isInline && D.isFunctionDefinition()) {
  4885. // C++ [class.friend]p5
  4886. // A function can be defined in a friend declaration of a
  4887. // class . . . . Such a function is implicitly inline.
  4888. NewFD->setImplicitlyInline();
  4889. }
  4890. // If this is a method defined in an __interface, and is not a constructor
  4891. // or an overloaded operator, then set the pure flag (isVirtual will already
  4892. // return true).
  4893. if (const CXXRecordDecl *Parent =
  4894. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  4895. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  4896. NewFD->setPure(true);
  4897. }
  4898. SetNestedNameSpecifier(NewFD, D);
  4899. isExplicitSpecialization = false;
  4900. isFunctionTemplateSpecialization = false;
  4901. if (D.isInvalidType())
  4902. NewFD->setInvalidDecl();
  4903. // Set the lexical context. If the declarator has a C++
  4904. // scope specifier, or is the object of a friend declaration, the
  4905. // lexical context will be different from the semantic context.
  4906. NewFD->setLexicalDeclContext(CurContext);
  4907. // Match up the template parameter lists with the scope specifier, then
  4908. // determine whether we have a template or a template specialization.
  4909. bool Invalid = false;
  4910. if (TemplateParameterList *TemplateParams
  4911. = MatchTemplateParametersToScopeSpecifier(
  4912. D.getDeclSpec().getLocStart(),
  4913. D.getIdentifierLoc(),
  4914. D.getCXXScopeSpec(),
  4915. TemplateParamLists.data(),
  4916. TemplateParamLists.size(),
  4917. isFriend,
  4918. isExplicitSpecialization,
  4919. Invalid)) {
  4920. if (TemplateParams->size() > 0) {
  4921. // This is a function template
  4922. // Check that we can declare a template here.
  4923. if (CheckTemplateDeclScope(S, TemplateParams))
  4924. return 0;
  4925. // A destructor cannot be a template.
  4926. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  4927. Diag(NewFD->getLocation(), diag::err_destructor_template);
  4928. return 0;
  4929. }
  4930. // If we're adding a template to a dependent context, we may need to
  4931. // rebuilding some of the types used within the template parameter list,
  4932. // now that we know what the current instantiation is.
  4933. if (DC->isDependentContext()) {
  4934. ContextRAII SavedContext(*this, DC);
  4935. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  4936. Invalid = true;
  4937. }
  4938. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  4939. NewFD->getLocation(),
  4940. Name, TemplateParams,
  4941. NewFD);
  4942. FunctionTemplate->setLexicalDeclContext(CurContext);
  4943. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  4944. // For source fidelity, store the other template param lists.
  4945. if (TemplateParamLists.size() > 1) {
  4946. NewFD->setTemplateParameterListsInfo(Context,
  4947. TemplateParamLists.size() - 1,
  4948. TemplateParamLists.data());
  4949. }
  4950. } else {
  4951. // This is a function template specialization.
  4952. isFunctionTemplateSpecialization = true;
  4953. // For source fidelity, store all the template param lists.
  4954. NewFD->setTemplateParameterListsInfo(Context,
  4955. TemplateParamLists.size(),
  4956. TemplateParamLists.data());
  4957. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  4958. if (isFriend) {
  4959. // We want to remove the "template<>", found here.
  4960. SourceRange RemoveRange = TemplateParams->getSourceRange();
  4961. // If we remove the template<> and the name is not a
  4962. // template-id, we're actually silently creating a problem:
  4963. // the friend declaration will refer to an untemplated decl,
  4964. // and clearly the user wants a template specialization. So
  4965. // we need to insert '<>' after the name.
  4966. SourceLocation InsertLoc;
  4967. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  4968. InsertLoc = D.getName().getSourceRange().getEnd();
  4969. InsertLoc = PP.getLocForEndOfToken(InsertLoc);
  4970. }
  4971. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  4972. << Name << RemoveRange
  4973. << FixItHint::CreateRemoval(RemoveRange)
  4974. << FixItHint::CreateInsertion(InsertLoc, "<>");
  4975. }
  4976. }
  4977. }
  4978. else {
  4979. // All template param lists were matched against the scope specifier:
  4980. // this is NOT (an explicit specialization of) a template.
  4981. if (TemplateParamLists.size() > 0)
  4982. // For source fidelity, store all the template param lists.
  4983. NewFD->setTemplateParameterListsInfo(Context,
  4984. TemplateParamLists.size(),
  4985. TemplateParamLists.data());
  4986. }
  4987. if (Invalid) {
  4988. NewFD->setInvalidDecl();
  4989. if (FunctionTemplate)
  4990. FunctionTemplate->setInvalidDecl();
  4991. }
  4992. // C++ [dcl.fct.spec]p5:
  4993. // The virtual specifier shall only be used in declarations of
  4994. // nonstatic class member functions that appear within a
  4995. // member-specification of a class declaration; see 10.3.
  4996. //
  4997. if (isVirtual && !NewFD->isInvalidDecl()) {
  4998. if (!isVirtualOkay) {
  4999. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  5000. diag::err_virtual_non_function);
  5001. } else if (!CurContext->isRecord()) {
  5002. // 'virtual' was specified outside of the class.
  5003. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  5004. diag::err_virtual_out_of_class)
  5005. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  5006. } else if (NewFD->getDescribedFunctionTemplate()) {
  5007. // C++ [temp.mem]p3:
  5008. // A member function template shall not be virtual.
  5009. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  5010. diag::err_virtual_member_function_template)
  5011. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  5012. } else {
  5013. // Okay: Add virtual to the method.
  5014. NewFD->setVirtualAsWritten(true);
  5015. }
  5016. }
  5017. // C++ [dcl.fct.spec]p3:
  5018. // The inline specifier shall not appear on a block scope function
  5019. // declaration.
  5020. if (isInline && !NewFD->isInvalidDecl()) {
  5021. if (CurContext->isFunctionOrMethod()) {
  5022. // 'inline' is not allowed on block scope function declaration.
  5023. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5024. diag::err_inline_declaration_block_scope) << Name
  5025. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  5026. }
  5027. }
  5028. // C++ [dcl.fct.spec]p6:
  5029. // The explicit specifier shall be used only in the declaration of a
  5030. // constructor or conversion function within its class definition;
  5031. // see 12.3.1 and 12.3.2.
  5032. if (isExplicit && !NewFD->isInvalidDecl()) {
  5033. if (!CurContext->isRecord()) {
  5034. // 'explicit' was specified outside of the class.
  5035. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  5036. diag::err_explicit_out_of_class)
  5037. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  5038. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  5039. !isa<CXXConversionDecl>(NewFD)) {
  5040. // 'explicit' was specified on a function that wasn't a constructor
  5041. // or conversion function.
  5042. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  5043. diag::err_explicit_non_ctor_or_conv_function)
  5044. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  5045. }
  5046. }
  5047. if (isConstexpr) {
  5048. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  5049. // are implicitly inline.
  5050. NewFD->setImplicitlyInline();
  5051. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  5052. // be either constructors or to return a literal type. Therefore,
  5053. // destructors cannot be declared constexpr.
  5054. if (isa<CXXDestructorDecl>(NewFD))
  5055. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  5056. }
  5057. // If __module_private__ was specified, mark the function accordingly.
  5058. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5059. if (isFunctionTemplateSpecialization) {
  5060. SourceLocation ModulePrivateLoc
  5061. = D.getDeclSpec().getModulePrivateSpecLoc();
  5062. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  5063. << 0
  5064. << FixItHint::CreateRemoval(ModulePrivateLoc);
  5065. } else {
  5066. NewFD->setModulePrivate();
  5067. if (FunctionTemplate)
  5068. FunctionTemplate->setModulePrivate();
  5069. }
  5070. }
  5071. if (isFriend) {
  5072. // For now, claim that the objects have no previous declaration.
  5073. if (FunctionTemplate) {
  5074. FunctionTemplate->setObjectOfFriendDecl(false);
  5075. FunctionTemplate->setAccess(AS_public);
  5076. }
  5077. NewFD->setObjectOfFriendDecl(false);
  5078. NewFD->setAccess(AS_public);
  5079. }
  5080. // If a function is defined as defaulted or deleted, mark it as such now.
  5081. switch (D.getFunctionDefinitionKind()) {
  5082. case FDK_Declaration:
  5083. case FDK_Definition:
  5084. break;
  5085. case FDK_Defaulted:
  5086. NewFD->setDefaulted();
  5087. break;
  5088. case FDK_Deleted:
  5089. NewFD->setDeletedAsWritten();
  5090. break;
  5091. }
  5092. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  5093. D.isFunctionDefinition()) {
  5094. // C++ [class.mfct]p2:
  5095. // A member function may be defined (8.4) in its class definition, in
  5096. // which case it is an inline member function (7.1.2)
  5097. NewFD->setImplicitlyInline();
  5098. }
  5099. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  5100. !CurContext->isRecord()) {
  5101. // C++ [class.static]p1:
  5102. // A data or function member of a class may be declared static
  5103. // in a class definition, in which case it is a static member of
  5104. // the class.
  5105. // Complain about the 'static' specifier if it's on an out-of-line
  5106. // member function definition.
  5107. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5108. diag::err_static_out_of_line)
  5109. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5110. }
  5111. // C++11 [except.spec]p15:
  5112. // A deallocation function with no exception-specification is treated
  5113. // as if it were specified with noexcept(true).
  5114. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  5115. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  5116. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  5117. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
  5118. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  5119. EPI.ExceptionSpecType = EST_BasicNoexcept;
  5120. NewFD->setType(Context.getFunctionType(FPT->getResultType(),
  5121. FPT->arg_type_begin(),
  5122. FPT->getNumArgs(), EPI));
  5123. }
  5124. }
  5125. // Filter out previous declarations that don't match the scope.
  5126. FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
  5127. isExplicitSpecialization ||
  5128. isFunctionTemplateSpecialization);
  5129. // Handle GNU asm-label extension (encoded as an attribute).
  5130. if (Expr *E = (Expr*) D.getAsmLabel()) {
  5131. // The parser guarantees this is a string.
  5132. StringLiteral *SE = cast<StringLiteral>(E);
  5133. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  5134. SE->getString()));
  5135. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  5136. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  5137. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  5138. if (I != ExtnameUndeclaredIdentifiers.end()) {
  5139. NewFD->addAttr(I->second);
  5140. ExtnameUndeclaredIdentifiers.erase(I);
  5141. }
  5142. }
  5143. // Copy the parameter declarations from the declarator D to the function
  5144. // declaration NewFD, if they are available. First scavenge them into Params.
  5145. SmallVector<ParmVarDecl*, 16> Params;
  5146. if (D.isFunctionDeclarator()) {
  5147. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  5148. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  5149. // function that takes no arguments, not a function that takes a
  5150. // single void argument.
  5151. // We let through "const void" here because Sema::GetTypeForDeclarator
  5152. // already checks for that case.
  5153. if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
  5154. FTI.ArgInfo[0].Param &&
  5155. cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
  5156. // Empty arg list, don't push any params.
  5157. checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
  5158. } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
  5159. for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
  5160. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
  5161. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  5162. Param->setDeclContext(NewFD);
  5163. Params.push_back(Param);
  5164. if (Param->isInvalidDecl())
  5165. NewFD->setInvalidDecl();
  5166. }
  5167. }
  5168. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  5169. // When we're declaring a function with a typedef, typeof, etc as in the
  5170. // following example, we'll need to synthesize (unnamed)
  5171. // parameters for use in the declaration.
  5172. //
  5173. // @code
  5174. // typedef void fn(int);
  5175. // fn f;
  5176. // @endcode
  5177. // Synthesize a parameter for each argument type.
  5178. for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
  5179. AE = FT->arg_type_end(); AI != AE; ++AI) {
  5180. ParmVarDecl *Param =
  5181. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
  5182. Param->setScopeInfo(0, Params.size());
  5183. Params.push_back(Param);
  5184. }
  5185. } else {
  5186. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  5187. "Should not need args for typedef of non-prototype fn");
  5188. }
  5189. // Finally, we know we have the right number of parameters, install them.
  5190. NewFD->setParams(Params);
  5191. // Find all anonymous symbols defined during the declaration of this function
  5192. // and add to NewFD. This lets us track decls such 'enum Y' in:
  5193. //
  5194. // void f(enum Y {AA} x) {}
  5195. //
  5196. // which would otherwise incorrectly end up in the translation unit scope.
  5197. NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
  5198. DeclsInPrototypeScope.clear();
  5199. if (D.getDeclSpec().isNoreturnSpecified())
  5200. NewFD->addAttr(
  5201. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  5202. Context));
  5203. // Process the non-inheritable attributes on this declaration.
  5204. ProcessDeclAttributes(S, NewFD, D,
  5205. /*NonInheritable=*/true, /*Inheritable=*/false);
  5206. // Functions returning a variably modified type violate C99 6.7.5.2p2
  5207. // because all functions have linkage.
  5208. if (!NewFD->isInvalidDecl() &&
  5209. NewFD->getResultType()->isVariablyModifiedType()) {
  5210. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  5211. NewFD->setInvalidDecl();
  5212. }
  5213. // Handle attributes.
  5214. ProcessDeclAttributes(S, NewFD, D,
  5215. /*NonInheritable=*/false, /*Inheritable=*/true);
  5216. QualType RetType = NewFD->getResultType();
  5217. const CXXRecordDecl *Ret = RetType->isRecordType() ?
  5218. RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
  5219. if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
  5220. Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
  5221. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  5222. if (!(MD && MD->getCorrespondingMethodInClass(Ret, true))) {
  5223. NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
  5224. Context));
  5225. }
  5226. }
  5227. if (!getLangOpts().CPlusPlus) {
  5228. // Perform semantic checking on the function declaration.
  5229. bool isExplicitSpecialization=false;
  5230. if (!NewFD->isInvalidDecl()) {
  5231. if (NewFD->isMain())
  5232. CheckMain(NewFD, D.getDeclSpec());
  5233. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  5234. isExplicitSpecialization));
  5235. }
  5236. // Make graceful recovery from an invalid redeclaration.
  5237. else if (!Previous.empty())
  5238. D.setRedeclaration(true);
  5239. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  5240. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  5241. "previous declaration set still overloaded");
  5242. } else {
  5243. // If the declarator is a template-id, translate the parser's template
  5244. // argument list into our AST format.
  5245. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  5246. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  5247. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  5248. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  5249. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  5250. TemplateId->NumArgs);
  5251. translateTemplateArguments(TemplateArgsPtr,
  5252. TemplateArgs);
  5253. HasExplicitTemplateArgs = true;
  5254. if (NewFD->isInvalidDecl()) {
  5255. HasExplicitTemplateArgs = false;
  5256. } else if (FunctionTemplate) {
  5257. // Function template with explicit template arguments.
  5258. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  5259. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  5260. HasExplicitTemplateArgs = false;
  5261. } else if (!isFunctionTemplateSpecialization &&
  5262. !D.getDeclSpec().isFriendSpecified()) {
  5263. // We have encountered something that the user meant to be a
  5264. // specialization (because it has explicitly-specified template
  5265. // arguments) but that was not introduced with a "template<>" (or had
  5266. // too few of them).
  5267. Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
  5268. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
  5269. << FixItHint::CreateInsertion(
  5270. D.getDeclSpec().getLocStart(),
  5271. "template<> ");
  5272. isFunctionTemplateSpecialization = true;
  5273. } else {
  5274. // "friend void foo<>(int);" is an implicit specialization decl.
  5275. isFunctionTemplateSpecialization = true;
  5276. }
  5277. } else if (isFriend && isFunctionTemplateSpecialization) {
  5278. // This combination is only possible in a recovery case; the user
  5279. // wrote something like:
  5280. // template <> friend void foo(int);
  5281. // which we're recovering from as if the user had written:
  5282. // friend void foo<>(int);
  5283. // Go ahead and fake up a template id.
  5284. HasExplicitTemplateArgs = true;
  5285. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  5286. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  5287. }
  5288. // If it's a friend (and only if it's a friend), it's possible
  5289. // that either the specialized function type or the specialized
  5290. // template is dependent, and therefore matching will fail. In
  5291. // this case, don't check the specialization yet.
  5292. bool InstantiationDependent = false;
  5293. if (isFunctionTemplateSpecialization && isFriend &&
  5294. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  5295. TemplateSpecializationType::anyDependentTemplateArguments(
  5296. TemplateArgs.getArgumentArray(), TemplateArgs.size(),
  5297. InstantiationDependent))) {
  5298. assert(HasExplicitTemplateArgs &&
  5299. "friend function specialization without template args");
  5300. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  5301. Previous))
  5302. NewFD->setInvalidDecl();
  5303. } else if (isFunctionTemplateSpecialization) {
  5304. if (CurContext->isDependentContext() && CurContext->isRecord()
  5305. && !isFriend) {
  5306. isDependentClassScopeExplicitSpecialization = true;
  5307. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  5308. diag::ext_function_specialization_in_class :
  5309. diag::err_function_specialization_in_class)
  5310. << NewFD->getDeclName();
  5311. } else if (CheckFunctionTemplateSpecialization(NewFD,
  5312. (HasExplicitTemplateArgs ? &TemplateArgs : 0),
  5313. Previous))
  5314. NewFD->setInvalidDecl();
  5315. // C++ [dcl.stc]p1:
  5316. // A storage-class-specifier shall not be specified in an explicit
  5317. // specialization (14.7.3)
  5318. if (SC != SC_None) {
  5319. if (SC != NewFD->getStorageClass())
  5320. Diag(NewFD->getLocation(),
  5321. diag::err_explicit_specialization_inconsistent_storage_class)
  5322. << SC
  5323. << FixItHint::CreateRemoval(
  5324. D.getDeclSpec().getStorageClassSpecLoc());
  5325. else
  5326. Diag(NewFD->getLocation(),
  5327. diag::ext_explicit_specialization_storage_class)
  5328. << FixItHint::CreateRemoval(
  5329. D.getDeclSpec().getStorageClassSpecLoc());
  5330. }
  5331. } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
  5332. if (CheckMemberSpecialization(NewFD, Previous))
  5333. NewFD->setInvalidDecl();
  5334. }
  5335. // Perform semantic checking on the function declaration.
  5336. if (!isDependentClassScopeExplicitSpecialization) {
  5337. if (NewFD->isInvalidDecl()) {
  5338. // If this is a class member, mark the class invalid immediately.
  5339. // This avoids some consistency errors later.
  5340. if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
  5341. methodDecl->getParent()->setInvalidDecl();
  5342. } else {
  5343. if (NewFD->isMain())
  5344. CheckMain(NewFD, D.getDeclSpec());
  5345. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  5346. isExplicitSpecialization));
  5347. }
  5348. }
  5349. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  5350. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  5351. "previous declaration set still overloaded");
  5352. NamedDecl *PrincipalDecl = (FunctionTemplate
  5353. ? cast<NamedDecl>(FunctionTemplate)
  5354. : NewFD);
  5355. if (isFriend && D.isRedeclaration()) {
  5356. AccessSpecifier Access = AS_public;
  5357. if (!NewFD->isInvalidDecl())
  5358. Access = NewFD->getPreviousDecl()->getAccess();
  5359. NewFD->setAccess(Access);
  5360. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  5361. PrincipalDecl->setObjectOfFriendDecl(true);
  5362. }
  5363. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  5364. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  5365. PrincipalDecl->setNonMemberOperator();
  5366. // If we have a function template, check the template parameter
  5367. // list. This will check and merge default template arguments.
  5368. if (FunctionTemplate) {
  5369. FunctionTemplateDecl *PrevTemplate =
  5370. FunctionTemplate->getPreviousDecl();
  5371. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  5372. PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
  5373. D.getDeclSpec().isFriendSpecified()
  5374. ? (D.isFunctionDefinition()
  5375. ? TPC_FriendFunctionTemplateDefinition
  5376. : TPC_FriendFunctionTemplate)
  5377. : (D.getCXXScopeSpec().isSet() &&
  5378. DC && DC->isRecord() &&
  5379. DC->isDependentContext())
  5380. ? TPC_ClassTemplateMember
  5381. : TPC_FunctionTemplate);
  5382. }
  5383. if (NewFD->isInvalidDecl()) {
  5384. // Ignore all the rest of this.
  5385. } else if (!D.isRedeclaration()) {
  5386. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  5387. AddToScope };
  5388. // Fake up an access specifier if it's supposed to be a class member.
  5389. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  5390. NewFD->setAccess(AS_public);
  5391. // Qualified decls generally require a previous declaration.
  5392. if (D.getCXXScopeSpec().isSet()) {
  5393. // ...with the major exception of templated-scope or
  5394. // dependent-scope friend declarations.
  5395. // TODO: we currently also suppress this check in dependent
  5396. // contexts because (1) the parameter depth will be off when
  5397. // matching friend templates and (2) we might actually be
  5398. // selecting a friend based on a dependent factor. But there
  5399. // are situations where these conditions don't apply and we
  5400. // can actually do this check immediately.
  5401. if (isFriend &&
  5402. (TemplateParamLists.size() ||
  5403. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  5404. CurContext->isDependentContext())) {
  5405. // ignore these
  5406. } else {
  5407. // The user tried to provide an out-of-line definition for a
  5408. // function that is a member of a class or namespace, but there
  5409. // was no such member function declared (C++ [class.mfct]p2,
  5410. // C++ [namespace.memdef]p2). For example:
  5411. //
  5412. // class X {
  5413. // void f() const;
  5414. // };
  5415. //
  5416. // void X::f() { } // ill-formed
  5417. //
  5418. // Complain about this problem, and attempt to suggest close
  5419. // matches (e.g., those that differ only in cv-qualifiers and
  5420. // whether the parameter types are references).
  5421. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
  5422. NewFD,
  5423. ExtraArgs)) {
  5424. AddToScope = ExtraArgs.AddToScope;
  5425. return Result;
  5426. }
  5427. }
  5428. // Unqualified local friend declarations are required to resolve
  5429. // to something.
  5430. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  5431. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
  5432. NewFD,
  5433. ExtraArgs)) {
  5434. AddToScope = ExtraArgs.AddToScope;
  5435. return Result;
  5436. }
  5437. }
  5438. } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
  5439. !isFriend && !isFunctionTemplateSpecialization &&
  5440. !isExplicitSpecialization) {
  5441. // An out-of-line member function declaration must also be a
  5442. // definition (C++ [dcl.meaning]p1).
  5443. // Note that this is not the case for explicit specializations of
  5444. // function templates or member functions of class templates, per
  5445. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  5446. // extension for compatibility with old SWIG code which likes to
  5447. // generate them.
  5448. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  5449. << D.getCXXScopeSpec().getRange();
  5450. }
  5451. }
  5452. checkAttributesAfterMerging(*this, *NewFD);
  5453. AddKnownFunctionAttributes(NewFD);
  5454. if (NewFD->hasAttr<OverloadableAttr>() &&
  5455. !NewFD->getType()->getAs<FunctionProtoType>()) {
  5456. Diag(NewFD->getLocation(),
  5457. diag::err_attribute_overloadable_no_prototype)
  5458. << NewFD;
  5459. // Turn this into a variadic function with no parameters.
  5460. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  5461. FunctionProtoType::ExtProtoInfo EPI;
  5462. EPI.Variadic = true;
  5463. EPI.ExtInfo = FT->getExtInfo();
  5464. QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
  5465. NewFD->setType(R);
  5466. }
  5467. // If there's a #pragma GCC visibility in scope, and this isn't a class
  5468. // member, set the visibility of this function.
  5469. if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
  5470. AddPushedVisibilityAttribute(NewFD);
  5471. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  5472. // marking the function.
  5473. AddCFAuditedAttribute(NewFD);
  5474. // If this is a locally-scoped extern C function, update the
  5475. // map of such names.
  5476. if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
  5477. && !NewFD->isInvalidDecl())
  5478. RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
  5479. // Set this FunctionDecl's range up to the right paren.
  5480. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  5481. if (getLangOpts().CPlusPlus) {
  5482. if (FunctionTemplate) {
  5483. if (NewFD->isInvalidDecl())
  5484. FunctionTemplate->setInvalidDecl();
  5485. return FunctionTemplate;
  5486. }
  5487. }
  5488. if (NewFD->hasAttr<OpenCLKernelAttr>()) {
  5489. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  5490. if ((getLangOpts().OpenCLVersion >= 120)
  5491. && (SC == SC_Static)) {
  5492. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  5493. D.setInvalidType();
  5494. }
  5495. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  5496. if (!NewFD->getResultType()->isVoidType()) {
  5497. Diag(D.getIdentifierLoc(),
  5498. diag::err_expected_kernel_void_return_type);
  5499. D.setInvalidType();
  5500. }
  5501. for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
  5502. PE = NewFD->param_end(); PI != PE; ++PI) {
  5503. ParmVarDecl *Param = *PI;
  5504. QualType PT = Param->getType();
  5505. // OpenCL v1.2 s6.9.a:
  5506. // A kernel function argument cannot be declared as a
  5507. // pointer to a pointer type.
  5508. if (PT->isPointerType() && PT->getPointeeType()->isPointerType()) {
  5509. Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_arg);
  5510. D.setInvalidType();
  5511. }
  5512. // OpenCL v1.2 s6.8 n:
  5513. // A kernel function argument cannot be declared
  5514. // of event_t type.
  5515. if (PT->isEventT()) {
  5516. Diag(Param->getLocation(), diag::err_event_t_kernel_arg);
  5517. D.setInvalidType();
  5518. }
  5519. }
  5520. }
  5521. MarkUnusedFileScopedDecl(NewFD);
  5522. if (getLangOpts().CUDA)
  5523. if (IdentifierInfo *II = NewFD->getIdentifier())
  5524. if (!NewFD->isInvalidDecl() &&
  5525. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5526. if (II->isStr("cudaConfigureCall")) {
  5527. if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
  5528. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  5529. Context.setcudaConfigureCallDecl(NewFD);
  5530. }
  5531. }
  5532. // Here we have an function template explicit specialization at class scope.
  5533. // The actually specialization will be postponed to template instatiation
  5534. // time via the ClassScopeFunctionSpecializationDecl node.
  5535. if (isDependentClassScopeExplicitSpecialization) {
  5536. ClassScopeFunctionSpecializationDecl *NewSpec =
  5537. ClassScopeFunctionSpecializationDecl::Create(
  5538. Context, CurContext, SourceLocation(),
  5539. cast<CXXMethodDecl>(NewFD),
  5540. HasExplicitTemplateArgs, TemplateArgs);
  5541. CurContext->addDecl(NewSpec);
  5542. AddToScope = false;
  5543. }
  5544. return NewFD;
  5545. }
  5546. /// \brief Perform semantic checking of a new function declaration.
  5547. ///
  5548. /// Performs semantic analysis of the new function declaration
  5549. /// NewFD. This routine performs all semantic checking that does not
  5550. /// require the actual declarator involved in the declaration, and is
  5551. /// used both for the declaration of functions as they are parsed
  5552. /// (called via ActOnDeclarator) and for the declaration of functions
  5553. /// that have been instantiated via C++ template instantiation (called
  5554. /// via InstantiateDecl).
  5555. ///
  5556. /// \param IsExplicitSpecialization whether this new function declaration is
  5557. /// an explicit specialization of the previous declaration.
  5558. ///
  5559. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  5560. ///
  5561. /// \returns true if the function declaration is a redeclaration.
  5562. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  5563. LookupResult &Previous,
  5564. bool IsExplicitSpecialization) {
  5565. assert(!NewFD->getResultType()->isVariablyModifiedType()
  5566. && "Variably modified return types are not handled here");
  5567. // Check for a previous declaration of this name.
  5568. if (Previous.empty() && mayConflictWithNonVisibleExternC(NewFD)) {
  5569. // Since we did not find anything by this name, look for a non-visible
  5570. // extern "C" declaration with the same name.
  5571. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  5572. = findLocallyScopedExternCDecl(NewFD->getDeclName());
  5573. if (Pos != LocallyScopedExternCDecls.end())
  5574. Previous.addDecl(Pos->second);
  5575. }
  5576. // Filter out any non-conflicting previous declarations.
  5577. filterNonConflictingPreviousDecls(Context, NewFD, Previous);
  5578. bool Redeclaration = false;
  5579. NamedDecl *OldDecl = 0;
  5580. // Merge or overload the declaration with an existing declaration of
  5581. // the same name, if appropriate.
  5582. if (!Previous.empty()) {
  5583. // Determine whether NewFD is an overload of PrevDecl or
  5584. // a declaration that requires merging. If it's an overload,
  5585. // there's no more work to do here; we'll just add the new
  5586. // function to the scope.
  5587. if (!AllowOverloadingOfFunction(Previous, Context)) {
  5588. Redeclaration = true;
  5589. OldDecl = Previous.getFoundDecl();
  5590. } else {
  5591. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  5592. /*NewIsUsingDecl*/ false)) {
  5593. case Ovl_Match:
  5594. Redeclaration = true;
  5595. break;
  5596. case Ovl_NonFunction:
  5597. Redeclaration = true;
  5598. break;
  5599. case Ovl_Overload:
  5600. Redeclaration = false;
  5601. break;
  5602. }
  5603. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  5604. // If a function name is overloadable in C, then every function
  5605. // with that name must be marked "overloadable".
  5606. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  5607. << Redeclaration << NewFD;
  5608. NamedDecl *OverloadedDecl = 0;
  5609. if (Redeclaration)
  5610. OverloadedDecl = OldDecl;
  5611. else if (!Previous.empty())
  5612. OverloadedDecl = Previous.getRepresentativeDecl();
  5613. if (OverloadedDecl)
  5614. Diag(OverloadedDecl->getLocation(),
  5615. diag::note_attribute_overloadable_prev_overload);
  5616. NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
  5617. Context));
  5618. }
  5619. }
  5620. }
  5621. // C++11 [dcl.constexpr]p8:
  5622. // A constexpr specifier for a non-static member function that is not
  5623. // a constructor declares that member function to be const.
  5624. //
  5625. // This needs to be delayed until we know whether this is an out-of-line
  5626. // definition of a static member function.
  5627. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  5628. if (MD && MD->isConstexpr() && !MD->isStatic() &&
  5629. !isa<CXXConstructorDecl>(MD) &&
  5630. (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
  5631. CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
  5632. if (FunctionTemplateDecl *OldTD =
  5633. dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
  5634. OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
  5635. if (!OldMD || !OldMD->isStatic()) {
  5636. const FunctionProtoType *FPT =
  5637. MD->getType()->castAs<FunctionProtoType>();
  5638. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  5639. EPI.TypeQuals |= Qualifiers::Const;
  5640. MD->setType(Context.getFunctionType(FPT->getResultType(),
  5641. FPT->arg_type_begin(),
  5642. FPT->getNumArgs(), EPI));
  5643. }
  5644. }
  5645. if (Redeclaration) {
  5646. // NewFD and OldDecl represent declarations that need to be
  5647. // merged.
  5648. if (MergeFunctionDecl(NewFD, OldDecl, S)) {
  5649. NewFD->setInvalidDecl();
  5650. return Redeclaration;
  5651. }
  5652. Previous.clear();
  5653. Previous.addDecl(OldDecl);
  5654. if (FunctionTemplateDecl *OldTemplateDecl
  5655. = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  5656. NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
  5657. FunctionTemplateDecl *NewTemplateDecl
  5658. = NewFD->getDescribedFunctionTemplate();
  5659. assert(NewTemplateDecl && "Template/non-template mismatch");
  5660. if (CXXMethodDecl *Method
  5661. = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
  5662. Method->setAccess(OldTemplateDecl->getAccess());
  5663. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  5664. }
  5665. // If this is an explicit specialization of a member that is a function
  5666. // template, mark it as a member specialization.
  5667. if (IsExplicitSpecialization &&
  5668. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  5669. NewTemplateDecl->setMemberSpecialization();
  5670. assert(OldTemplateDecl->isMemberSpecialization());
  5671. }
  5672. } else {
  5673. // This needs to happen first so that 'inline' propagates.
  5674. NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
  5675. if (isa<CXXMethodDecl>(NewFD)) {
  5676. // A valid redeclaration of a C++ method must be out-of-line,
  5677. // but (unfortunately) it's not necessarily a definition
  5678. // because of templates, which means that the previous
  5679. // declaration is not necessarily from the class definition.
  5680. // For just setting the access, that doesn't matter.
  5681. CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
  5682. NewFD->setAccess(oldMethod->getAccess());
  5683. // Update the key-function state if necessary for this ABI.
  5684. if (NewFD->isInlined() &&
  5685. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  5686. // setNonKeyFunction needs to work with the original
  5687. // declaration from the class definition, and isVirtual() is
  5688. // just faster in that case, so map back to that now.
  5689. oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDeclaration());
  5690. if (oldMethod->isVirtual()) {
  5691. Context.setNonKeyFunction(oldMethod);
  5692. }
  5693. }
  5694. }
  5695. }
  5696. }
  5697. // Semantic checking for this function declaration (in isolation).
  5698. if (getLangOpts().CPlusPlus) {
  5699. // C++-specific checks.
  5700. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  5701. CheckConstructor(Constructor);
  5702. } else if (CXXDestructorDecl *Destructor =
  5703. dyn_cast<CXXDestructorDecl>(NewFD)) {
  5704. CXXRecordDecl *Record = Destructor->getParent();
  5705. QualType ClassType = Context.getTypeDeclType(Record);
  5706. // FIXME: Shouldn't we be able to perform this check even when the class
  5707. // type is dependent? Both gcc and edg can handle that.
  5708. if (!ClassType->isDependentType()) {
  5709. DeclarationName Name
  5710. = Context.DeclarationNames.getCXXDestructorName(
  5711. Context.getCanonicalType(ClassType));
  5712. if (NewFD->getDeclName() != Name) {
  5713. Diag(NewFD->getLocation(), diag::err_destructor_name);
  5714. NewFD->setInvalidDecl();
  5715. return Redeclaration;
  5716. }
  5717. }
  5718. } else if (CXXConversionDecl *Conversion
  5719. = dyn_cast<CXXConversionDecl>(NewFD)) {
  5720. ActOnConversionDeclarator(Conversion);
  5721. }
  5722. // Find any virtual functions that this function overrides.
  5723. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  5724. if (!Method->isFunctionTemplateSpecialization() &&
  5725. !Method->getDescribedFunctionTemplate() &&
  5726. Method->isCanonicalDecl()) {
  5727. if (AddOverriddenMethods(Method->getParent(), Method)) {
  5728. // If the function was marked as "static", we have a problem.
  5729. if (NewFD->getStorageClass() == SC_Static) {
  5730. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  5731. }
  5732. }
  5733. }
  5734. if (Method->isStatic())
  5735. checkThisInStaticMemberFunctionType(Method);
  5736. }
  5737. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  5738. if (NewFD->isOverloadedOperator() &&
  5739. CheckOverloadedOperatorDeclaration(NewFD)) {
  5740. NewFD->setInvalidDecl();
  5741. return Redeclaration;
  5742. }
  5743. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  5744. if (NewFD->getLiteralIdentifier() &&
  5745. CheckLiteralOperatorDeclaration(NewFD)) {
  5746. NewFD->setInvalidDecl();
  5747. return Redeclaration;
  5748. }
  5749. // In C++, check default arguments now that we have merged decls. Unless
  5750. // the lexical context is the class, because in this case this is done
  5751. // during delayed parsing anyway.
  5752. if (!CurContext->isRecord())
  5753. CheckCXXDefaultArguments(NewFD);
  5754. // If this function declares a builtin function, check the type of this
  5755. // declaration against the expected type for the builtin.
  5756. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  5757. ASTContext::GetBuiltinTypeError Error;
  5758. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  5759. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  5760. if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
  5761. // The type of this function differs from the type of the builtin,
  5762. // so forget about the builtin entirely.
  5763. Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
  5764. }
  5765. }
  5766. // If this function is declared as being extern "C", then check to see if
  5767. // the function returns a UDT (class, struct, or union type) that is not C
  5768. // compatible, and if it does, warn the user.
  5769. if (NewFD->hasCLanguageLinkage()) {
  5770. QualType R = NewFD->getResultType();
  5771. if (R->isIncompleteType() && !R->isVoidType())
  5772. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  5773. << NewFD << R;
  5774. else if (!R.isPODType(Context) && !R->isVoidType() &&
  5775. !R->isObjCObjectPointerType())
  5776. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  5777. }
  5778. }
  5779. return Redeclaration;
  5780. }
  5781. static SourceRange getResultSourceRange(const FunctionDecl *FD) {
  5782. const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
  5783. if (!TSI)
  5784. return SourceRange();
  5785. TypeLoc TL = TSI->getTypeLoc();
  5786. FunctionTypeLoc *FunctionTL = dyn_cast<FunctionTypeLoc>(&TL);
  5787. if (!FunctionTL)
  5788. return SourceRange();
  5789. TypeLoc ResultTL = FunctionTL->getResultLoc();
  5790. if (isa<BuiltinTypeLoc>(ResultTL.getUnqualifiedLoc()))
  5791. return ResultTL.getSourceRange();
  5792. return SourceRange();
  5793. }
  5794. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  5795. // C++11 [basic.start.main]p3: A program that declares main to be inline,
  5796. // static or constexpr is ill-formed.
  5797. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  5798. // appear in a declaration of main.
  5799. // static main is not an error under C99, but we should warn about it.
  5800. // We accept _Noreturn main as an extension.
  5801. if (FD->getStorageClass() == SC_Static)
  5802. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  5803. ? diag::err_static_main : diag::warn_static_main)
  5804. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  5805. if (FD->isInlineSpecified())
  5806. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  5807. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  5808. if (DS.isNoreturnSpecified()) {
  5809. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  5810. SourceRange NoreturnRange(NoreturnLoc,
  5811. PP.getLocForEndOfToken(NoreturnLoc));
  5812. Diag(NoreturnLoc, diag::ext_noreturn_main);
  5813. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  5814. << FixItHint::CreateRemoval(NoreturnRange);
  5815. }
  5816. if (FD->isConstexpr()) {
  5817. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  5818. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  5819. FD->setConstexpr(false);
  5820. }
  5821. QualType T = FD->getType();
  5822. assert(T->isFunctionType() && "function decl is not of function type");
  5823. const FunctionType* FT = T->castAs<FunctionType>();
  5824. // All the standards say that main() should should return 'int'.
  5825. if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
  5826. // In C and C++, main magically returns 0 if you fall off the end;
  5827. // set the flag which tells us that.
  5828. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  5829. FD->setHasImplicitReturnZero(true);
  5830. // In C with GNU extensions we allow main() to have non-integer return
  5831. // type, but we should warn about the extension, and we disable the
  5832. // implicit-return-zero rule.
  5833. } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  5834. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  5835. SourceRange ResultRange = getResultSourceRange(FD);
  5836. if (ResultRange.isValid())
  5837. Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
  5838. << FixItHint::CreateReplacement(ResultRange, "int");
  5839. // Otherwise, this is just a flat-out error.
  5840. } else {
  5841. SourceRange ResultRange = getResultSourceRange(FD);
  5842. if (ResultRange.isValid())
  5843. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  5844. << FixItHint::CreateReplacement(ResultRange, "int");
  5845. else
  5846. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
  5847. FD->setInvalidDecl(true);
  5848. }
  5849. // Treat protoless main() as nullary.
  5850. if (isa<FunctionNoProtoType>(FT)) return;
  5851. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  5852. unsigned nparams = FTP->getNumArgs();
  5853. assert(FD->getNumParams() == nparams);
  5854. bool HasExtraParameters = (nparams > 3);
  5855. // Darwin passes an undocumented fourth argument of type char**. If
  5856. // other platforms start sprouting these, the logic below will start
  5857. // getting shifty.
  5858. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  5859. HasExtraParameters = false;
  5860. if (HasExtraParameters) {
  5861. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  5862. FD->setInvalidDecl(true);
  5863. nparams = 3;
  5864. }
  5865. // FIXME: a lot of the following diagnostics would be improved
  5866. // if we had some location information about types.
  5867. QualType CharPP =
  5868. Context.getPointerType(Context.getPointerType(Context.CharTy));
  5869. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  5870. for (unsigned i = 0; i < nparams; ++i) {
  5871. QualType AT = FTP->getArgType(i);
  5872. bool mismatch = true;
  5873. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  5874. mismatch = false;
  5875. else if (Expected[i] == CharPP) {
  5876. // As an extension, the following forms are okay:
  5877. // char const **
  5878. // char const * const *
  5879. // char * const *
  5880. QualifierCollector qs;
  5881. const PointerType* PT;
  5882. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  5883. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  5884. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  5885. Context.CharTy)) {
  5886. qs.removeConst();
  5887. mismatch = !qs.empty();
  5888. }
  5889. }
  5890. if (mismatch) {
  5891. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  5892. // TODO: suggest replacing given type with expected type
  5893. FD->setInvalidDecl(true);
  5894. }
  5895. }
  5896. if (nparams == 1 && !FD->isInvalidDecl()) {
  5897. Diag(FD->getLocation(), diag::warn_main_one_arg);
  5898. }
  5899. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  5900. Diag(FD->getLocation(), diag::err_main_template_decl);
  5901. FD->setInvalidDecl();
  5902. }
  5903. }
  5904. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  5905. // FIXME: Need strict checking. In C89, we need to check for
  5906. // any assignment, increment, decrement, function-calls, or
  5907. // commas outside of a sizeof. In C99, it's the same list,
  5908. // except that the aforementioned are allowed in unevaluated
  5909. // expressions. Everything else falls under the
  5910. // "may accept other forms of constant expressions" exception.
  5911. // (We never end up here for C++, so the constant expression
  5912. // rules there don't matter.)
  5913. if (Init->isConstantInitializer(Context, false))
  5914. return false;
  5915. Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
  5916. << Init->getSourceRange();
  5917. return true;
  5918. }
  5919. namespace {
  5920. // Visits an initialization expression to see if OrigDecl is evaluated in
  5921. // its own initialization and throws a warning if it does.
  5922. class SelfReferenceChecker
  5923. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  5924. Sema &S;
  5925. Decl *OrigDecl;
  5926. bool isRecordType;
  5927. bool isPODType;
  5928. bool isReferenceType;
  5929. public:
  5930. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  5931. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  5932. S(S), OrigDecl(OrigDecl) {
  5933. isPODType = false;
  5934. isRecordType = false;
  5935. isReferenceType = false;
  5936. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  5937. isPODType = VD->getType().isPODType(S.Context);
  5938. isRecordType = VD->getType()->isRecordType();
  5939. isReferenceType = VD->getType()->isReferenceType();
  5940. }
  5941. }
  5942. // For most expressions, the cast is directly above the DeclRefExpr.
  5943. // For conditional operators, the cast can be outside the conditional
  5944. // operator if both expressions are DeclRefExpr's.
  5945. void HandleValue(Expr *E) {
  5946. if (isReferenceType)
  5947. return;
  5948. E = E->IgnoreParenImpCasts();
  5949. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  5950. HandleDeclRefExpr(DRE);
  5951. return;
  5952. }
  5953. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  5954. HandleValue(CO->getTrueExpr());
  5955. HandleValue(CO->getFalseExpr());
  5956. return;
  5957. }
  5958. if (isa<MemberExpr>(E)) {
  5959. Expr *Base = E->IgnoreParenImpCasts();
  5960. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  5961. // Check for static member variables and don't warn on them.
  5962. if (!isa<FieldDecl>(ME->getMemberDecl()))
  5963. return;
  5964. Base = ME->getBase()->IgnoreParenImpCasts();
  5965. }
  5966. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  5967. HandleDeclRefExpr(DRE);
  5968. return;
  5969. }
  5970. }
  5971. // Reference types are handled here since all uses of references are
  5972. // bad, not just r-value uses.
  5973. void VisitDeclRefExpr(DeclRefExpr *E) {
  5974. if (isReferenceType)
  5975. HandleDeclRefExpr(E);
  5976. }
  5977. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  5978. if (E->getCastKind() == CK_LValueToRValue ||
  5979. (isRecordType && E->getCastKind() == CK_NoOp))
  5980. HandleValue(E->getSubExpr());
  5981. Inherited::VisitImplicitCastExpr(E);
  5982. }
  5983. void VisitMemberExpr(MemberExpr *E) {
  5984. // Don't warn on arrays since they can be treated as pointers.
  5985. if (E->getType()->canDecayToPointerType()) return;
  5986. // Warn when a non-static method call is followed by non-static member
  5987. // field accesses, which is followed by a DeclRefExpr.
  5988. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  5989. bool Warn = (MD && !MD->isStatic());
  5990. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  5991. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  5992. if (!isa<FieldDecl>(ME->getMemberDecl()))
  5993. Warn = false;
  5994. Base = ME->getBase()->IgnoreParenImpCasts();
  5995. }
  5996. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  5997. if (Warn)
  5998. HandleDeclRefExpr(DRE);
  5999. return;
  6000. }
  6001. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  6002. // Visit that expression.
  6003. Visit(Base);
  6004. }
  6005. void VisitUnaryOperator(UnaryOperator *E) {
  6006. // For POD record types, addresses of its own members are well-defined.
  6007. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  6008. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  6009. if (!isPODType)
  6010. HandleValue(E->getSubExpr());
  6011. return;
  6012. }
  6013. Inherited::VisitUnaryOperator(E);
  6014. }
  6015. void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
  6016. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  6017. Decl* ReferenceDecl = DRE->getDecl();
  6018. if (OrigDecl != ReferenceDecl) return;
  6019. unsigned diag;
  6020. if (isReferenceType) {
  6021. diag = diag::warn_uninit_self_reference_in_reference_init;
  6022. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  6023. diag = diag::warn_static_self_reference_in_init;
  6024. } else {
  6025. diag = diag::warn_uninit_self_reference_in_init;
  6026. }
  6027. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  6028. S.PDiag(diag)
  6029. << DRE->getNameInfo().getName()
  6030. << OrigDecl->getLocation()
  6031. << DRE->getSourceRange());
  6032. }
  6033. };
  6034. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  6035. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  6036. bool DirectInit) {
  6037. // Parameters arguments are occassionially constructed with itself,
  6038. // for instance, in recursive functions. Skip them.
  6039. if (isa<ParmVarDecl>(OrigDecl))
  6040. return;
  6041. E = E->IgnoreParens();
  6042. // Skip checking T a = a where T is not a record or reference type.
  6043. // Doing so is a way to silence uninitialized warnings.
  6044. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  6045. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  6046. if (ICE->getCastKind() == CK_LValueToRValue)
  6047. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  6048. if (DRE->getDecl() == OrigDecl)
  6049. return;
  6050. SelfReferenceChecker(S, OrigDecl).Visit(E);
  6051. }
  6052. }
  6053. /// AddInitializerToDecl - Adds the initializer Init to the
  6054. /// declaration dcl. If DirectInit is true, this is C++ direct
  6055. /// initialization rather than copy initialization.
  6056. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
  6057. bool DirectInit, bool TypeMayContainAuto) {
  6058. // If there is no declaration, there was an error parsing it. Just ignore
  6059. // the initializer.
  6060. if (RealDecl == 0 || RealDecl->isInvalidDecl())
  6061. return;
  6062. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  6063. // With declarators parsed the way they are, the parser cannot
  6064. // distinguish between a normal initializer and a pure-specifier.
  6065. // Thus this grotesque test.
  6066. IntegerLiteral *IL;
  6067. if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
  6068. Context.getCanonicalType(IL->getType()) == Context.IntTy)
  6069. CheckPureMethod(Method, Init->getSourceRange());
  6070. else {
  6071. Diag(Method->getLocation(), diag::err_member_function_initialization)
  6072. << Method->getDeclName() << Init->getSourceRange();
  6073. Method->setInvalidDecl();
  6074. }
  6075. return;
  6076. }
  6077. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  6078. if (!VDecl) {
  6079. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  6080. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  6081. RealDecl->setInvalidDecl();
  6082. return;
  6083. }
  6084. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  6085. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  6086. AutoType *Auto = 0;
  6087. if (TypeMayContainAuto &&
  6088. (Auto = VDecl->getType()->getContainedAutoType()) &&
  6089. !Auto->isDeduced()) {
  6090. Expr *DeduceInit = Init;
  6091. // Initializer could be a C++ direct-initializer. Deduction only works if it
  6092. // contains exactly one expression.
  6093. if (CXXDirectInit) {
  6094. if (CXXDirectInit->getNumExprs() == 0) {
  6095. // It isn't possible to write this directly, but it is possible to
  6096. // end up in this situation with "auto x(some_pack...);"
  6097. Diag(CXXDirectInit->getLocStart(),
  6098. diag::err_auto_var_init_no_expression)
  6099. << VDecl->getDeclName() << VDecl->getType()
  6100. << VDecl->getSourceRange();
  6101. RealDecl->setInvalidDecl();
  6102. return;
  6103. } else if (CXXDirectInit->getNumExprs() > 1) {
  6104. Diag(CXXDirectInit->getExpr(1)->getLocStart(),
  6105. diag::err_auto_var_init_multiple_expressions)
  6106. << VDecl->getDeclName() << VDecl->getType()
  6107. << VDecl->getSourceRange();
  6108. RealDecl->setInvalidDecl();
  6109. return;
  6110. } else {
  6111. DeduceInit = CXXDirectInit->getExpr(0);
  6112. }
  6113. }
  6114. TypeSourceInfo *DeducedType = 0;
  6115. if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
  6116. DAR_Failed)
  6117. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  6118. if (!DeducedType) {
  6119. RealDecl->setInvalidDecl();
  6120. return;
  6121. }
  6122. VDecl->setTypeSourceInfo(DeducedType);
  6123. VDecl->setType(DeducedType->getType());
  6124. VDecl->ClearLinkageCache();
  6125. // In ARC, infer lifetime.
  6126. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  6127. VDecl->setInvalidDecl();
  6128. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  6129. // 'id' instead of a specific object type prevents most of our usual checks.
  6130. // We only want to warn outside of template instantiations, though:
  6131. // inside a template, the 'id' could have come from a parameter.
  6132. if (ActiveTemplateInstantiations.empty() &&
  6133. DeducedType->getType()->isObjCIdType()) {
  6134. SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc();
  6135. Diag(Loc, diag::warn_auto_var_is_id)
  6136. << VDecl->getDeclName() << DeduceInit->getSourceRange();
  6137. }
  6138. // If this is a redeclaration, check that the type we just deduced matches
  6139. // the previously declared type.
  6140. if (VarDecl *Old = VDecl->getPreviousDecl())
  6141. MergeVarDeclTypes(VDecl, Old);
  6142. }
  6143. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  6144. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  6145. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  6146. VDecl->setInvalidDecl();
  6147. return;
  6148. }
  6149. if (!VDecl->getType()->isDependentType()) {
  6150. // A definition must end up with a complete type, which means it must be
  6151. // complete with the restriction that an array type might be completed by
  6152. // the initializer; note that later code assumes this restriction.
  6153. QualType BaseDeclType = VDecl->getType();
  6154. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  6155. BaseDeclType = Array->getElementType();
  6156. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  6157. diag::err_typecheck_decl_incomplete_type)) {
  6158. RealDecl->setInvalidDecl();
  6159. return;
  6160. }
  6161. // The variable can not have an abstract class type.
  6162. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  6163. diag::err_abstract_type_in_decl,
  6164. AbstractVariableType))
  6165. VDecl->setInvalidDecl();
  6166. }
  6167. const VarDecl *Def;
  6168. if ((Def = VDecl->getDefinition()) && Def != VDecl) {
  6169. Diag(VDecl->getLocation(), diag::err_redefinition)
  6170. << VDecl->getDeclName();
  6171. Diag(Def->getLocation(), diag::note_previous_definition);
  6172. VDecl->setInvalidDecl();
  6173. return;
  6174. }
  6175. const VarDecl* PrevInit = 0;
  6176. if (getLangOpts().CPlusPlus) {
  6177. // C++ [class.static.data]p4
  6178. // If a static data member is of const integral or const
  6179. // enumeration type, its declaration in the class definition can
  6180. // specify a constant-initializer which shall be an integral
  6181. // constant expression (5.19). In that case, the member can appear
  6182. // in integral constant expressions. The member shall still be
  6183. // defined in a namespace scope if it is used in the program and the
  6184. // namespace scope definition shall not contain an initializer.
  6185. //
  6186. // We already performed a redefinition check above, but for static
  6187. // data members we also need to check whether there was an in-class
  6188. // declaration with an initializer.
  6189. if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
  6190. Diag(VDecl->getLocation(), diag::err_redefinition)
  6191. << VDecl->getDeclName();
  6192. Diag(PrevInit->getLocation(), diag::note_previous_definition);
  6193. return;
  6194. }
  6195. if (VDecl->hasLocalStorage())
  6196. getCurFunction()->setHasBranchProtectedScope();
  6197. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  6198. VDecl->setInvalidDecl();
  6199. return;
  6200. }
  6201. }
  6202. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  6203. // a kernel function cannot be initialized."
  6204. if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
  6205. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  6206. VDecl->setInvalidDecl();
  6207. return;
  6208. }
  6209. // Get the decls type and save a reference for later, since
  6210. // CheckInitializerTypes may change it.
  6211. QualType DclT = VDecl->getType(), SavT = DclT;
  6212. // Top-level message sends default to 'id' when we're in a debugger
  6213. // and we are assigning it to a variable of 'id' type.
  6214. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
  6215. if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
  6216. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  6217. if (Result.isInvalid()) {
  6218. VDecl->setInvalidDecl();
  6219. return;
  6220. }
  6221. Init = Result.take();
  6222. }
  6223. // Perform the initialization.
  6224. if (!VDecl->isInvalidDecl()) {
  6225. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  6226. InitializationKind Kind
  6227. = DirectInit ?
  6228. CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
  6229. Init->getLocStart(),
  6230. Init->getLocEnd())
  6231. : InitializationKind::CreateDirectList(
  6232. VDecl->getLocation())
  6233. : InitializationKind::CreateCopy(VDecl->getLocation(),
  6234. Init->getLocStart());
  6235. Expr **Args = &Init;
  6236. unsigned NumArgs = 1;
  6237. if (CXXDirectInit) {
  6238. Args = CXXDirectInit->getExprs();
  6239. NumArgs = CXXDirectInit->getNumExprs();
  6240. }
  6241. InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
  6242. ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
  6243. MultiExprArg(Args, NumArgs), &DclT);
  6244. if (Result.isInvalid()) {
  6245. VDecl->setInvalidDecl();
  6246. return;
  6247. }
  6248. Init = Result.takeAs<Expr>();
  6249. }
  6250. // Check for self-references within variable initializers.
  6251. // Variables declared within a function/method body (except for references)
  6252. // are handled by a dataflow analysis.
  6253. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  6254. VDecl->getType()->isReferenceType()) {
  6255. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  6256. }
  6257. // If the type changed, it means we had an incomplete type that was
  6258. // completed by the initializer. For example:
  6259. // int ary[] = { 1, 3, 5 };
  6260. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  6261. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  6262. VDecl->setType(DclT);
  6263. if (!VDecl->isInvalidDecl()) {
  6264. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  6265. if (VDecl->hasAttr<BlocksAttr>())
  6266. checkRetainCycles(VDecl, Init);
  6267. // It is safe to assign a weak reference into a strong variable.
  6268. // Although this code can still have problems:
  6269. // id x = self.weakProp;
  6270. // id y = self.weakProp;
  6271. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  6272. // paths through the function. This should be revisited if
  6273. // -Wrepeated-use-of-weak is made flow-sensitive.
  6274. if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
  6275. DiagnosticsEngine::Level Level =
  6276. Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
  6277. Init->getLocStart());
  6278. if (Level != DiagnosticsEngine::Ignored)
  6279. getCurFunction()->markSafeWeakUse(Init);
  6280. }
  6281. }
  6282. // The initialization is usually a full-expression.
  6283. //
  6284. // FIXME: If this is a braced initialization of an aggregate, it is not
  6285. // an expression, and each individual field initializer is a separate
  6286. // full-expression. For instance, in:
  6287. //
  6288. // struct Temp { ~Temp(); };
  6289. // struct S { S(Temp); };
  6290. // struct T { S a, b; } t = { Temp(), Temp() }
  6291. //
  6292. // we should destroy the first Temp before constructing the second.
  6293. ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
  6294. false,
  6295. VDecl->isConstexpr());
  6296. if (Result.isInvalid()) {
  6297. VDecl->setInvalidDecl();
  6298. return;
  6299. }
  6300. Init = Result.take();
  6301. // Attach the initializer to the decl.
  6302. VDecl->setInit(Init);
  6303. if (VDecl->isLocalVarDecl()) {
  6304. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  6305. // static storage duration shall be constant expressions or string literals.
  6306. // C++ does not have this restriction.
  6307. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
  6308. VDecl->getStorageClass() == SC_Static)
  6309. CheckForConstantInitializer(Init, DclT);
  6310. } else if (VDecl->isStaticDataMember() &&
  6311. VDecl->getLexicalDeclContext()->isRecord()) {
  6312. // This is an in-class initialization for a static data member, e.g.,
  6313. //
  6314. // struct S {
  6315. // static const int value = 17;
  6316. // };
  6317. // C++ [class.mem]p4:
  6318. // A member-declarator can contain a constant-initializer only
  6319. // if it declares a static member (9.4) of const integral or
  6320. // const enumeration type, see 9.4.2.
  6321. //
  6322. // C++11 [class.static.data]p3:
  6323. // If a non-volatile const static data member is of integral or
  6324. // enumeration type, its declaration in the class definition can
  6325. // specify a brace-or-equal-initializer in which every initalizer-clause
  6326. // that is an assignment-expression is a constant expression. A static
  6327. // data member of literal type can be declared in the class definition
  6328. // with the constexpr specifier; if so, its declaration shall specify a
  6329. // brace-or-equal-initializer in which every initializer-clause that is
  6330. // an assignment-expression is a constant expression.
  6331. // Do nothing on dependent types.
  6332. if (DclT->isDependentType()) {
  6333. // Allow any 'static constexpr' members, whether or not they are of literal
  6334. // type. We separately check that every constexpr variable is of literal
  6335. // type.
  6336. } else if (VDecl->isConstexpr()) {
  6337. // Require constness.
  6338. } else if (!DclT.isConstQualified()) {
  6339. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  6340. << Init->getSourceRange();
  6341. VDecl->setInvalidDecl();
  6342. // We allow integer constant expressions in all cases.
  6343. } else if (DclT->isIntegralOrEnumerationType()) {
  6344. // Check whether the expression is a constant expression.
  6345. SourceLocation Loc;
  6346. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  6347. // In C++11, a non-constexpr const static data member with an
  6348. // in-class initializer cannot be volatile.
  6349. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  6350. else if (Init->isValueDependent())
  6351. ; // Nothing to check.
  6352. else if (Init->isIntegerConstantExpr(Context, &Loc))
  6353. ; // Ok, it's an ICE!
  6354. else if (Init->isEvaluatable(Context)) {
  6355. // If we can constant fold the initializer through heroics, accept it,
  6356. // but report this as a use of an extension for -pedantic.
  6357. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  6358. << Init->getSourceRange();
  6359. } else {
  6360. // Otherwise, this is some crazy unknown case. Report the issue at the
  6361. // location provided by the isIntegerConstantExpr failed check.
  6362. Diag(Loc, diag::err_in_class_initializer_non_constant)
  6363. << Init->getSourceRange();
  6364. VDecl->setInvalidDecl();
  6365. }
  6366. // We allow foldable floating-point constants as an extension.
  6367. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  6368. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  6369. // it anyway and provide a fixit to add the 'constexpr'.
  6370. if (getLangOpts().CPlusPlus11) {
  6371. Diag(VDecl->getLocation(),
  6372. diag::ext_in_class_initializer_float_type_cxx11)
  6373. << DclT << Init->getSourceRange();
  6374. Diag(VDecl->getLocStart(),
  6375. diag::note_in_class_initializer_float_type_cxx11)
  6376. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  6377. } else {
  6378. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  6379. << DclT << Init->getSourceRange();
  6380. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  6381. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  6382. << Init->getSourceRange();
  6383. VDecl->setInvalidDecl();
  6384. }
  6385. }
  6386. // Suggest adding 'constexpr' in C++11 for literal types.
  6387. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType()) {
  6388. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  6389. << DclT << Init->getSourceRange()
  6390. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  6391. VDecl->setConstexpr(true);
  6392. } else {
  6393. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  6394. << DclT << Init->getSourceRange();
  6395. VDecl->setInvalidDecl();
  6396. }
  6397. } else if (VDecl->isFileVarDecl()) {
  6398. if (VDecl->getStorageClassAsWritten() == SC_Extern &&
  6399. (!getLangOpts().CPlusPlus ||
  6400. !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
  6401. Diag(VDecl->getLocation(), diag::warn_extern_init);
  6402. // C99 6.7.8p4. All file scoped initializers need to be constant.
  6403. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  6404. CheckForConstantInitializer(Init, DclT);
  6405. }
  6406. // We will represent direct-initialization similarly to copy-initialization:
  6407. // int x(1); -as-> int x = 1;
  6408. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  6409. //
  6410. // Clients that want to distinguish between the two forms, can check for
  6411. // direct initializer using VarDecl::getInitStyle().
  6412. // A major benefit is that clients that don't particularly care about which
  6413. // exactly form was it (like the CodeGen) can handle both cases without
  6414. // special case code.
  6415. // C++ 8.5p11:
  6416. // The form of initialization (using parentheses or '=') is generally
  6417. // insignificant, but does matter when the entity being initialized has a
  6418. // class type.
  6419. if (CXXDirectInit) {
  6420. assert(DirectInit && "Call-style initializer must be direct init.");
  6421. VDecl->setInitStyle(VarDecl::CallInit);
  6422. } else if (DirectInit) {
  6423. // This must be list-initialization. No other way is direct-initialization.
  6424. VDecl->setInitStyle(VarDecl::ListInit);
  6425. }
  6426. CheckCompleteVariableDeclaration(VDecl);
  6427. }
  6428. /// ActOnInitializerError - Given that there was an error parsing an
  6429. /// initializer for the given declaration, try to return to some form
  6430. /// of sanity.
  6431. void Sema::ActOnInitializerError(Decl *D) {
  6432. // Our main concern here is re-establishing invariants like "a
  6433. // variable's type is either dependent or complete".
  6434. if (!D || D->isInvalidDecl()) return;
  6435. VarDecl *VD = dyn_cast<VarDecl>(D);
  6436. if (!VD) return;
  6437. // Auto types are meaningless if we can't make sense of the initializer.
  6438. if (ParsingInitForAutoVars.count(D)) {
  6439. D->setInvalidDecl();
  6440. return;
  6441. }
  6442. QualType Ty = VD->getType();
  6443. if (Ty->isDependentType()) return;
  6444. // Require a complete type.
  6445. if (RequireCompleteType(VD->getLocation(),
  6446. Context.getBaseElementType(Ty),
  6447. diag::err_typecheck_decl_incomplete_type)) {
  6448. VD->setInvalidDecl();
  6449. return;
  6450. }
  6451. // Require an abstract type.
  6452. if (RequireNonAbstractType(VD->getLocation(), Ty,
  6453. diag::err_abstract_type_in_decl,
  6454. AbstractVariableType)) {
  6455. VD->setInvalidDecl();
  6456. return;
  6457. }
  6458. // Don't bother complaining about constructors or destructors,
  6459. // though.
  6460. }
  6461. void Sema::ActOnUninitializedDecl(Decl *RealDecl,
  6462. bool TypeMayContainAuto) {
  6463. // If there is no declaration, there was an error parsing it. Just ignore it.
  6464. if (RealDecl == 0)
  6465. return;
  6466. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  6467. QualType Type = Var->getType();
  6468. // C++11 [dcl.spec.auto]p3
  6469. if (TypeMayContainAuto && Type->getContainedAutoType()) {
  6470. Diag(Var->getLocation(), diag::err_auto_var_requires_init)
  6471. << Var->getDeclName() << Type;
  6472. Var->setInvalidDecl();
  6473. return;
  6474. }
  6475. // C++11 [class.static.data]p3: A static data member can be declared with
  6476. // the constexpr specifier; if so, its declaration shall specify
  6477. // a brace-or-equal-initializer.
  6478. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  6479. // the definition of a variable [...] or the declaration of a static data
  6480. // member.
  6481. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
  6482. if (Var->isStaticDataMember())
  6483. Diag(Var->getLocation(),
  6484. diag::err_constexpr_static_mem_var_requires_init)
  6485. << Var->getDeclName();
  6486. else
  6487. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  6488. Var->setInvalidDecl();
  6489. return;
  6490. }
  6491. switch (Var->isThisDeclarationADefinition()) {
  6492. case VarDecl::Definition:
  6493. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  6494. break;
  6495. // We have an out-of-line definition of a static data member
  6496. // that has an in-class initializer, so we type-check this like
  6497. // a declaration.
  6498. //
  6499. // Fall through
  6500. case VarDecl::DeclarationOnly:
  6501. // It's only a declaration.
  6502. // Block scope. C99 6.7p7: If an identifier for an object is
  6503. // declared with no linkage (C99 6.2.2p6), the type for the
  6504. // object shall be complete.
  6505. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  6506. !Var->getLinkage() && !Var->isInvalidDecl() &&
  6507. RequireCompleteType(Var->getLocation(), Type,
  6508. diag::err_typecheck_decl_incomplete_type))
  6509. Var->setInvalidDecl();
  6510. // Make sure that the type is not abstract.
  6511. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  6512. RequireNonAbstractType(Var->getLocation(), Type,
  6513. diag::err_abstract_type_in_decl,
  6514. AbstractVariableType))
  6515. Var->setInvalidDecl();
  6516. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  6517. Var->getStorageClass() == SC_PrivateExtern) {
  6518. Diag(Var->getLocation(), diag::warn_private_extern);
  6519. Diag(Var->getLocation(), diag::note_private_extern);
  6520. }
  6521. return;
  6522. case VarDecl::TentativeDefinition:
  6523. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  6524. // object that has file scope without an initializer, and without a
  6525. // storage-class specifier or with the storage-class specifier "static",
  6526. // constitutes a tentative definition. Note: A tentative definition with
  6527. // external linkage is valid (C99 6.2.2p5).
  6528. if (!Var->isInvalidDecl()) {
  6529. if (const IncompleteArrayType *ArrayT
  6530. = Context.getAsIncompleteArrayType(Type)) {
  6531. if (RequireCompleteType(Var->getLocation(),
  6532. ArrayT->getElementType(),
  6533. diag::err_illegal_decl_array_incomplete_type))
  6534. Var->setInvalidDecl();
  6535. } else if (Var->getStorageClass() == SC_Static) {
  6536. // C99 6.9.2p3: If the declaration of an identifier for an object is
  6537. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  6538. // declared type shall not be an incomplete type.
  6539. // NOTE: code such as the following
  6540. // static struct s;
  6541. // struct s { int a; };
  6542. // is accepted by gcc. Hence here we issue a warning instead of
  6543. // an error and we do not invalidate the static declaration.
  6544. // NOTE: to avoid multiple warnings, only check the first declaration.
  6545. if (Var->getPreviousDecl() == 0)
  6546. RequireCompleteType(Var->getLocation(), Type,
  6547. diag::ext_typecheck_decl_incomplete_type);
  6548. }
  6549. }
  6550. // Record the tentative definition; we're done.
  6551. if (!Var->isInvalidDecl())
  6552. TentativeDefinitions.push_back(Var);
  6553. return;
  6554. }
  6555. // Provide a specific diagnostic for uninitialized variable
  6556. // definitions with incomplete array type.
  6557. if (Type->isIncompleteArrayType()) {
  6558. Diag(Var->getLocation(),
  6559. diag::err_typecheck_incomplete_array_needs_initializer);
  6560. Var->setInvalidDecl();
  6561. return;
  6562. }
  6563. // Provide a specific diagnostic for uninitialized variable
  6564. // definitions with reference type.
  6565. if (Type->isReferenceType()) {
  6566. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  6567. << Var->getDeclName()
  6568. << SourceRange(Var->getLocation(), Var->getLocation());
  6569. Var->setInvalidDecl();
  6570. return;
  6571. }
  6572. // Do not attempt to type-check the default initializer for a
  6573. // variable with dependent type.
  6574. if (Type->isDependentType())
  6575. return;
  6576. if (Var->isInvalidDecl())
  6577. return;
  6578. if (RequireCompleteType(Var->getLocation(),
  6579. Context.getBaseElementType(Type),
  6580. diag::err_typecheck_decl_incomplete_type)) {
  6581. Var->setInvalidDecl();
  6582. return;
  6583. }
  6584. // The variable can not have an abstract class type.
  6585. if (RequireNonAbstractType(Var->getLocation(), Type,
  6586. diag::err_abstract_type_in_decl,
  6587. AbstractVariableType)) {
  6588. Var->setInvalidDecl();
  6589. return;
  6590. }
  6591. // Check for jumps past the implicit initializer. C++0x
  6592. // clarifies that this applies to a "variable with automatic
  6593. // storage duration", not a "local variable".
  6594. // C++11 [stmt.dcl]p3
  6595. // A program that jumps from a point where a variable with automatic
  6596. // storage duration is not in scope to a point where it is in scope is
  6597. // ill-formed unless the variable has scalar type, class type with a
  6598. // trivial default constructor and a trivial destructor, a cv-qualified
  6599. // version of one of these types, or an array of one of the preceding
  6600. // types and is declared without an initializer.
  6601. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  6602. if (const RecordType *Record
  6603. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  6604. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  6605. // Mark the function for further checking even if the looser rules of
  6606. // C++11 do not require such checks, so that we can diagnose
  6607. // incompatibilities with C++98.
  6608. if (!CXXRecord->isPOD())
  6609. getCurFunction()->setHasBranchProtectedScope();
  6610. }
  6611. }
  6612. // C++03 [dcl.init]p9:
  6613. // If no initializer is specified for an object, and the
  6614. // object is of (possibly cv-qualified) non-POD class type (or
  6615. // array thereof), the object shall be default-initialized; if
  6616. // the object is of const-qualified type, the underlying class
  6617. // type shall have a user-declared default
  6618. // constructor. Otherwise, if no initializer is specified for
  6619. // a non- static object, the object and its subobjects, if
  6620. // any, have an indeterminate initial value); if the object
  6621. // or any of its subobjects are of const-qualified type, the
  6622. // program is ill-formed.
  6623. // C++0x [dcl.init]p11:
  6624. // If no initializer is specified for an object, the object is
  6625. // default-initialized; [...].
  6626. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  6627. InitializationKind Kind
  6628. = InitializationKind::CreateDefault(Var->getLocation());
  6629. InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
  6630. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, MultiExprArg());
  6631. if (Init.isInvalid())
  6632. Var->setInvalidDecl();
  6633. else if (Init.get()) {
  6634. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  6635. // This is important for template substitution.
  6636. Var->setInitStyle(VarDecl::CallInit);
  6637. }
  6638. CheckCompleteVariableDeclaration(Var);
  6639. }
  6640. }
  6641. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  6642. VarDecl *VD = dyn_cast<VarDecl>(D);
  6643. if (!VD) {
  6644. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  6645. D->setInvalidDecl();
  6646. return;
  6647. }
  6648. VD->setCXXForRangeDecl(true);
  6649. // for-range-declaration cannot be given a storage class specifier.
  6650. int Error = -1;
  6651. switch (VD->getStorageClassAsWritten()) {
  6652. case SC_None:
  6653. break;
  6654. case SC_Extern:
  6655. Error = 0;
  6656. break;
  6657. case SC_Static:
  6658. Error = 1;
  6659. break;
  6660. case SC_PrivateExtern:
  6661. Error = 2;
  6662. break;
  6663. case SC_Auto:
  6664. Error = 3;
  6665. break;
  6666. case SC_Register:
  6667. Error = 4;
  6668. break;
  6669. case SC_OpenCLWorkGroupLocal:
  6670. llvm_unreachable("Unexpected storage class");
  6671. }
  6672. if (VD->isConstexpr())
  6673. Error = 5;
  6674. if (Error != -1) {
  6675. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  6676. << VD->getDeclName() << Error;
  6677. D->setInvalidDecl();
  6678. }
  6679. }
  6680. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  6681. if (var->isInvalidDecl()) return;
  6682. // In ARC, don't allow jumps past the implicit initialization of a
  6683. // local retaining variable.
  6684. if (getLangOpts().ObjCAutoRefCount &&
  6685. var->hasLocalStorage()) {
  6686. switch (var->getType().getObjCLifetime()) {
  6687. case Qualifiers::OCL_None:
  6688. case Qualifiers::OCL_ExplicitNone:
  6689. case Qualifiers::OCL_Autoreleasing:
  6690. break;
  6691. case Qualifiers::OCL_Weak:
  6692. case Qualifiers::OCL_Strong:
  6693. getCurFunction()->setHasBranchProtectedScope();
  6694. break;
  6695. }
  6696. }
  6697. if (var->isThisDeclarationADefinition() &&
  6698. var->getLinkage() == ExternalLinkage &&
  6699. getDiagnostics().getDiagnosticLevel(
  6700. diag::warn_missing_variable_declarations,
  6701. var->getLocation())) {
  6702. // Find a previous declaration that's not a definition.
  6703. VarDecl *prev = var->getPreviousDecl();
  6704. while (prev && prev->isThisDeclarationADefinition())
  6705. prev = prev->getPreviousDecl();
  6706. if (!prev)
  6707. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  6708. }
  6709. // All the following checks are C++ only.
  6710. if (!getLangOpts().CPlusPlus) return;
  6711. QualType type = var->getType();
  6712. if (type->isDependentType()) return;
  6713. // __block variables might require us to capture a copy-initializer.
  6714. if (var->hasAttr<BlocksAttr>()) {
  6715. // It's currently invalid to ever have a __block variable with an
  6716. // array type; should we diagnose that here?
  6717. // Regardless, we don't want to ignore array nesting when
  6718. // constructing this copy.
  6719. if (type->isStructureOrClassType()) {
  6720. SourceLocation poi = var->getLocation();
  6721. Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
  6722. ExprResult result =
  6723. PerformCopyInitialization(
  6724. InitializedEntity::InitializeBlock(poi, type, false),
  6725. poi, Owned(varRef));
  6726. if (!result.isInvalid()) {
  6727. result = MaybeCreateExprWithCleanups(result);
  6728. Expr *init = result.takeAs<Expr>();
  6729. Context.setBlockVarCopyInits(var, init);
  6730. }
  6731. }
  6732. }
  6733. Expr *Init = var->getInit();
  6734. bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
  6735. QualType baseType = Context.getBaseElementType(type);
  6736. if (!var->getDeclContext()->isDependentContext() &&
  6737. Init && !Init->isValueDependent()) {
  6738. if (IsGlobal && !var->isConstexpr() &&
  6739. getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
  6740. var->getLocation())
  6741. != DiagnosticsEngine::Ignored &&
  6742. !Init->isConstantInitializer(Context, baseType->isReferenceType()))
  6743. Diag(var->getLocation(), diag::warn_global_constructor)
  6744. << Init->getSourceRange();
  6745. if (var->isConstexpr()) {
  6746. SmallVector<PartialDiagnosticAt, 8> Notes;
  6747. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  6748. SourceLocation DiagLoc = var->getLocation();
  6749. // If the note doesn't add any useful information other than a source
  6750. // location, fold it into the primary diagnostic.
  6751. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  6752. diag::note_invalid_subexpr_in_const_expr) {
  6753. DiagLoc = Notes[0].first;
  6754. Notes.clear();
  6755. }
  6756. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  6757. << var << Init->getSourceRange();
  6758. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  6759. Diag(Notes[I].first, Notes[I].second);
  6760. }
  6761. } else if (var->isUsableInConstantExpressions(Context)) {
  6762. // Check whether the initializer of a const variable of integral or
  6763. // enumeration type is an ICE now, since we can't tell whether it was
  6764. // initialized by a constant expression if we check later.
  6765. var->checkInitIsICE();
  6766. }
  6767. }
  6768. // Require the destructor.
  6769. if (const RecordType *recordType = baseType->getAs<RecordType>())
  6770. FinalizeVarWithDestructor(var, recordType);
  6771. }
  6772. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  6773. /// any semantic actions necessary after any initializer has been attached.
  6774. void
  6775. Sema::FinalizeDeclaration(Decl *ThisDecl) {
  6776. // Note that we are no longer parsing the initializer for this declaration.
  6777. ParsingInitForAutoVars.erase(ThisDecl);
  6778. const VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  6779. if (!VD)
  6780. return;
  6781. if (VD->isFileVarDecl())
  6782. MarkUnusedFileScopedDecl(VD);
  6783. // Now we have parsed the initializer and can update the table of magic
  6784. // tag values.
  6785. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  6786. !VD->getType()->isIntegralOrEnumerationType())
  6787. return;
  6788. for (specific_attr_iterator<TypeTagForDatatypeAttr>
  6789. I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
  6790. E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
  6791. I != E; ++I) {
  6792. const Expr *MagicValueExpr = VD->getInit();
  6793. if (!MagicValueExpr) {
  6794. continue;
  6795. }
  6796. llvm::APSInt MagicValueInt;
  6797. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  6798. Diag(I->getRange().getBegin(),
  6799. diag::err_type_tag_for_datatype_not_ice)
  6800. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  6801. continue;
  6802. }
  6803. if (MagicValueInt.getActiveBits() > 64) {
  6804. Diag(I->getRange().getBegin(),
  6805. diag::err_type_tag_for_datatype_too_large)
  6806. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  6807. continue;
  6808. }
  6809. uint64_t MagicValue = MagicValueInt.getZExtValue();
  6810. RegisterTypeTagForDatatype(I->getArgumentKind(),
  6811. MagicValue,
  6812. I->getMatchingCType(),
  6813. I->getLayoutCompatible(),
  6814. I->getMustBeNull());
  6815. }
  6816. }
  6817. Sema::DeclGroupPtrTy
  6818. Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  6819. Decl **Group, unsigned NumDecls) {
  6820. SmallVector<Decl*, 8> Decls;
  6821. if (DS.isTypeSpecOwned())
  6822. Decls.push_back(DS.getRepAsDecl());
  6823. for (unsigned i = 0; i != NumDecls; ++i)
  6824. if (Decl *D = Group[i])
  6825. Decls.push_back(D);
  6826. if (DeclSpec::isDeclRep(DS.getTypeSpecType()))
  6827. if (const TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl()))
  6828. getASTContext().addUnnamedTag(Tag);
  6829. return BuildDeclaratorGroup(Decls.data(), Decls.size(),
  6830. DS.getTypeSpecType() == DeclSpec::TST_auto);
  6831. }
  6832. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  6833. /// group, performing any necessary semantic checking.
  6834. Sema::DeclGroupPtrTy
  6835. Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
  6836. bool TypeMayContainAuto) {
  6837. // C++0x [dcl.spec.auto]p7:
  6838. // If the type deduced for the template parameter U is not the same in each
  6839. // deduction, the program is ill-formed.
  6840. // FIXME: When initializer-list support is added, a distinction is needed
  6841. // between the deduced type U and the deduced type which 'auto' stands for.
  6842. // auto a = 0, b = { 1, 2, 3 };
  6843. // is legal because the deduced type U is 'int' in both cases.
  6844. if (TypeMayContainAuto && NumDecls > 1) {
  6845. QualType Deduced;
  6846. CanQualType DeducedCanon;
  6847. VarDecl *DeducedDecl = 0;
  6848. for (unsigned i = 0; i != NumDecls; ++i) {
  6849. if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
  6850. AutoType *AT = D->getType()->getContainedAutoType();
  6851. // Don't reissue diagnostics when instantiating a template.
  6852. if (AT && D->isInvalidDecl())
  6853. break;
  6854. if (AT && AT->isDeduced()) {
  6855. QualType U = AT->getDeducedType();
  6856. CanQualType UCanon = Context.getCanonicalType(U);
  6857. if (Deduced.isNull()) {
  6858. Deduced = U;
  6859. DeducedCanon = UCanon;
  6860. DeducedDecl = D;
  6861. } else if (DeducedCanon != UCanon) {
  6862. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  6863. diag::err_auto_different_deductions)
  6864. << Deduced << DeducedDecl->getDeclName()
  6865. << U << D->getDeclName()
  6866. << DeducedDecl->getInit()->getSourceRange()
  6867. << D->getInit()->getSourceRange();
  6868. D->setInvalidDecl();
  6869. break;
  6870. }
  6871. }
  6872. }
  6873. }
  6874. }
  6875. ActOnDocumentableDecls(Group, NumDecls);
  6876. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
  6877. }
  6878. void Sema::ActOnDocumentableDecl(Decl *D) {
  6879. ActOnDocumentableDecls(&D, 1);
  6880. }
  6881. void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) {
  6882. // Don't parse the comment if Doxygen diagnostics are ignored.
  6883. if (NumDecls == 0 || !Group[0])
  6884. return;
  6885. if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
  6886. Group[0]->getLocation())
  6887. == DiagnosticsEngine::Ignored)
  6888. return;
  6889. if (NumDecls >= 2) {
  6890. // This is a decl group. Normally it will contain only declarations
  6891. // procuded from declarator list. But in case we have any definitions or
  6892. // additional declaration references:
  6893. // 'typedef struct S {} S;'
  6894. // 'typedef struct S *S;'
  6895. // 'struct S *pS;'
  6896. // FinalizeDeclaratorGroup adds these as separate declarations.
  6897. Decl *MaybeTagDecl = Group[0];
  6898. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  6899. Group++;
  6900. NumDecls--;
  6901. }
  6902. }
  6903. // See if there are any new comments that are not attached to a decl.
  6904. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  6905. if (!Comments.empty() &&
  6906. !Comments.back()->isAttached()) {
  6907. // There is at least one comment that not attached to a decl.
  6908. // Maybe it should be attached to one of these decls?
  6909. //
  6910. // Note that this way we pick up not only comments that precede the
  6911. // declaration, but also comments that *follow* the declaration -- thanks to
  6912. // the lookahead in the lexer: we've consumed the semicolon and looked
  6913. // ahead through comments.
  6914. for (unsigned i = 0; i != NumDecls; ++i)
  6915. Context.getCommentForDecl(Group[i], &PP);
  6916. }
  6917. }
  6918. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  6919. /// to introduce parameters into function prototype scope.
  6920. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  6921. const DeclSpec &DS = D.getDeclSpec();
  6922. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  6923. // C++03 [dcl.stc]p2 also permits 'auto'.
  6924. VarDecl::StorageClass StorageClass = SC_None;
  6925. VarDecl::StorageClass StorageClassAsWritten = SC_None;
  6926. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  6927. StorageClass = SC_Register;
  6928. StorageClassAsWritten = SC_Register;
  6929. } else if (getLangOpts().CPlusPlus &&
  6930. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  6931. StorageClass = SC_Auto;
  6932. StorageClassAsWritten = SC_Auto;
  6933. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  6934. Diag(DS.getStorageClassSpecLoc(),
  6935. diag::err_invalid_storage_class_in_func_decl);
  6936. D.getMutableDeclSpec().ClearStorageClassSpecs();
  6937. }
  6938. if (D.getDeclSpec().isThreadSpecified())
  6939. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  6940. if (D.getDeclSpec().isConstexprSpecified())
  6941. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  6942. << 0;
  6943. DiagnoseFunctionSpecifiers(D);
  6944. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  6945. QualType parmDeclType = TInfo->getType();
  6946. if (getLangOpts().CPlusPlus) {
  6947. // Check that there are no default arguments inside the type of this
  6948. // parameter.
  6949. CheckExtraCXXDefaultArguments(D);
  6950. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  6951. if (D.getCXXScopeSpec().isSet()) {
  6952. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  6953. << D.getCXXScopeSpec().getRange();
  6954. D.getCXXScopeSpec().clear();
  6955. }
  6956. }
  6957. // Ensure we have a valid name
  6958. IdentifierInfo *II = 0;
  6959. if (D.hasName()) {
  6960. II = D.getIdentifier();
  6961. if (!II) {
  6962. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  6963. << GetNameForDeclarator(D).getName().getAsString();
  6964. D.setInvalidType(true);
  6965. }
  6966. }
  6967. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  6968. if (II) {
  6969. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  6970. ForRedeclaration);
  6971. LookupName(R, S);
  6972. if (R.isSingleResult()) {
  6973. NamedDecl *PrevDecl = R.getFoundDecl();
  6974. if (PrevDecl->isTemplateParameter()) {
  6975. // Maybe we will complain about the shadowed template parameter.
  6976. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  6977. // Just pretend that we didn't see the previous declaration.
  6978. PrevDecl = 0;
  6979. } else if (S->isDeclScope(PrevDecl)) {
  6980. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  6981. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  6982. // Recover by removing the name
  6983. II = 0;
  6984. D.SetIdentifier(0, D.getIdentifierLoc());
  6985. D.setInvalidType(true);
  6986. }
  6987. }
  6988. }
  6989. // Temporarily put parameter variables in the translation unit, not
  6990. // the enclosing context. This prevents them from accidentally
  6991. // looking like class members in C++.
  6992. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  6993. D.getLocStart(),
  6994. D.getIdentifierLoc(), II,
  6995. parmDeclType, TInfo,
  6996. StorageClass, StorageClassAsWritten);
  6997. if (D.isInvalidType())
  6998. New->setInvalidDecl();
  6999. assert(S->isFunctionPrototypeScope());
  7000. assert(S->getFunctionPrototypeDepth() >= 1);
  7001. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  7002. S->getNextFunctionPrototypeIndex());
  7003. // Add the parameter declaration into this scope.
  7004. S->AddDecl(New);
  7005. if (II)
  7006. IdResolver.AddDecl(New);
  7007. ProcessDeclAttributes(S, New, D);
  7008. if (D.getDeclSpec().isModulePrivateSpecified())
  7009. Diag(New->getLocation(), diag::err_module_private_local)
  7010. << 1 << New->getDeclName()
  7011. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  7012. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  7013. if (New->hasAttr<BlocksAttr>()) {
  7014. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  7015. }
  7016. return New;
  7017. }
  7018. /// \brief Synthesizes a variable for a parameter arising from a
  7019. /// typedef.
  7020. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  7021. SourceLocation Loc,
  7022. QualType T) {
  7023. /* FIXME: setting StartLoc == Loc.
  7024. Would it be worth to modify callers so as to provide proper source
  7025. location for the unnamed parameters, embedding the parameter's type? */
  7026. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
  7027. T, Context.getTrivialTypeSourceInfo(T, Loc),
  7028. SC_None, SC_None, 0);
  7029. Param->setImplicit();
  7030. return Param;
  7031. }
  7032. void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
  7033. ParmVarDecl * const *ParamEnd) {
  7034. // Don't diagnose unused-parameter errors in template instantiations; we
  7035. // will already have done so in the template itself.
  7036. if (!ActiveTemplateInstantiations.empty())
  7037. return;
  7038. for (; Param != ParamEnd; ++Param) {
  7039. if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
  7040. !(*Param)->hasAttr<UnusedAttr>()) {
  7041. Diag((*Param)->getLocation(), diag::warn_unused_parameter)
  7042. << (*Param)->getDeclName();
  7043. }
  7044. }
  7045. }
  7046. void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
  7047. ParmVarDecl * const *ParamEnd,
  7048. QualType ReturnTy,
  7049. NamedDecl *D) {
  7050. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  7051. return;
  7052. // Warn if the return value is pass-by-value and larger than the specified
  7053. // threshold.
  7054. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  7055. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  7056. if (Size > LangOpts.NumLargeByValueCopy)
  7057. Diag(D->getLocation(), diag::warn_return_value_size)
  7058. << D->getDeclName() << Size;
  7059. }
  7060. // Warn if any parameter is pass-by-value and larger than the specified
  7061. // threshold.
  7062. for (; Param != ParamEnd; ++Param) {
  7063. QualType T = (*Param)->getType();
  7064. if (T->isDependentType() || !T.isPODType(Context))
  7065. continue;
  7066. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  7067. if (Size > LangOpts.NumLargeByValueCopy)
  7068. Diag((*Param)->getLocation(), diag::warn_parameter_size)
  7069. << (*Param)->getDeclName() << Size;
  7070. }
  7071. }
  7072. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  7073. SourceLocation NameLoc, IdentifierInfo *Name,
  7074. QualType T, TypeSourceInfo *TSInfo,
  7075. VarDecl::StorageClass StorageClass,
  7076. VarDecl::StorageClass StorageClassAsWritten) {
  7077. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  7078. if (getLangOpts().ObjCAutoRefCount &&
  7079. T.getObjCLifetime() == Qualifiers::OCL_None &&
  7080. T->isObjCLifetimeType()) {
  7081. Qualifiers::ObjCLifetime lifetime;
  7082. // Special cases for arrays:
  7083. // - if it's const, use __unsafe_unretained
  7084. // - otherwise, it's an error
  7085. if (T->isArrayType()) {
  7086. if (!T.isConstQualified()) {
  7087. DelayedDiagnostics.add(
  7088. sema::DelayedDiagnostic::makeForbiddenType(
  7089. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  7090. }
  7091. lifetime = Qualifiers::OCL_ExplicitNone;
  7092. } else {
  7093. lifetime = T->getObjCARCImplicitLifetime();
  7094. }
  7095. T = Context.getLifetimeQualifiedType(T, lifetime);
  7096. }
  7097. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  7098. Context.getAdjustedParameterType(T),
  7099. TSInfo,
  7100. StorageClass, StorageClassAsWritten,
  7101. 0);
  7102. // Parameters can not be abstract class types.
  7103. // For record types, this is done by the AbstractClassUsageDiagnoser once
  7104. // the class has been completely parsed.
  7105. if (!CurContext->isRecord() &&
  7106. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  7107. AbstractParamType))
  7108. New->setInvalidDecl();
  7109. // Parameter declarators cannot be interface types. All ObjC objects are
  7110. // passed by reference.
  7111. if (T->isObjCObjectType()) {
  7112. SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
  7113. Diag(NameLoc,
  7114. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  7115. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  7116. T = Context.getObjCObjectPointerType(T);
  7117. New->setType(T);
  7118. }
  7119. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  7120. // duration shall not be qualified by an address-space qualifier."
  7121. // Since all parameters have automatic store duration, they can not have
  7122. // an address space.
  7123. if (T.getAddressSpace() != 0) {
  7124. Diag(NameLoc, diag::err_arg_with_address_space);
  7125. New->setInvalidDecl();
  7126. }
  7127. return New;
  7128. }
  7129. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  7130. SourceLocation LocAfterDecls) {
  7131. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  7132. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  7133. // for a K&R function.
  7134. if (!FTI.hasPrototype) {
  7135. for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
  7136. --i;
  7137. if (FTI.ArgInfo[i].Param == 0) {
  7138. SmallString<256> Code;
  7139. llvm::raw_svector_ostream(Code) << " int "
  7140. << FTI.ArgInfo[i].Ident->getName()
  7141. << ";\n";
  7142. Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
  7143. << FTI.ArgInfo[i].Ident
  7144. << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
  7145. // Implicitly declare the argument as type 'int' for lack of a better
  7146. // type.
  7147. AttributeFactory attrs;
  7148. DeclSpec DS(attrs);
  7149. const char* PrevSpec; // unused
  7150. unsigned DiagID; // unused
  7151. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
  7152. PrevSpec, DiagID);
  7153. // Use the identifier location for the type source range.
  7154. DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
  7155. DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
  7156. Declarator ParamD(DS, Declarator::KNRTypeListContext);
  7157. ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
  7158. FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
  7159. }
  7160. }
  7161. }
  7162. }
  7163. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
  7164. assert(getCurFunctionDecl() == 0 && "Function parsing confused");
  7165. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  7166. Scope *ParentScope = FnBodyScope->getParent();
  7167. D.setFunctionDefinitionKind(FDK_Definition);
  7168. Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
  7169. return ActOnStartOfFunctionDef(FnBodyScope, DP);
  7170. }
  7171. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  7172. const FunctionDecl*& PossibleZeroParamPrototype) {
  7173. // Don't warn about invalid declarations.
  7174. if (FD->isInvalidDecl())
  7175. return false;
  7176. // Or declarations that aren't global.
  7177. if (!FD->isGlobal())
  7178. return false;
  7179. // Don't warn about C++ member functions.
  7180. if (isa<CXXMethodDecl>(FD))
  7181. return false;
  7182. // Don't warn about 'main'.
  7183. if (FD->isMain())
  7184. return false;
  7185. // Don't warn about inline functions.
  7186. if (FD->isInlined())
  7187. return false;
  7188. // Don't warn about function templates.
  7189. if (FD->getDescribedFunctionTemplate())
  7190. return false;
  7191. // Don't warn about function template specializations.
  7192. if (FD->isFunctionTemplateSpecialization())
  7193. return false;
  7194. // Don't warn for OpenCL kernels.
  7195. if (FD->hasAttr<OpenCLKernelAttr>())
  7196. return false;
  7197. bool MissingPrototype = true;
  7198. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  7199. Prev; Prev = Prev->getPreviousDecl()) {
  7200. // Ignore any declarations that occur in function or method
  7201. // scope, because they aren't visible from the header.
  7202. if (Prev->getDeclContext()->isFunctionOrMethod())
  7203. continue;
  7204. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  7205. if (FD->getNumParams() == 0)
  7206. PossibleZeroParamPrototype = Prev;
  7207. break;
  7208. }
  7209. return MissingPrototype;
  7210. }
  7211. void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
  7212. // Don't complain if we're in GNU89 mode and the previous definition
  7213. // was an extern inline function.
  7214. const FunctionDecl *Definition;
  7215. if (FD->isDefined(Definition) &&
  7216. !canRedefineFunction(Definition, getLangOpts())) {
  7217. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  7218. Definition->getStorageClass() == SC_Extern)
  7219. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  7220. << FD->getDeclName() << getLangOpts().CPlusPlus;
  7221. else
  7222. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  7223. Diag(Definition->getLocation(), diag::note_previous_definition);
  7224. FD->setInvalidDecl();
  7225. }
  7226. }
  7227. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
  7228. // Clear the last template instantiation error context.
  7229. LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
  7230. if (!D)
  7231. return D;
  7232. FunctionDecl *FD = 0;
  7233. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  7234. FD = FunTmpl->getTemplatedDecl();
  7235. else
  7236. FD = cast<FunctionDecl>(D);
  7237. // Enter a new function scope
  7238. PushFunctionScope();
  7239. // See if this is a redefinition.
  7240. if (!FD->isLateTemplateParsed())
  7241. CheckForFunctionRedefinition(FD);
  7242. // Builtin functions cannot be defined.
  7243. if (unsigned BuiltinID = FD->getBuiltinID()) {
  7244. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  7245. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  7246. FD->setInvalidDecl();
  7247. }
  7248. }
  7249. // The return type of a function definition must be complete
  7250. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  7251. QualType ResultType = FD->getResultType();
  7252. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  7253. !FD->isInvalidDecl() &&
  7254. RequireCompleteType(FD->getLocation(), ResultType,
  7255. diag::err_func_def_incomplete_result))
  7256. FD->setInvalidDecl();
  7257. // GNU warning -Wmissing-prototypes:
  7258. // Warn if a global function is defined without a previous
  7259. // prototype declaration. This warning is issued even if the
  7260. // definition itself provides a prototype. The aim is to detect
  7261. // global functions that fail to be declared in header files.
  7262. const FunctionDecl *PossibleZeroParamPrototype = 0;
  7263. if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
  7264. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  7265. if (PossibleZeroParamPrototype) {
  7266. // We found a declaration that is not a prototype,
  7267. // but that could be a zero-parameter prototype
  7268. TypeSourceInfo* TI = PossibleZeroParamPrototype->getTypeSourceInfo();
  7269. TypeLoc TL = TI->getTypeLoc();
  7270. if (FunctionNoProtoTypeLoc* FTL = dyn_cast<FunctionNoProtoTypeLoc>(&TL))
  7271. Diag(PossibleZeroParamPrototype->getLocation(),
  7272. diag::note_declaration_not_a_prototype)
  7273. << PossibleZeroParamPrototype
  7274. << FixItHint::CreateInsertion(FTL->getRParenLoc(), "void");
  7275. }
  7276. }
  7277. if (FnBodyScope)
  7278. PushDeclContext(FnBodyScope, FD);
  7279. // Check the validity of our function parameters
  7280. CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
  7281. /*CheckParameterNames=*/true);
  7282. // Introduce our parameters into the function scope
  7283. for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
  7284. ParmVarDecl *Param = FD->getParamDecl(p);
  7285. Param->setOwningFunction(FD);
  7286. // If this has an identifier, add it to the scope stack.
  7287. if (Param->getIdentifier() && FnBodyScope) {
  7288. CheckShadow(FnBodyScope, Param);
  7289. PushOnScopeChains(Param, FnBodyScope);
  7290. }
  7291. }
  7292. // If we had any tags defined in the function prototype,
  7293. // introduce them into the function scope.
  7294. if (FnBodyScope) {
  7295. for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
  7296. E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
  7297. NamedDecl *D = *I;
  7298. // Some of these decls (like enums) may have been pinned to the translation unit
  7299. // for lack of a real context earlier. If so, remove from the translation unit
  7300. // and reattach to the current context.
  7301. if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
  7302. // Is the decl actually in the context?
  7303. for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
  7304. DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
  7305. if (*DI == D) {
  7306. Context.getTranslationUnitDecl()->removeDecl(D);
  7307. break;
  7308. }
  7309. }
  7310. // Either way, reassign the lexical decl context to our FunctionDecl.
  7311. D->setLexicalDeclContext(CurContext);
  7312. }
  7313. // If the decl has a non-null name, make accessible in the current scope.
  7314. if (!D->getName().empty())
  7315. PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
  7316. // Similarly, dive into enums and fish their constants out, making them
  7317. // accessible in this scope.
  7318. if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
  7319. for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
  7320. EE = ED->enumerator_end(); EI != EE; ++EI)
  7321. PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
  7322. }
  7323. }
  7324. }
  7325. // Ensure that the function's exception specification is instantiated.
  7326. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  7327. ResolveExceptionSpec(D->getLocation(), FPT);
  7328. // Checking attributes of current function definition
  7329. // dllimport attribute.
  7330. DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
  7331. if (DA && (!FD->getAttr<DLLExportAttr>())) {
  7332. // dllimport attribute cannot be directly applied to definition.
  7333. // Microsoft accepts dllimport for functions defined within class scope.
  7334. if (!DA->isInherited() &&
  7335. !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
  7336. Diag(FD->getLocation(),
  7337. diag::err_attribute_can_be_applied_only_to_symbol_declaration)
  7338. << "dllimport";
  7339. FD->setInvalidDecl();
  7340. return D;
  7341. }
  7342. // Visual C++ appears to not think this is an issue, so only issue
  7343. // a warning when Microsoft extensions are disabled.
  7344. if (!LangOpts.MicrosoftExt) {
  7345. // If a symbol previously declared dllimport is later defined, the
  7346. // attribute is ignored in subsequent references, and a warning is
  7347. // emitted.
  7348. Diag(FD->getLocation(),
  7349. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  7350. << FD->getName() << "dllimport";
  7351. }
  7352. }
  7353. // We want to attach documentation to original Decl (which might be
  7354. // a function template).
  7355. ActOnDocumentableDecl(D);
  7356. return D;
  7357. }
  7358. /// \brief Given the set of return statements within a function body,
  7359. /// compute the variables that are subject to the named return value
  7360. /// optimization.
  7361. ///
  7362. /// Each of the variables that is subject to the named return value
  7363. /// optimization will be marked as NRVO variables in the AST, and any
  7364. /// return statement that has a marked NRVO variable as its NRVO candidate can
  7365. /// use the named return value optimization.
  7366. ///
  7367. /// This function applies a very simplistic algorithm for NRVO: if every return
  7368. /// statement in the function has the same NRVO candidate, that candidate is
  7369. /// the NRVO variable.
  7370. ///
  7371. /// FIXME: Employ a smarter algorithm that accounts for multiple return
  7372. /// statements and the lifetimes of the NRVO candidates. We should be able to
  7373. /// find a maximal set of NRVO variables.
  7374. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  7375. ReturnStmt **Returns = Scope->Returns.data();
  7376. const VarDecl *NRVOCandidate = 0;
  7377. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  7378. if (!Returns[I]->getNRVOCandidate())
  7379. return;
  7380. if (!NRVOCandidate)
  7381. NRVOCandidate = Returns[I]->getNRVOCandidate();
  7382. else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
  7383. return;
  7384. }
  7385. if (NRVOCandidate)
  7386. const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
  7387. }
  7388. bool Sema::canSkipFunctionBody(Decl *D) {
  7389. if (!Consumer.shouldSkipFunctionBody(D))
  7390. return false;
  7391. if (isa<ObjCMethodDecl>(D))
  7392. return true;
  7393. FunctionDecl *FD = 0;
  7394. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
  7395. FD = FTD->getTemplatedDecl();
  7396. else
  7397. FD = cast<FunctionDecl>(D);
  7398. // We cannot skip the body of a function (or function template) which is
  7399. // constexpr, since we may need to evaluate its body in order to parse the
  7400. // rest of the file.
  7401. return !FD->isConstexpr();
  7402. }
  7403. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  7404. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
  7405. FD->setHasSkippedBody();
  7406. else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
  7407. MD->setHasSkippedBody();
  7408. return ActOnFinishFunctionBody(Decl, 0);
  7409. }
  7410. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  7411. return ActOnFinishFunctionBody(D, BodyArg, false);
  7412. }
  7413. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  7414. bool IsInstantiation) {
  7415. FunctionDecl *FD = 0;
  7416. FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
  7417. if (FunTmpl)
  7418. FD = FunTmpl->getTemplatedDecl();
  7419. else
  7420. FD = dyn_cast_or_null<FunctionDecl>(dcl);
  7421. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  7422. sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
  7423. if (FD) {
  7424. FD->setBody(Body);
  7425. // The only way to be included in UndefinedButUsed is if there is an
  7426. // ODR use before the definition. Avoid the expensive map lookup if this
  7427. // is the first declaration.
  7428. if (FD->getPreviousDecl() != 0 && FD->getPreviousDecl()->isUsed()) {
  7429. if (FD->getLinkage() != ExternalLinkage)
  7430. UndefinedButUsed.erase(FD);
  7431. else if (FD->isInlined() &&
  7432. (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
  7433. (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
  7434. UndefinedButUsed.erase(FD);
  7435. }
  7436. // If the function implicitly returns zero (like 'main') or is naked,
  7437. // don't complain about missing return statements.
  7438. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  7439. WP.disableCheckFallThrough();
  7440. // MSVC permits the use of pure specifier (=0) on function definition,
  7441. // defined at class scope, warn about this non standard construct.
  7442. if (getLangOpts().MicrosoftExt && FD->isPure())
  7443. Diag(FD->getLocation(), diag::warn_pure_function_definition);
  7444. if (!FD->isInvalidDecl()) {
  7445. DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
  7446. DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
  7447. FD->getResultType(), FD);
  7448. // If this is a constructor, we need a vtable.
  7449. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  7450. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  7451. // Try to apply the named return value optimization. We have to check
  7452. // if we can do this here because lambdas keep return statements around
  7453. // to deduce an implicit return type.
  7454. if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
  7455. !FD->isDependentContext())
  7456. computeNRVO(Body, getCurFunction());
  7457. }
  7458. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  7459. "Function parsing confused");
  7460. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  7461. assert(MD == getCurMethodDecl() && "Method parsing confused");
  7462. MD->setBody(Body);
  7463. if (!MD->isInvalidDecl()) {
  7464. DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
  7465. DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
  7466. MD->getResultType(), MD);
  7467. if (Body)
  7468. computeNRVO(Body, getCurFunction());
  7469. }
  7470. if (getCurFunction()->ObjCShouldCallSuper) {
  7471. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
  7472. << MD->getSelector().getAsString();
  7473. getCurFunction()->ObjCShouldCallSuper = false;
  7474. }
  7475. } else {
  7476. return 0;
  7477. }
  7478. assert(!getCurFunction()->ObjCShouldCallSuper &&
  7479. "This should only be set for ObjC methods, which should have been "
  7480. "handled in the block above.");
  7481. // Verify and clean out per-function state.
  7482. if (Body) {
  7483. // C++ constructors that have function-try-blocks can't have return
  7484. // statements in the handlers of that block. (C++ [except.handle]p14)
  7485. // Verify this.
  7486. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  7487. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  7488. // Verify that gotos and switch cases don't jump into scopes illegally.
  7489. if (getCurFunction()->NeedsScopeChecking() &&
  7490. !dcl->isInvalidDecl() &&
  7491. !hasAnyUnrecoverableErrorsInThisFunction() &&
  7492. !PP.isCodeCompletionEnabled())
  7493. DiagnoseInvalidJumps(Body);
  7494. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  7495. if (!Destructor->getParent()->isDependentType())
  7496. CheckDestructor(Destructor);
  7497. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  7498. Destructor->getParent());
  7499. }
  7500. // If any errors have occurred, clear out any temporaries that may have
  7501. // been leftover. This ensures that these temporaries won't be picked up for
  7502. // deletion in some later function.
  7503. if (PP.getDiagnostics().hasErrorOccurred() ||
  7504. PP.getDiagnostics().getSuppressAllDiagnostics()) {
  7505. DiscardCleanupsInEvaluationContext();
  7506. }
  7507. if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
  7508. !isa<FunctionTemplateDecl>(dcl)) {
  7509. // Since the body is valid, issue any analysis-based warnings that are
  7510. // enabled.
  7511. ActivePolicy = &WP;
  7512. }
  7513. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  7514. (!CheckConstexprFunctionDecl(FD) ||
  7515. !CheckConstexprFunctionBody(FD, Body)))
  7516. FD->setInvalidDecl();
  7517. assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
  7518. assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
  7519. assert(MaybeODRUseExprs.empty() &&
  7520. "Leftover expressions for odr-use checking");
  7521. }
  7522. if (!IsInstantiation)
  7523. PopDeclContext();
  7524. PopFunctionScopeInfo(ActivePolicy, dcl);
  7525. // If any errors have occurred, clear out any temporaries that may have
  7526. // been leftover. This ensures that these temporaries won't be picked up for
  7527. // deletion in some later function.
  7528. if (getDiagnostics().hasErrorOccurred()) {
  7529. DiscardCleanupsInEvaluationContext();
  7530. }
  7531. return dcl;
  7532. }
  7533. /// When we finish delayed parsing of an attribute, we must attach it to the
  7534. /// relevant Decl.
  7535. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  7536. ParsedAttributes &Attrs) {
  7537. // Always attach attributes to the underlying decl.
  7538. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  7539. D = TD->getTemplatedDecl();
  7540. ProcessDeclAttributeList(S, D, Attrs.getList());
  7541. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  7542. if (Method->isStatic())
  7543. checkThisInStaticMemberFunctionAttributes(Method);
  7544. }
  7545. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  7546. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  7547. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  7548. IdentifierInfo &II, Scope *S) {
  7549. // Before we produce a declaration for an implicitly defined
  7550. // function, see whether there was a locally-scoped declaration of
  7551. // this name as a function or variable. If so, use that
  7552. // (non-visible) declaration, and complain about it.
  7553. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  7554. = findLocallyScopedExternCDecl(&II);
  7555. if (Pos != LocallyScopedExternCDecls.end()) {
  7556. Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
  7557. Diag(Pos->second->getLocation(), diag::note_previous_declaration);
  7558. return Pos->second;
  7559. }
  7560. // Extension in C99. Legal in C90, but warn about it.
  7561. unsigned diag_id;
  7562. if (II.getName().startswith("__builtin_"))
  7563. diag_id = diag::warn_builtin_unknown;
  7564. else if (getLangOpts().C99)
  7565. diag_id = diag::ext_implicit_function_decl;
  7566. else
  7567. diag_id = diag::warn_implicit_function_decl;
  7568. Diag(Loc, diag_id) << &II;
  7569. // Because typo correction is expensive, only do it if the implicit
  7570. // function declaration is going to be treated as an error.
  7571. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  7572. TypoCorrection Corrected;
  7573. DeclFilterCCC<FunctionDecl> Validator;
  7574. if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
  7575. LookupOrdinaryName, S, 0, Validator))) {
  7576. std::string CorrectedStr = Corrected.getAsString(getLangOpts());
  7577. std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
  7578. FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
  7579. Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
  7580. << FixItHint::CreateReplacement(Loc, CorrectedStr);
  7581. if (Func->getLocation().isValid()
  7582. && !II.getName().startswith("__builtin_"))
  7583. Diag(Func->getLocation(), diag::note_previous_decl)
  7584. << CorrectedQuotedStr;
  7585. }
  7586. }
  7587. // Set a Declarator for the implicit definition: int foo();
  7588. const char *Dummy;
  7589. AttributeFactory attrFactory;
  7590. DeclSpec DS(attrFactory);
  7591. unsigned DiagID;
  7592. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
  7593. (void)Error; // Silence warning.
  7594. assert(!Error && "Error setting up implicit decl!");
  7595. SourceLocation NoLoc;
  7596. Declarator D(DS, Declarator::BlockContext);
  7597. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  7598. /*IsAmbiguous=*/false,
  7599. /*RParenLoc=*/NoLoc,
  7600. /*ArgInfo=*/0,
  7601. /*NumArgs=*/0,
  7602. /*EllipsisLoc=*/NoLoc,
  7603. /*RParenLoc=*/NoLoc,
  7604. /*TypeQuals=*/0,
  7605. /*RefQualifierIsLvalueRef=*/true,
  7606. /*RefQualifierLoc=*/NoLoc,
  7607. /*ConstQualifierLoc=*/NoLoc,
  7608. /*VolatileQualifierLoc=*/NoLoc,
  7609. /*MutableLoc=*/NoLoc,
  7610. EST_None,
  7611. /*ESpecLoc=*/NoLoc,
  7612. /*Exceptions=*/0,
  7613. /*ExceptionRanges=*/0,
  7614. /*NumExceptions=*/0,
  7615. /*NoexceptExpr=*/0,
  7616. Loc, Loc, D),
  7617. DS.getAttributes(),
  7618. SourceLocation());
  7619. D.SetIdentifier(&II, Loc);
  7620. // Insert this function into translation-unit scope.
  7621. DeclContext *PrevDC = CurContext;
  7622. CurContext = Context.getTranslationUnitDecl();
  7623. FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
  7624. FD->setImplicit();
  7625. CurContext = PrevDC;
  7626. AddKnownFunctionAttributes(FD);
  7627. return FD;
  7628. }
  7629. /// \brief Adds any function attributes that we know a priori based on
  7630. /// the declaration of this function.
  7631. ///
  7632. /// These attributes can apply both to implicitly-declared builtins
  7633. /// (like __builtin___printf_chk) or to library-declared functions
  7634. /// like NSLog or printf.
  7635. ///
  7636. /// We need to check for duplicate attributes both here and where user-written
  7637. /// attributes are applied to declarations.
  7638. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  7639. if (FD->isInvalidDecl())
  7640. return;
  7641. // If this is a built-in function, map its builtin attributes to
  7642. // actual attributes.
  7643. if (unsigned BuiltinID = FD->getBuiltinID()) {
  7644. // Handle printf-formatting attributes.
  7645. unsigned FormatIdx;
  7646. bool HasVAListArg;
  7647. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  7648. if (!FD->getAttr<FormatAttr>()) {
  7649. const char *fmt = "printf";
  7650. unsigned int NumParams = FD->getNumParams();
  7651. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  7652. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  7653. fmt = "NSString";
  7654. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  7655. fmt, FormatIdx+1,
  7656. HasVAListArg ? 0 : FormatIdx+2));
  7657. }
  7658. }
  7659. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  7660. HasVAListArg)) {
  7661. if (!FD->getAttr<FormatAttr>())
  7662. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  7663. "scanf", FormatIdx+1,
  7664. HasVAListArg ? 0 : FormatIdx+2));
  7665. }
  7666. // Mark const if we don't care about errno and that is the only
  7667. // thing preventing the function from being const. This allows
  7668. // IRgen to use LLVM intrinsics for such functions.
  7669. if (!getLangOpts().MathErrno &&
  7670. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
  7671. if (!FD->getAttr<ConstAttr>())
  7672. FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
  7673. }
  7674. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  7675. !FD->getAttr<ReturnsTwiceAttr>())
  7676. FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
  7677. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
  7678. FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
  7679. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
  7680. FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
  7681. }
  7682. IdentifierInfo *Name = FD->getIdentifier();
  7683. if (!Name)
  7684. return;
  7685. if ((!getLangOpts().CPlusPlus &&
  7686. FD->getDeclContext()->isTranslationUnit()) ||
  7687. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  7688. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  7689. LinkageSpecDecl::lang_c)) {
  7690. // Okay: this could be a libc/libm/Objective-C function we know
  7691. // about.
  7692. } else
  7693. return;
  7694. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  7695. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  7696. // target-specific builtins, perhaps?
  7697. if (!FD->getAttr<FormatAttr>())
  7698. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  7699. "printf", 2,
  7700. Name->isStr("vasprintf") ? 0 : 3));
  7701. }
  7702. if (Name->isStr("__CFStringMakeConstantString")) {
  7703. // We already have a __builtin___CFStringMakeConstantString,
  7704. // but builds that use -fno-constant-cfstrings don't go through that.
  7705. if (!FD->getAttr<FormatArgAttr>())
  7706. FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
  7707. }
  7708. }
  7709. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  7710. TypeSourceInfo *TInfo) {
  7711. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  7712. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  7713. if (!TInfo) {
  7714. assert(D.isInvalidType() && "no declarator info for valid type");
  7715. TInfo = Context.getTrivialTypeSourceInfo(T);
  7716. }
  7717. // Scope manipulation handled by caller.
  7718. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  7719. D.getLocStart(),
  7720. D.getIdentifierLoc(),
  7721. D.getIdentifier(),
  7722. TInfo);
  7723. // Bail out immediately if we have an invalid declaration.
  7724. if (D.isInvalidType()) {
  7725. NewTD->setInvalidDecl();
  7726. return NewTD;
  7727. }
  7728. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7729. if (CurContext->isFunctionOrMethod())
  7730. Diag(NewTD->getLocation(), diag::err_module_private_local)
  7731. << 2 << NewTD->getDeclName()
  7732. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  7733. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  7734. else
  7735. NewTD->setModulePrivate();
  7736. }
  7737. // C++ [dcl.typedef]p8:
  7738. // If the typedef declaration defines an unnamed class (or
  7739. // enum), the first typedef-name declared by the declaration
  7740. // to be that class type (or enum type) is used to denote the
  7741. // class type (or enum type) for linkage purposes only.
  7742. // We need to check whether the type was declared in the declaration.
  7743. switch (D.getDeclSpec().getTypeSpecType()) {
  7744. case TST_enum:
  7745. case TST_struct:
  7746. case TST_interface:
  7747. case TST_union:
  7748. case TST_class: {
  7749. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  7750. // Do nothing if the tag is not anonymous or already has an
  7751. // associated typedef (from an earlier typedef in this decl group).
  7752. if (tagFromDeclSpec->getIdentifier()) break;
  7753. if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
  7754. // A well-formed anonymous tag must always be a TUK_Definition.
  7755. assert(tagFromDeclSpec->isThisDeclarationADefinition());
  7756. // The type must match the tag exactly; no qualifiers allowed.
  7757. if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
  7758. break;
  7759. // Otherwise, set this is the anon-decl typedef for the tag.
  7760. tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  7761. break;
  7762. }
  7763. default:
  7764. break;
  7765. }
  7766. return NewTD;
  7767. }
  7768. /// \brief Check that this is a valid underlying type for an enum declaration.
  7769. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  7770. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  7771. QualType T = TI->getType();
  7772. if (T->isDependentType())
  7773. return false;
  7774. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  7775. if (BT->isInteger())
  7776. return false;
  7777. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  7778. return true;
  7779. }
  7780. /// Check whether this is a valid redeclaration of a previous enumeration.
  7781. /// \return true if the redeclaration was invalid.
  7782. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  7783. QualType EnumUnderlyingTy,
  7784. const EnumDecl *Prev) {
  7785. bool IsFixed = !EnumUnderlyingTy.isNull();
  7786. if (IsScoped != Prev->isScoped()) {
  7787. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  7788. << Prev->isScoped();
  7789. Diag(Prev->getLocation(), diag::note_previous_use);
  7790. return true;
  7791. }
  7792. if (IsFixed && Prev->isFixed()) {
  7793. if (!EnumUnderlyingTy->isDependentType() &&
  7794. !Prev->getIntegerType()->isDependentType() &&
  7795. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  7796. Prev->getIntegerType())) {
  7797. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  7798. << EnumUnderlyingTy << Prev->getIntegerType();
  7799. Diag(Prev->getLocation(), diag::note_previous_use);
  7800. return true;
  7801. }
  7802. } else if (IsFixed != Prev->isFixed()) {
  7803. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  7804. << Prev->isFixed();
  7805. Diag(Prev->getLocation(), diag::note_previous_use);
  7806. return true;
  7807. }
  7808. return false;
  7809. }
  7810. /// \brief Get diagnostic %select index for tag kind for
  7811. /// redeclaration diagnostic message.
  7812. /// WARNING: Indexes apply to particular diagnostics only!
  7813. ///
  7814. /// \returns diagnostic %select index.
  7815. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  7816. switch (Tag) {
  7817. case TTK_Struct: return 0;
  7818. case TTK_Interface: return 1;
  7819. case TTK_Class: return 2;
  7820. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  7821. }
  7822. }
  7823. /// \brief Determine if tag kind is a class-key compatible with
  7824. /// class for redeclaration (class, struct, or __interface).
  7825. ///
  7826. /// \returns true iff the tag kind is compatible.
  7827. static bool isClassCompatTagKind(TagTypeKind Tag)
  7828. {
  7829. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  7830. }
  7831. /// \brief Determine whether a tag with a given kind is acceptable
  7832. /// as a redeclaration of the given tag declaration.
  7833. ///
  7834. /// \returns true if the new tag kind is acceptable, false otherwise.
  7835. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  7836. TagTypeKind NewTag, bool isDefinition,
  7837. SourceLocation NewTagLoc,
  7838. const IdentifierInfo &Name) {
  7839. // C++ [dcl.type.elab]p3:
  7840. // The class-key or enum keyword present in the
  7841. // elaborated-type-specifier shall agree in kind with the
  7842. // declaration to which the name in the elaborated-type-specifier
  7843. // refers. This rule also applies to the form of
  7844. // elaborated-type-specifier that declares a class-name or
  7845. // friend class since it can be construed as referring to the
  7846. // definition of the class. Thus, in any
  7847. // elaborated-type-specifier, the enum keyword shall be used to
  7848. // refer to an enumeration (7.2), the union class-key shall be
  7849. // used to refer to a union (clause 9), and either the class or
  7850. // struct class-key shall be used to refer to a class (clause 9)
  7851. // declared using the class or struct class-key.
  7852. TagTypeKind OldTag = Previous->getTagKind();
  7853. if (!isDefinition || !isClassCompatTagKind(NewTag))
  7854. if (OldTag == NewTag)
  7855. return true;
  7856. if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
  7857. // Warn about the struct/class tag mismatch.
  7858. bool isTemplate = false;
  7859. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  7860. isTemplate = Record->getDescribedClassTemplate();
  7861. if (!ActiveTemplateInstantiations.empty()) {
  7862. // In a template instantiation, do not offer fix-its for tag mismatches
  7863. // since they usually mess up the template instead of fixing the problem.
  7864. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  7865. << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
  7866. << getRedeclDiagFromTagKind(OldTag);
  7867. return true;
  7868. }
  7869. if (isDefinition) {
  7870. // On definitions, check previous tags and issue a fix-it for each
  7871. // one that doesn't match the current tag.
  7872. if (Previous->getDefinition()) {
  7873. // Don't suggest fix-its for redefinitions.
  7874. return true;
  7875. }
  7876. bool previousMismatch = false;
  7877. for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
  7878. E(Previous->redecls_end()); I != E; ++I) {
  7879. if (I->getTagKind() != NewTag) {
  7880. if (!previousMismatch) {
  7881. previousMismatch = true;
  7882. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  7883. << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
  7884. << getRedeclDiagFromTagKind(I->getTagKind());
  7885. }
  7886. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  7887. << getRedeclDiagFromTagKind(NewTag)
  7888. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  7889. TypeWithKeyword::getTagTypeKindName(NewTag));
  7890. }
  7891. }
  7892. return true;
  7893. }
  7894. // Check for a previous definition. If current tag and definition
  7895. // are same type, do nothing. If no definition, but disagree with
  7896. // with previous tag type, give a warning, but no fix-it.
  7897. const TagDecl *Redecl = Previous->getDefinition() ?
  7898. Previous->getDefinition() : Previous;
  7899. if (Redecl->getTagKind() == NewTag) {
  7900. return true;
  7901. }
  7902. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  7903. << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
  7904. << getRedeclDiagFromTagKind(OldTag);
  7905. Diag(Redecl->getLocation(), diag::note_previous_use);
  7906. // If there is a previous defintion, suggest a fix-it.
  7907. if (Previous->getDefinition()) {
  7908. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  7909. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  7910. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  7911. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  7912. }
  7913. return true;
  7914. }
  7915. return false;
  7916. }
  7917. /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
  7918. /// former case, Name will be non-null. In the later case, Name will be null.
  7919. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  7920. /// reference/declaration/definition of a tag.
  7921. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  7922. SourceLocation KWLoc, CXXScopeSpec &SS,
  7923. IdentifierInfo *Name, SourceLocation NameLoc,
  7924. AttributeList *Attr, AccessSpecifier AS,
  7925. SourceLocation ModulePrivateLoc,
  7926. MultiTemplateParamsArg TemplateParameterLists,
  7927. bool &OwnedDecl, bool &IsDependent,
  7928. SourceLocation ScopedEnumKWLoc,
  7929. bool ScopedEnumUsesClassTag,
  7930. TypeResult UnderlyingType) {
  7931. // If this is not a definition, it must have a name.
  7932. IdentifierInfo *OrigName = Name;
  7933. assert((Name != 0 || TUK == TUK_Definition) &&
  7934. "Nameless record must be a definition!");
  7935. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  7936. OwnedDecl = false;
  7937. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  7938. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  7939. // FIXME: Check explicit specializations more carefully.
  7940. bool isExplicitSpecialization = false;
  7941. bool Invalid = false;
  7942. // We only need to do this matching if we have template parameters
  7943. // or a scope specifier, which also conveniently avoids this work
  7944. // for non-C++ cases.
  7945. if (TemplateParameterLists.size() > 0 ||
  7946. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  7947. if (TemplateParameterList *TemplateParams
  7948. = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
  7949. TemplateParameterLists.data(),
  7950. TemplateParameterLists.size(),
  7951. TUK == TUK_Friend,
  7952. isExplicitSpecialization,
  7953. Invalid)) {
  7954. if (TemplateParams->size() > 0) {
  7955. // This is a declaration or definition of a class template (which may
  7956. // be a member of another template).
  7957. if (Invalid)
  7958. return 0;
  7959. OwnedDecl = false;
  7960. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  7961. SS, Name, NameLoc, Attr,
  7962. TemplateParams, AS,
  7963. ModulePrivateLoc,
  7964. TemplateParameterLists.size()-1,
  7965. TemplateParameterLists.data());
  7966. return Result.get();
  7967. } else {
  7968. // The "template<>" header is extraneous.
  7969. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  7970. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  7971. isExplicitSpecialization = true;
  7972. }
  7973. }
  7974. }
  7975. // Figure out the underlying type if this a enum declaration. We need to do
  7976. // this early, because it's needed to detect if this is an incompatible
  7977. // redeclaration.
  7978. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  7979. if (Kind == TTK_Enum) {
  7980. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
  7981. // No underlying type explicitly specified, or we failed to parse the
  7982. // type, default to int.
  7983. EnumUnderlying = Context.IntTy.getTypePtr();
  7984. else if (UnderlyingType.get()) {
  7985. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  7986. // integral type; any cv-qualification is ignored.
  7987. TypeSourceInfo *TI = 0;
  7988. GetTypeFromParser(UnderlyingType.get(), &TI);
  7989. EnumUnderlying = TI;
  7990. if (CheckEnumUnderlyingType(TI))
  7991. // Recover by falling back to int.
  7992. EnumUnderlying = Context.IntTy.getTypePtr();
  7993. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  7994. UPPC_FixedUnderlyingType))
  7995. EnumUnderlying = Context.IntTy.getTypePtr();
  7996. } else if (getLangOpts().MicrosoftMode)
  7997. // Microsoft enums are always of int type.
  7998. EnumUnderlying = Context.IntTy.getTypePtr();
  7999. }
  8000. DeclContext *SearchDC = CurContext;
  8001. DeclContext *DC = CurContext;
  8002. bool isStdBadAlloc = false;
  8003. RedeclarationKind Redecl = ForRedeclaration;
  8004. if (TUK == TUK_Friend || TUK == TUK_Reference)
  8005. Redecl = NotForRedeclaration;
  8006. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  8007. if (Name && SS.isNotEmpty()) {
  8008. // We have a nested-name tag ('struct foo::bar').
  8009. // Check for invalid 'foo::'.
  8010. if (SS.isInvalid()) {
  8011. Name = 0;
  8012. goto CreateNewDecl;
  8013. }
  8014. // If this is a friend or a reference to a class in a dependent
  8015. // context, don't try to make a decl for it.
  8016. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  8017. DC = computeDeclContext(SS, false);
  8018. if (!DC) {
  8019. IsDependent = true;
  8020. return 0;
  8021. }
  8022. } else {
  8023. DC = computeDeclContext(SS, true);
  8024. if (!DC) {
  8025. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  8026. << SS.getRange();
  8027. return 0;
  8028. }
  8029. }
  8030. if (RequireCompleteDeclContext(SS, DC))
  8031. return 0;
  8032. SearchDC = DC;
  8033. // Look-up name inside 'foo::'.
  8034. LookupQualifiedName(Previous, DC);
  8035. if (Previous.isAmbiguous())
  8036. return 0;
  8037. if (Previous.empty()) {
  8038. // Name lookup did not find anything. However, if the
  8039. // nested-name-specifier refers to the current instantiation,
  8040. // and that current instantiation has any dependent base
  8041. // classes, we might find something at instantiation time: treat
  8042. // this as a dependent elaborated-type-specifier.
  8043. // But this only makes any sense for reference-like lookups.
  8044. if (Previous.wasNotFoundInCurrentInstantiation() &&
  8045. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  8046. IsDependent = true;
  8047. return 0;
  8048. }
  8049. // A tag 'foo::bar' must already exist.
  8050. Diag(NameLoc, diag::err_not_tag_in_scope)
  8051. << Kind << Name << DC << SS.getRange();
  8052. Name = 0;
  8053. Invalid = true;
  8054. goto CreateNewDecl;
  8055. }
  8056. } else if (Name) {
  8057. // If this is a named struct, check to see if there was a previous forward
  8058. // declaration or definition.
  8059. // FIXME: We're looking into outer scopes here, even when we
  8060. // shouldn't be. Doing so can result in ambiguities that we
  8061. // shouldn't be diagnosing.
  8062. LookupName(Previous, S);
  8063. if (Previous.isAmbiguous() &&
  8064. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  8065. LookupResult::Filter F = Previous.makeFilter();
  8066. while (F.hasNext()) {
  8067. NamedDecl *ND = F.next();
  8068. if (ND->getDeclContext()->getRedeclContext() != SearchDC)
  8069. F.erase();
  8070. }
  8071. F.done();
  8072. }
  8073. // Note: there used to be some attempt at recovery here.
  8074. if (Previous.isAmbiguous())
  8075. return 0;
  8076. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  8077. // FIXME: This makes sure that we ignore the contexts associated
  8078. // with C structs, unions, and enums when looking for a matching
  8079. // tag declaration or definition. See the similar lookup tweak
  8080. // in Sema::LookupName; is there a better way to deal with this?
  8081. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  8082. SearchDC = SearchDC->getParent();
  8083. }
  8084. } else if (S->isFunctionPrototypeScope()) {
  8085. // If this is an enum declaration in function prototype scope, set its
  8086. // initial context to the translation unit.
  8087. // FIXME: [citation needed]
  8088. SearchDC = Context.getTranslationUnitDecl();
  8089. }
  8090. if (Previous.isSingleResult() &&
  8091. Previous.getFoundDecl()->isTemplateParameter()) {
  8092. // Maybe we will complain about the shadowed template parameter.
  8093. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  8094. // Just pretend that we didn't see the previous declaration.
  8095. Previous.clear();
  8096. }
  8097. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  8098. DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
  8099. // This is a declaration of or a reference to "std::bad_alloc".
  8100. isStdBadAlloc = true;
  8101. if (Previous.empty() && StdBadAlloc) {
  8102. // std::bad_alloc has been implicitly declared (but made invisible to
  8103. // name lookup). Fill in this implicit declaration as the previous
  8104. // declaration, so that the declarations get chained appropriately.
  8105. Previous.addDecl(getStdBadAlloc());
  8106. }
  8107. }
  8108. // If we didn't find a previous declaration, and this is a reference
  8109. // (or friend reference), move to the correct scope. In C++, we
  8110. // also need to do a redeclaration lookup there, just in case
  8111. // there's a shadow friend decl.
  8112. if (Name && Previous.empty() &&
  8113. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  8114. if (Invalid) goto CreateNewDecl;
  8115. assert(SS.isEmpty());
  8116. if (TUK == TUK_Reference) {
  8117. // C++ [basic.scope.pdecl]p5:
  8118. // -- for an elaborated-type-specifier of the form
  8119. //
  8120. // class-key identifier
  8121. //
  8122. // if the elaborated-type-specifier is used in the
  8123. // decl-specifier-seq or parameter-declaration-clause of a
  8124. // function defined in namespace scope, the identifier is
  8125. // declared as a class-name in the namespace that contains
  8126. // the declaration; otherwise, except as a friend
  8127. // declaration, the identifier is declared in the smallest
  8128. // non-class, non-function-prototype scope that contains the
  8129. // declaration.
  8130. //
  8131. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  8132. // C structs and unions.
  8133. //
  8134. // It is an error in C++ to declare (rather than define) an enum
  8135. // type, including via an elaborated type specifier. We'll
  8136. // diagnose that later; for now, declare the enum in the same
  8137. // scope as we would have picked for any other tag type.
  8138. //
  8139. // GNU C also supports this behavior as part of its incomplete
  8140. // enum types extension, while GNU C++ does not.
  8141. //
  8142. // Find the context where we'll be declaring the tag.
  8143. // FIXME: We would like to maintain the current DeclContext as the
  8144. // lexical context,
  8145. while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
  8146. SearchDC = SearchDC->getParent();
  8147. // Find the scope where we'll be declaring the tag.
  8148. while (S->isClassScope() ||
  8149. (getLangOpts().CPlusPlus &&
  8150. S->isFunctionPrototypeScope()) ||
  8151. ((S->getFlags() & Scope::DeclScope) == 0) ||
  8152. (S->getEntity() &&
  8153. ((DeclContext *)S->getEntity())->isTransparentContext()))
  8154. S = S->getParent();
  8155. } else {
  8156. assert(TUK == TUK_Friend);
  8157. // C++ [namespace.memdef]p3:
  8158. // If a friend declaration in a non-local class first declares a
  8159. // class or function, the friend class or function is a member of
  8160. // the innermost enclosing namespace.
  8161. SearchDC = SearchDC->getEnclosingNamespaceContext();
  8162. }
  8163. // In C++, we need to do a redeclaration lookup to properly
  8164. // diagnose some problems.
  8165. if (getLangOpts().CPlusPlus) {
  8166. Previous.setRedeclarationKind(ForRedeclaration);
  8167. LookupQualifiedName(Previous, SearchDC);
  8168. }
  8169. }
  8170. if (!Previous.empty()) {
  8171. NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
  8172. // It's okay to have a tag decl in the same scope as a typedef
  8173. // which hides a tag decl in the same scope. Finding this
  8174. // insanity with a redeclaration lookup can only actually happen
  8175. // in C++.
  8176. //
  8177. // This is also okay for elaborated-type-specifiers, which is
  8178. // technically forbidden by the current standard but which is
  8179. // okay according to the likely resolution of an open issue;
  8180. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  8181. if (getLangOpts().CPlusPlus) {
  8182. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  8183. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  8184. TagDecl *Tag = TT->getDecl();
  8185. if (Tag->getDeclName() == Name &&
  8186. Tag->getDeclContext()->getRedeclContext()
  8187. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  8188. PrevDecl = Tag;
  8189. Previous.clear();
  8190. Previous.addDecl(Tag);
  8191. Previous.resolveKind();
  8192. }
  8193. }
  8194. }
  8195. }
  8196. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  8197. // If this is a use of a previous tag, or if the tag is already declared
  8198. // in the same scope (so that the definition/declaration completes or
  8199. // rementions the tag), reuse the decl.
  8200. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  8201. isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
  8202. // Make sure that this wasn't declared as an enum and now used as a
  8203. // struct or something similar.
  8204. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  8205. TUK == TUK_Definition, KWLoc,
  8206. *Name)) {
  8207. bool SafeToContinue
  8208. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  8209. Kind != TTK_Enum);
  8210. if (SafeToContinue)
  8211. Diag(KWLoc, diag::err_use_with_wrong_tag)
  8212. << Name
  8213. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  8214. PrevTagDecl->getKindName());
  8215. else
  8216. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  8217. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  8218. if (SafeToContinue)
  8219. Kind = PrevTagDecl->getTagKind();
  8220. else {
  8221. // Recover by making this an anonymous redefinition.
  8222. Name = 0;
  8223. Previous.clear();
  8224. Invalid = true;
  8225. }
  8226. }
  8227. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  8228. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  8229. // If this is an elaborated-type-specifier for a scoped enumeration,
  8230. // the 'class' keyword is not necessary and not permitted.
  8231. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  8232. if (ScopedEnum)
  8233. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  8234. << PrevEnum->isScoped()
  8235. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  8236. return PrevTagDecl;
  8237. }
  8238. QualType EnumUnderlyingTy;
  8239. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  8240. EnumUnderlyingTy = TI->getType();
  8241. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  8242. EnumUnderlyingTy = QualType(T, 0);
  8243. // All conflicts with previous declarations are recovered by
  8244. // returning the previous declaration, unless this is a definition,
  8245. // in which case we want the caller to bail out.
  8246. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  8247. ScopedEnum, EnumUnderlyingTy, PrevEnum))
  8248. return TUK == TUK_Declaration ? PrevTagDecl : 0;
  8249. }
  8250. if (!Invalid) {
  8251. // If this is a use, just return the declaration we found.
  8252. // FIXME: In the future, return a variant or some other clue
  8253. // for the consumer of this Decl to know it doesn't own it.
  8254. // For our current ASTs this shouldn't be a problem, but will
  8255. // need to be changed with DeclGroups.
  8256. if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
  8257. getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
  8258. return PrevTagDecl;
  8259. // Diagnose attempts to redefine a tag.
  8260. if (TUK == TUK_Definition) {
  8261. if (TagDecl *Def = PrevTagDecl->getDefinition()) {
  8262. // If we're defining a specialization and the previous definition
  8263. // is from an implicit instantiation, don't emit an error
  8264. // here; we'll catch this in the general case below.
  8265. bool IsExplicitSpecializationAfterInstantiation = false;
  8266. if (isExplicitSpecialization) {
  8267. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  8268. IsExplicitSpecializationAfterInstantiation =
  8269. RD->getTemplateSpecializationKind() !=
  8270. TSK_ExplicitSpecialization;
  8271. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  8272. IsExplicitSpecializationAfterInstantiation =
  8273. ED->getTemplateSpecializationKind() !=
  8274. TSK_ExplicitSpecialization;
  8275. }
  8276. if (!IsExplicitSpecializationAfterInstantiation) {
  8277. // A redeclaration in function prototype scope in C isn't
  8278. // visible elsewhere, so merely issue a warning.
  8279. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  8280. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  8281. else
  8282. Diag(NameLoc, diag::err_redefinition) << Name;
  8283. Diag(Def->getLocation(), diag::note_previous_definition);
  8284. // If this is a redefinition, recover by making this
  8285. // struct be anonymous, which will make any later
  8286. // references get the previous definition.
  8287. Name = 0;
  8288. Previous.clear();
  8289. Invalid = true;
  8290. }
  8291. } else {
  8292. // If the type is currently being defined, complain
  8293. // about a nested redefinition.
  8294. const TagType *Tag
  8295. = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
  8296. if (Tag->isBeingDefined()) {
  8297. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  8298. Diag(PrevTagDecl->getLocation(),
  8299. diag::note_previous_definition);
  8300. Name = 0;
  8301. Previous.clear();
  8302. Invalid = true;
  8303. }
  8304. }
  8305. // Okay, this is definition of a previously declared or referenced
  8306. // tag PrevDecl. We're going to create a new Decl for it.
  8307. }
  8308. }
  8309. // If we get here we have (another) forward declaration or we
  8310. // have a definition. Just create a new decl.
  8311. } else {
  8312. // If we get here, this is a definition of a new tag type in a nested
  8313. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  8314. // new decl/type. We set PrevDecl to NULL so that the entities
  8315. // have distinct types.
  8316. Previous.clear();
  8317. }
  8318. // If we get here, we're going to create a new Decl. If PrevDecl
  8319. // is non-NULL, it's a definition of the tag declared by
  8320. // PrevDecl. If it's NULL, we have a new definition.
  8321. // Otherwise, PrevDecl is not a tag, but was found with tag
  8322. // lookup. This is only actually possible in C++, where a few
  8323. // things like templates still live in the tag namespace.
  8324. } else {
  8325. // Use a better diagnostic if an elaborated-type-specifier
  8326. // found the wrong kind of type on the first
  8327. // (non-redeclaration) lookup.
  8328. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  8329. !Previous.isForRedeclaration()) {
  8330. unsigned Kind = 0;
  8331. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  8332. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  8333. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  8334. Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
  8335. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  8336. Invalid = true;
  8337. // Otherwise, only diagnose if the declaration is in scope.
  8338. } else if (!isDeclInScope(PrevDecl, SearchDC, S,
  8339. isExplicitSpecialization)) {
  8340. // do nothing
  8341. // Diagnose implicit declarations introduced by elaborated types.
  8342. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  8343. unsigned Kind = 0;
  8344. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  8345. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  8346. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  8347. Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
  8348. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  8349. Invalid = true;
  8350. // Otherwise it's a declaration. Call out a particularly common
  8351. // case here.
  8352. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  8353. unsigned Kind = 0;
  8354. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  8355. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  8356. << Name << Kind << TND->getUnderlyingType();
  8357. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  8358. Invalid = true;
  8359. // Otherwise, diagnose.
  8360. } else {
  8361. // The tag name clashes with something else in the target scope,
  8362. // issue an error and recover by making this tag be anonymous.
  8363. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  8364. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  8365. Name = 0;
  8366. Invalid = true;
  8367. }
  8368. // The existing declaration isn't relevant to us; we're in a
  8369. // new scope, so clear out the previous declaration.
  8370. Previous.clear();
  8371. }
  8372. }
  8373. CreateNewDecl:
  8374. TagDecl *PrevDecl = 0;
  8375. if (Previous.isSingleResult())
  8376. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  8377. // If there is an identifier, use the location of the identifier as the
  8378. // location of the decl, otherwise use the location of the struct/union
  8379. // keyword.
  8380. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  8381. // Otherwise, create a new declaration. If there is a previous
  8382. // declaration of the same entity, the two will be linked via
  8383. // PrevDecl.
  8384. TagDecl *New;
  8385. bool IsForwardReference = false;
  8386. if (Kind == TTK_Enum) {
  8387. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  8388. // enum X { A, B, C } D; D should chain to X.
  8389. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  8390. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  8391. ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
  8392. // If this is an undefined enum, warn.
  8393. if (TUK != TUK_Definition && !Invalid) {
  8394. TagDecl *Def;
  8395. if (getLangOpts().CPlusPlus11 && cast<EnumDecl>(New)->isFixed()) {
  8396. // C++0x: 7.2p2: opaque-enum-declaration.
  8397. // Conflicts are diagnosed above. Do nothing.
  8398. }
  8399. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  8400. Diag(Loc, diag::ext_forward_ref_enum_def)
  8401. << New;
  8402. Diag(Def->getLocation(), diag::note_previous_definition);
  8403. } else {
  8404. unsigned DiagID = diag::ext_forward_ref_enum;
  8405. if (getLangOpts().MicrosoftMode)
  8406. DiagID = diag::ext_ms_forward_ref_enum;
  8407. else if (getLangOpts().CPlusPlus)
  8408. DiagID = diag::err_forward_ref_enum;
  8409. Diag(Loc, DiagID);
  8410. // If this is a forward-declared reference to an enumeration, make a
  8411. // note of it; we won't actually be introducing the declaration into
  8412. // the declaration context.
  8413. if (TUK == TUK_Reference)
  8414. IsForwardReference = true;
  8415. }
  8416. }
  8417. if (EnumUnderlying) {
  8418. EnumDecl *ED = cast<EnumDecl>(New);
  8419. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  8420. ED->setIntegerTypeSourceInfo(TI);
  8421. else
  8422. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  8423. ED->setPromotionType(ED->getIntegerType());
  8424. }
  8425. } else {
  8426. // struct/union/class
  8427. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  8428. // struct X { int A; } D; D should chain to X.
  8429. if (getLangOpts().CPlusPlus) {
  8430. // FIXME: Look for a way to use RecordDecl for simple structs.
  8431. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  8432. cast_or_null<CXXRecordDecl>(PrevDecl));
  8433. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  8434. StdBadAlloc = cast<CXXRecordDecl>(New);
  8435. } else
  8436. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  8437. cast_or_null<RecordDecl>(PrevDecl));
  8438. }
  8439. // Maybe add qualifier info.
  8440. if (SS.isNotEmpty()) {
  8441. if (SS.isSet()) {
  8442. // If this is either a declaration or a definition, check the
  8443. // nested-name-specifier against the current context. We don't do this
  8444. // for explicit specializations, because they have similar checking
  8445. // (with more specific diagnostics) in the call to
  8446. // CheckMemberSpecialization, below.
  8447. if (!isExplicitSpecialization &&
  8448. (TUK == TUK_Definition || TUK == TUK_Declaration) &&
  8449. diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
  8450. Invalid = true;
  8451. New->setQualifierInfo(SS.getWithLocInContext(Context));
  8452. if (TemplateParameterLists.size() > 0) {
  8453. New->setTemplateParameterListsInfo(Context,
  8454. TemplateParameterLists.size(),
  8455. TemplateParameterLists.data());
  8456. }
  8457. }
  8458. else
  8459. Invalid = true;
  8460. }
  8461. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  8462. // Add alignment attributes if necessary; these attributes are checked when
  8463. // the ASTContext lays out the structure.
  8464. //
  8465. // It is important for implementing the correct semantics that this
  8466. // happen here (in act on tag decl). The #pragma pack stack is
  8467. // maintained as a result of parser callbacks which can occur at
  8468. // many points during the parsing of a struct declaration (because
  8469. // the #pragma tokens are effectively skipped over during the
  8470. // parsing of the struct).
  8471. if (TUK == TUK_Definition) {
  8472. AddAlignmentAttributesForRecord(RD);
  8473. AddMsStructLayoutForRecord(RD);
  8474. }
  8475. }
  8476. if (ModulePrivateLoc.isValid()) {
  8477. if (isExplicitSpecialization)
  8478. Diag(New->getLocation(), diag::err_module_private_specialization)
  8479. << 2
  8480. << FixItHint::CreateRemoval(ModulePrivateLoc);
  8481. // __module_private__ does not apply to local classes. However, we only
  8482. // diagnose this as an error when the declaration specifiers are
  8483. // freestanding. Here, we just ignore the __module_private__.
  8484. else if (!SearchDC->isFunctionOrMethod())
  8485. New->setModulePrivate();
  8486. }
  8487. // If this is a specialization of a member class (of a class template),
  8488. // check the specialization.
  8489. if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
  8490. Invalid = true;
  8491. if (Invalid)
  8492. New->setInvalidDecl();
  8493. if (Attr)
  8494. ProcessDeclAttributeList(S, New, Attr);
  8495. // If we're declaring or defining a tag in function prototype scope
  8496. // in C, note that this type can only be used within the function.
  8497. if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
  8498. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  8499. // Set the lexical context. If the tag has a C++ scope specifier, the
  8500. // lexical context will be different from the semantic context.
  8501. New->setLexicalDeclContext(CurContext);
  8502. // Mark this as a friend decl if applicable.
  8503. // In Microsoft mode, a friend declaration also acts as a forward
  8504. // declaration so we always pass true to setObjectOfFriendDecl to make
  8505. // the tag name visible.
  8506. if (TUK == TUK_Friend)
  8507. New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
  8508. getLangOpts().MicrosoftExt);
  8509. // Set the access specifier.
  8510. if (!Invalid && SearchDC->isRecord())
  8511. SetMemberAccessSpecifier(New, PrevDecl, AS);
  8512. if (TUK == TUK_Definition)
  8513. New->startDefinition();
  8514. // If this has an identifier, add it to the scope stack.
  8515. if (TUK == TUK_Friend) {
  8516. // We might be replacing an existing declaration in the lookup tables;
  8517. // if so, borrow its access specifier.
  8518. if (PrevDecl)
  8519. New->setAccess(PrevDecl->getAccess());
  8520. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  8521. DC->makeDeclVisibleInContext(New);
  8522. if (Name) // can be null along some error paths
  8523. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  8524. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  8525. } else if (Name) {
  8526. S = getNonFieldDeclScope(S);
  8527. PushOnScopeChains(New, S, !IsForwardReference);
  8528. if (IsForwardReference)
  8529. SearchDC->makeDeclVisibleInContext(New);
  8530. } else {
  8531. CurContext->addDecl(New);
  8532. }
  8533. // If this is the C FILE type, notify the AST context.
  8534. if (IdentifierInfo *II = New->getIdentifier())
  8535. if (!New->isInvalidDecl() &&
  8536. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  8537. II->isStr("FILE"))
  8538. Context.setFILEDecl(New);
  8539. // If we were in function prototype scope (and not in C++ mode), add this
  8540. // tag to the list of decls to inject into the function definition scope.
  8541. if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
  8542. InFunctionDeclarator && Name)
  8543. DeclsInPrototypeScope.push_back(New);
  8544. if (PrevDecl)
  8545. mergeDeclAttributes(New, PrevDecl);
  8546. // If there's a #pragma GCC visibility in scope, set the visibility of this
  8547. // record.
  8548. AddPushedVisibilityAttribute(New);
  8549. OwnedDecl = true;
  8550. // In C++, don't return an invalid declaration. We can't recover well from
  8551. // the cases where we make the type anonymous.
  8552. return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
  8553. }
  8554. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  8555. AdjustDeclIfTemplate(TagD);
  8556. TagDecl *Tag = cast<TagDecl>(TagD);
  8557. // Enter the tag context.
  8558. PushDeclContext(S, Tag);
  8559. ActOnDocumentableDecl(TagD);
  8560. // If there's a #pragma GCC visibility in scope, set the visibility of this
  8561. // record.
  8562. AddPushedVisibilityAttribute(Tag);
  8563. }
  8564. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  8565. assert(isa<ObjCContainerDecl>(IDecl) &&
  8566. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  8567. DeclContext *OCD = cast<DeclContext>(IDecl);
  8568. assert(getContainingDC(OCD) == CurContext &&
  8569. "The next DeclContext should be lexically contained in the current one.");
  8570. CurContext = OCD;
  8571. return IDecl;
  8572. }
  8573. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  8574. SourceLocation FinalLoc,
  8575. SourceLocation LBraceLoc) {
  8576. AdjustDeclIfTemplate(TagD);
  8577. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  8578. FieldCollector->StartClass();
  8579. if (!Record->getIdentifier())
  8580. return;
  8581. if (FinalLoc.isValid())
  8582. Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
  8583. // C++ [class]p2:
  8584. // [...] The class-name is also inserted into the scope of the
  8585. // class itself; this is known as the injected-class-name. For
  8586. // purposes of access checking, the injected-class-name is treated
  8587. // as if it were a public member name.
  8588. CXXRecordDecl *InjectedClassName
  8589. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  8590. Record->getLocStart(), Record->getLocation(),
  8591. Record->getIdentifier(),
  8592. /*PrevDecl=*/0,
  8593. /*DelayTypeCreation=*/true);
  8594. Context.getTypeDeclType(InjectedClassName, Record);
  8595. InjectedClassName->setImplicit();
  8596. InjectedClassName->setAccess(AS_public);
  8597. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  8598. InjectedClassName->setDescribedClassTemplate(Template);
  8599. PushOnScopeChains(InjectedClassName, S);
  8600. assert(InjectedClassName->isInjectedClassName() &&
  8601. "Broken injected-class-name");
  8602. }
  8603. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  8604. SourceLocation RBraceLoc) {
  8605. AdjustDeclIfTemplate(TagD);
  8606. TagDecl *Tag = cast<TagDecl>(TagD);
  8607. Tag->setRBraceLoc(RBraceLoc);
  8608. // Make sure we "complete" the definition even it is invalid.
  8609. if (Tag->isBeingDefined()) {
  8610. assert(Tag->isInvalidDecl() && "We should already have completed it");
  8611. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  8612. RD->completeDefinition();
  8613. }
  8614. if (isa<CXXRecordDecl>(Tag))
  8615. FieldCollector->FinishClass();
  8616. // Exit this scope of this tag's definition.
  8617. PopDeclContext();
  8618. if (getCurLexicalContext()->isObjCContainer() &&
  8619. Tag->getDeclContext()->isFileContext())
  8620. Tag->setTopLevelDeclInObjCContainer();
  8621. // Notify the consumer that we've defined a tag.
  8622. Consumer.HandleTagDeclDefinition(Tag);
  8623. }
  8624. void Sema::ActOnObjCContainerFinishDefinition() {
  8625. // Exit this scope of this interface definition.
  8626. PopDeclContext();
  8627. }
  8628. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  8629. assert(DC == CurContext && "Mismatch of container contexts");
  8630. OriginalLexicalContext = DC;
  8631. ActOnObjCContainerFinishDefinition();
  8632. }
  8633. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  8634. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  8635. OriginalLexicalContext = 0;
  8636. }
  8637. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  8638. AdjustDeclIfTemplate(TagD);
  8639. TagDecl *Tag = cast<TagDecl>(TagD);
  8640. Tag->setInvalidDecl();
  8641. // Make sure we "complete" the definition even it is invalid.
  8642. if (Tag->isBeingDefined()) {
  8643. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  8644. RD->completeDefinition();
  8645. }
  8646. // We're undoing ActOnTagStartDefinition here, not
  8647. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  8648. // the FieldCollector.
  8649. PopDeclContext();
  8650. }
  8651. // Note that FieldName may be null for anonymous bitfields.
  8652. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  8653. IdentifierInfo *FieldName,
  8654. QualType FieldTy, Expr *BitWidth,
  8655. bool *ZeroWidth) {
  8656. // Default to true; that shouldn't confuse checks for emptiness
  8657. if (ZeroWidth)
  8658. *ZeroWidth = true;
  8659. // C99 6.7.2.1p4 - verify the field type.
  8660. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  8661. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  8662. // Handle incomplete types with specific error.
  8663. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  8664. return ExprError();
  8665. if (FieldName)
  8666. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  8667. << FieldName << FieldTy << BitWidth->getSourceRange();
  8668. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  8669. << FieldTy << BitWidth->getSourceRange();
  8670. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  8671. UPPC_BitFieldWidth))
  8672. return ExprError();
  8673. // If the bit-width is type- or value-dependent, don't try to check
  8674. // it now.
  8675. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  8676. return Owned(BitWidth);
  8677. llvm::APSInt Value;
  8678. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  8679. if (ICE.isInvalid())
  8680. return ICE;
  8681. BitWidth = ICE.take();
  8682. if (Value != 0 && ZeroWidth)
  8683. *ZeroWidth = false;
  8684. // Zero-width bitfield is ok for anonymous field.
  8685. if (Value == 0 && FieldName)
  8686. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  8687. if (Value.isSigned() && Value.isNegative()) {
  8688. if (FieldName)
  8689. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  8690. << FieldName << Value.toString(10);
  8691. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  8692. << Value.toString(10);
  8693. }
  8694. if (!FieldTy->isDependentType()) {
  8695. uint64_t TypeSize = Context.getTypeSize(FieldTy);
  8696. if (Value.getZExtValue() > TypeSize) {
  8697. if (!getLangOpts().CPlusPlus) {
  8698. if (FieldName)
  8699. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
  8700. << FieldName << (unsigned)Value.getZExtValue()
  8701. << (unsigned)TypeSize;
  8702. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
  8703. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  8704. }
  8705. if (FieldName)
  8706. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
  8707. << FieldName << (unsigned)Value.getZExtValue()
  8708. << (unsigned)TypeSize;
  8709. else
  8710. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
  8711. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  8712. }
  8713. }
  8714. return Owned(BitWidth);
  8715. }
  8716. /// ActOnField - Each field of a C struct/union is passed into this in order
  8717. /// to create a FieldDecl object for it.
  8718. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  8719. Declarator &D, Expr *BitfieldWidth) {
  8720. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  8721. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  8722. /*InitStyle=*/ICIS_NoInit, AS_public);
  8723. return Res;
  8724. }
  8725. /// HandleField - Analyze a field of a C struct or a C++ data member.
  8726. ///
  8727. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  8728. SourceLocation DeclStart,
  8729. Declarator &D, Expr *BitWidth,
  8730. InClassInitStyle InitStyle,
  8731. AccessSpecifier AS) {
  8732. IdentifierInfo *II = D.getIdentifier();
  8733. SourceLocation Loc = DeclStart;
  8734. if (II) Loc = D.getIdentifierLoc();
  8735. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  8736. QualType T = TInfo->getType();
  8737. if (getLangOpts().CPlusPlus) {
  8738. CheckExtraCXXDefaultArguments(D);
  8739. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  8740. UPPC_DataMemberType)) {
  8741. D.setInvalidType();
  8742. T = Context.IntTy;
  8743. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  8744. }
  8745. }
  8746. // OpenCL 1.2 spec, s6.9 r:
  8747. // The event type cannot be used to declare a structure or union field.
  8748. if (LangOpts.OpenCL && T->isEventT()) {
  8749. Diag(Loc, diag::err_event_t_struct_field);
  8750. D.setInvalidType();
  8751. }
  8752. DiagnoseFunctionSpecifiers(D);
  8753. if (D.getDeclSpec().isThreadSpecified())
  8754. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  8755. // Check to see if this name was declared as a member previously
  8756. NamedDecl *PrevDecl = 0;
  8757. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  8758. LookupName(Previous, S);
  8759. switch (Previous.getResultKind()) {
  8760. case LookupResult::Found:
  8761. case LookupResult::FoundUnresolvedValue:
  8762. PrevDecl = Previous.getAsSingle<NamedDecl>();
  8763. break;
  8764. case LookupResult::FoundOverloaded:
  8765. PrevDecl = Previous.getRepresentativeDecl();
  8766. break;
  8767. case LookupResult::NotFound:
  8768. case LookupResult::NotFoundInCurrentInstantiation:
  8769. case LookupResult::Ambiguous:
  8770. break;
  8771. }
  8772. Previous.suppressDiagnostics();
  8773. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  8774. // Maybe we will complain about the shadowed template parameter.
  8775. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  8776. // Just pretend that we didn't see the previous declaration.
  8777. PrevDecl = 0;
  8778. }
  8779. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  8780. PrevDecl = 0;
  8781. bool Mutable
  8782. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  8783. SourceLocation TSSL = D.getLocStart();
  8784. FieldDecl *NewFD
  8785. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  8786. TSSL, AS, PrevDecl, &D);
  8787. if (NewFD->isInvalidDecl())
  8788. Record->setInvalidDecl();
  8789. if (D.getDeclSpec().isModulePrivateSpecified())
  8790. NewFD->setModulePrivate();
  8791. if (NewFD->isInvalidDecl() && PrevDecl) {
  8792. // Don't introduce NewFD into scope; there's already something
  8793. // with the same name in the same scope.
  8794. } else if (II) {
  8795. PushOnScopeChains(NewFD, S);
  8796. } else
  8797. Record->addDecl(NewFD);
  8798. return NewFD;
  8799. }
  8800. /// \brief Build a new FieldDecl and check its well-formedness.
  8801. ///
  8802. /// This routine builds a new FieldDecl given the fields name, type,
  8803. /// record, etc. \p PrevDecl should refer to any previous declaration
  8804. /// with the same name and in the same scope as the field to be
  8805. /// created.
  8806. ///
  8807. /// \returns a new FieldDecl.
  8808. ///
  8809. /// \todo The Declarator argument is a hack. It will be removed once
  8810. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  8811. TypeSourceInfo *TInfo,
  8812. RecordDecl *Record, SourceLocation Loc,
  8813. bool Mutable, Expr *BitWidth,
  8814. InClassInitStyle InitStyle,
  8815. SourceLocation TSSL,
  8816. AccessSpecifier AS, NamedDecl *PrevDecl,
  8817. Declarator *D) {
  8818. IdentifierInfo *II = Name.getAsIdentifierInfo();
  8819. bool InvalidDecl = false;
  8820. if (D) InvalidDecl = D->isInvalidType();
  8821. // If we receive a broken type, recover by assuming 'int' and
  8822. // marking this declaration as invalid.
  8823. if (T.isNull()) {
  8824. InvalidDecl = true;
  8825. T = Context.IntTy;
  8826. }
  8827. QualType EltTy = Context.getBaseElementType(T);
  8828. if (!EltTy->isDependentType()) {
  8829. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  8830. // Fields of incomplete type force their record to be invalid.
  8831. Record->setInvalidDecl();
  8832. InvalidDecl = true;
  8833. } else {
  8834. NamedDecl *Def;
  8835. EltTy->isIncompleteType(&Def);
  8836. if (Def && Def->isInvalidDecl()) {
  8837. Record->setInvalidDecl();
  8838. InvalidDecl = true;
  8839. }
  8840. }
  8841. }
  8842. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  8843. if (BitWidth && getLangOpts().OpenCL) {
  8844. Diag(Loc, diag::err_opencl_bitfields);
  8845. InvalidDecl = true;
  8846. }
  8847. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  8848. // than a variably modified type.
  8849. if (!InvalidDecl && T->isVariablyModifiedType()) {
  8850. bool SizeIsNegative;
  8851. llvm::APSInt Oversized;
  8852. TypeSourceInfo *FixedTInfo =
  8853. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  8854. SizeIsNegative,
  8855. Oversized);
  8856. if (FixedTInfo) {
  8857. Diag(Loc, diag::warn_illegal_constant_array_size);
  8858. TInfo = FixedTInfo;
  8859. T = FixedTInfo->getType();
  8860. } else {
  8861. if (SizeIsNegative)
  8862. Diag(Loc, diag::err_typecheck_negative_array_size);
  8863. else if (Oversized.getBoolValue())
  8864. Diag(Loc, diag::err_array_too_large)
  8865. << Oversized.toString(10);
  8866. else
  8867. Diag(Loc, diag::err_typecheck_field_variable_size);
  8868. InvalidDecl = true;
  8869. }
  8870. }
  8871. // Fields can not have abstract class types
  8872. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  8873. diag::err_abstract_type_in_decl,
  8874. AbstractFieldType))
  8875. InvalidDecl = true;
  8876. bool ZeroWidth = false;
  8877. // If this is declared as a bit-field, check the bit-field.
  8878. if (!InvalidDecl && BitWidth) {
  8879. BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
  8880. if (!BitWidth) {
  8881. InvalidDecl = true;
  8882. BitWidth = 0;
  8883. ZeroWidth = false;
  8884. }
  8885. }
  8886. // Check that 'mutable' is consistent with the type of the declaration.
  8887. if (!InvalidDecl && Mutable) {
  8888. unsigned DiagID = 0;
  8889. if (T->isReferenceType())
  8890. DiagID = diag::err_mutable_reference;
  8891. else if (T.isConstQualified())
  8892. DiagID = diag::err_mutable_const;
  8893. if (DiagID) {
  8894. SourceLocation ErrLoc = Loc;
  8895. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  8896. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  8897. Diag(ErrLoc, DiagID);
  8898. Mutable = false;
  8899. InvalidDecl = true;
  8900. }
  8901. }
  8902. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  8903. BitWidth, Mutable, InitStyle);
  8904. if (InvalidDecl)
  8905. NewFD->setInvalidDecl();
  8906. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  8907. Diag(Loc, diag::err_duplicate_member) << II;
  8908. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  8909. NewFD->setInvalidDecl();
  8910. }
  8911. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  8912. if (Record->isUnion()) {
  8913. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  8914. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  8915. if (RDecl->getDefinition()) {
  8916. // C++ [class.union]p1: An object of a class with a non-trivial
  8917. // constructor, a non-trivial copy constructor, a non-trivial
  8918. // destructor, or a non-trivial copy assignment operator
  8919. // cannot be a member of a union, nor can an array of such
  8920. // objects.
  8921. if (CheckNontrivialField(NewFD))
  8922. NewFD->setInvalidDecl();
  8923. }
  8924. }
  8925. // C++ [class.union]p1: If a union contains a member of reference type,
  8926. // the program is ill-formed.
  8927. if (EltTy->isReferenceType()) {
  8928. Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
  8929. << NewFD->getDeclName() << EltTy;
  8930. NewFD->setInvalidDecl();
  8931. }
  8932. }
  8933. }
  8934. // FIXME: We need to pass in the attributes given an AST
  8935. // representation, not a parser representation.
  8936. if (D) {
  8937. // FIXME: What to pass instead of TUScope?
  8938. ProcessDeclAttributes(TUScope, NewFD, *D);
  8939. if (NewFD->hasAttrs())
  8940. CheckAlignasUnderalignment(NewFD);
  8941. }
  8942. // In auto-retain/release, infer strong retension for fields of
  8943. // retainable type.
  8944. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  8945. NewFD->setInvalidDecl();
  8946. if (T.isObjCGCWeak())
  8947. Diag(Loc, diag::warn_attribute_weak_on_field);
  8948. NewFD->setAccess(AS);
  8949. return NewFD;
  8950. }
  8951. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  8952. assert(FD);
  8953. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  8954. if (FD->isInvalidDecl())
  8955. return true;
  8956. QualType EltTy = Context.getBaseElementType(FD->getType());
  8957. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  8958. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  8959. if (RDecl->getDefinition()) {
  8960. // We check for copy constructors before constructors
  8961. // because otherwise we'll never get complaints about
  8962. // copy constructors.
  8963. CXXSpecialMember member = CXXInvalid;
  8964. // We're required to check for any non-trivial constructors. Since the
  8965. // implicit default constructor is suppressed if there are any
  8966. // user-declared constructors, we just need to check that there is a
  8967. // trivial default constructor and a trivial copy constructor. (We don't
  8968. // worry about move constructors here, since this is a C++98 check.)
  8969. if (RDecl->hasNonTrivialCopyConstructor())
  8970. member = CXXCopyConstructor;
  8971. else if (!RDecl->hasTrivialDefaultConstructor())
  8972. member = CXXDefaultConstructor;
  8973. else if (RDecl->hasNonTrivialCopyAssignment())
  8974. member = CXXCopyAssignment;
  8975. else if (RDecl->hasNonTrivialDestructor())
  8976. member = CXXDestructor;
  8977. if (member != CXXInvalid) {
  8978. if (!getLangOpts().CPlusPlus11 &&
  8979. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  8980. // Objective-C++ ARC: it is an error to have a non-trivial field of
  8981. // a union. However, system headers in Objective-C programs
  8982. // occasionally have Objective-C lifetime objects within unions,
  8983. // and rather than cause the program to fail, we make those
  8984. // members unavailable.
  8985. SourceLocation Loc = FD->getLocation();
  8986. if (getSourceManager().isInSystemHeader(Loc)) {
  8987. if (!FD->hasAttr<UnavailableAttr>())
  8988. FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
  8989. "this system field has retaining ownership"));
  8990. return false;
  8991. }
  8992. }
  8993. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  8994. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  8995. diag::err_illegal_union_or_anon_struct_member)
  8996. << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
  8997. DiagnoseNontrivial(RDecl, member);
  8998. return !getLangOpts().CPlusPlus11;
  8999. }
  9000. }
  9001. }
  9002. return false;
  9003. }
  9004. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  9005. /// AST enum value.
  9006. static ObjCIvarDecl::AccessControl
  9007. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  9008. switch (ivarVisibility) {
  9009. default: llvm_unreachable("Unknown visitibility kind");
  9010. case tok::objc_private: return ObjCIvarDecl::Private;
  9011. case tok::objc_public: return ObjCIvarDecl::Public;
  9012. case tok::objc_protected: return ObjCIvarDecl::Protected;
  9013. case tok::objc_package: return ObjCIvarDecl::Package;
  9014. }
  9015. }
  9016. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  9017. /// in order to create an IvarDecl object for it.
  9018. Decl *Sema::ActOnIvar(Scope *S,
  9019. SourceLocation DeclStart,
  9020. Declarator &D, Expr *BitfieldWidth,
  9021. tok::ObjCKeywordKind Visibility) {
  9022. IdentifierInfo *II = D.getIdentifier();
  9023. Expr *BitWidth = (Expr*)BitfieldWidth;
  9024. SourceLocation Loc = DeclStart;
  9025. if (II) Loc = D.getIdentifierLoc();
  9026. // FIXME: Unnamed fields can be handled in various different ways, for
  9027. // example, unnamed unions inject all members into the struct namespace!
  9028. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  9029. QualType T = TInfo->getType();
  9030. if (BitWidth) {
  9031. // 6.7.2.1p3, 6.7.2.1p4
  9032. BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
  9033. if (!BitWidth)
  9034. D.setInvalidType();
  9035. } else {
  9036. // Not a bitfield.
  9037. // validate II.
  9038. }
  9039. if (T->isReferenceType()) {
  9040. Diag(Loc, diag::err_ivar_reference_type);
  9041. D.setInvalidType();
  9042. }
  9043. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  9044. // than a variably modified type.
  9045. else if (T->isVariablyModifiedType()) {
  9046. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  9047. D.setInvalidType();
  9048. }
  9049. // Get the visibility (access control) for this ivar.
  9050. ObjCIvarDecl::AccessControl ac =
  9051. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  9052. : ObjCIvarDecl::None;
  9053. // Must set ivar's DeclContext to its enclosing interface.
  9054. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  9055. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  9056. return 0;
  9057. ObjCContainerDecl *EnclosingContext;
  9058. if (ObjCImplementationDecl *IMPDecl =
  9059. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  9060. if (LangOpts.ObjCRuntime.isFragile()) {
  9061. // Case of ivar declared in an implementation. Context is that of its class.
  9062. EnclosingContext = IMPDecl->getClassInterface();
  9063. assert(EnclosingContext && "Implementation has no class interface!");
  9064. }
  9065. else
  9066. EnclosingContext = EnclosingDecl;
  9067. } else {
  9068. if (ObjCCategoryDecl *CDecl =
  9069. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  9070. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  9071. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  9072. return 0;
  9073. }
  9074. }
  9075. EnclosingContext = EnclosingDecl;
  9076. }
  9077. // Construct the decl.
  9078. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  9079. DeclStart, Loc, II, T,
  9080. TInfo, ac, (Expr *)BitfieldWidth);
  9081. if (II) {
  9082. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  9083. ForRedeclaration);
  9084. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  9085. && !isa<TagDecl>(PrevDecl)) {
  9086. Diag(Loc, diag::err_duplicate_member) << II;
  9087. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  9088. NewID->setInvalidDecl();
  9089. }
  9090. }
  9091. // Process attributes attached to the ivar.
  9092. ProcessDeclAttributes(S, NewID, D);
  9093. if (D.isInvalidType())
  9094. NewID->setInvalidDecl();
  9095. // In ARC, infer 'retaining' for ivars of retainable type.
  9096. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  9097. NewID->setInvalidDecl();
  9098. if (D.getDeclSpec().isModulePrivateSpecified())
  9099. NewID->setModulePrivate();
  9100. if (II) {
  9101. // FIXME: When interfaces are DeclContexts, we'll need to add
  9102. // these to the interface.
  9103. S->AddDecl(NewID);
  9104. IdResolver.AddDecl(NewID);
  9105. }
  9106. if (LangOpts.ObjCRuntime.isNonFragile() &&
  9107. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  9108. Diag(Loc, diag::warn_ivars_in_interface);
  9109. return NewID;
  9110. }
  9111. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  9112. /// class and class extensions. For every class @interface and class
  9113. /// extension @interface, if the last ivar is a bitfield of any type,
  9114. /// then add an implicit `char :0` ivar to the end of that interface.
  9115. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  9116. SmallVectorImpl<Decl *> &AllIvarDecls) {
  9117. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  9118. return;
  9119. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  9120. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  9121. if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
  9122. return;
  9123. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  9124. if (!ID) {
  9125. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  9126. if (!CD->IsClassExtension())
  9127. return;
  9128. }
  9129. // No need to add this to end of @implementation.
  9130. else
  9131. return;
  9132. }
  9133. // All conditions are met. Add a new bitfield to the tail end of ivars.
  9134. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  9135. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  9136. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  9137. DeclLoc, DeclLoc, 0,
  9138. Context.CharTy,
  9139. Context.getTrivialTypeSourceInfo(Context.CharTy,
  9140. DeclLoc),
  9141. ObjCIvarDecl::Private, BW,
  9142. true);
  9143. AllIvarDecls.push_back(Ivar);
  9144. }
  9145. void Sema::ActOnFields(Scope* S,
  9146. SourceLocation RecLoc, Decl *EnclosingDecl,
  9147. llvm::ArrayRef<Decl *> Fields,
  9148. SourceLocation LBrac, SourceLocation RBrac,
  9149. AttributeList *Attr) {
  9150. assert(EnclosingDecl && "missing record or interface decl");
  9151. // If this is an Objective-C @implementation or category and we have
  9152. // new fields here we should reset the layout of the interface since
  9153. // it will now change.
  9154. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  9155. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  9156. switch (DC->getKind()) {
  9157. default: break;
  9158. case Decl::ObjCCategory:
  9159. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  9160. break;
  9161. case Decl::ObjCImplementation:
  9162. Context.
  9163. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  9164. break;
  9165. }
  9166. }
  9167. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  9168. // Start counting up the number of named members; make sure to include
  9169. // members of anonymous structs and unions in the total.
  9170. unsigned NumNamedMembers = 0;
  9171. if (Record) {
  9172. for (RecordDecl::decl_iterator i = Record->decls_begin(),
  9173. e = Record->decls_end(); i != e; i++) {
  9174. if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
  9175. if (IFD->getDeclName())
  9176. ++NumNamedMembers;
  9177. }
  9178. }
  9179. // Verify that all the fields are okay.
  9180. SmallVector<FieldDecl*, 32> RecFields;
  9181. bool ARCErrReported = false;
  9182. for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  9183. i != end; ++i) {
  9184. FieldDecl *FD = cast<FieldDecl>(*i);
  9185. // Get the type for the field.
  9186. const Type *FDTy = FD->getType().getTypePtr();
  9187. if (!FD->isAnonymousStructOrUnion()) {
  9188. // Remember all fields written by the user.
  9189. RecFields.push_back(FD);
  9190. }
  9191. // If the field is already invalid for some reason, don't emit more
  9192. // diagnostics about it.
  9193. if (FD->isInvalidDecl()) {
  9194. EnclosingDecl->setInvalidDecl();
  9195. continue;
  9196. }
  9197. // C99 6.7.2.1p2:
  9198. // A structure or union shall not contain a member with
  9199. // incomplete or function type (hence, a structure shall not
  9200. // contain an instance of itself, but may contain a pointer to
  9201. // an instance of itself), except that the last member of a
  9202. // structure with more than one named member may have incomplete
  9203. // array type; such a structure (and any union containing,
  9204. // possibly recursively, a member that is such a structure)
  9205. // shall not be a member of a structure or an element of an
  9206. // array.
  9207. if (FDTy->isFunctionType()) {
  9208. // Field declared as a function.
  9209. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  9210. << FD->getDeclName();
  9211. FD->setInvalidDecl();
  9212. EnclosingDecl->setInvalidDecl();
  9213. continue;
  9214. } else if (FDTy->isIncompleteArrayType() && Record &&
  9215. ((i + 1 == Fields.end() && !Record->isUnion()) ||
  9216. ((getLangOpts().MicrosoftExt ||
  9217. getLangOpts().CPlusPlus) &&
  9218. (i + 1 == Fields.end() || Record->isUnion())))) {
  9219. // Flexible array member.
  9220. // Microsoft and g++ is more permissive regarding flexible array.
  9221. // It will accept flexible array in union and also
  9222. // as the sole element of a struct/class.
  9223. if (getLangOpts().MicrosoftExt) {
  9224. if (Record->isUnion())
  9225. Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
  9226. << FD->getDeclName();
  9227. else if (Fields.size() == 1)
  9228. Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
  9229. << FD->getDeclName() << Record->getTagKind();
  9230. } else if (getLangOpts().CPlusPlus) {
  9231. if (Record->isUnion())
  9232. Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
  9233. << FD->getDeclName();
  9234. else if (Fields.size() == 1)
  9235. Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
  9236. << FD->getDeclName() << Record->getTagKind();
  9237. } else if (!getLangOpts().C99) {
  9238. if (Record->isUnion())
  9239. Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
  9240. << FD->getDeclName();
  9241. else
  9242. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  9243. << FD->getDeclName() << Record->getTagKind();
  9244. } else if (NumNamedMembers < 1) {
  9245. Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
  9246. << FD->getDeclName();
  9247. FD->setInvalidDecl();
  9248. EnclosingDecl->setInvalidDecl();
  9249. continue;
  9250. }
  9251. if (!FD->getType()->isDependentType() &&
  9252. !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
  9253. Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
  9254. << FD->getDeclName() << FD->getType();
  9255. FD->setInvalidDecl();
  9256. EnclosingDecl->setInvalidDecl();
  9257. continue;
  9258. }
  9259. // Okay, we have a legal flexible array member at the end of the struct.
  9260. if (Record)
  9261. Record->setHasFlexibleArrayMember(true);
  9262. } else if (!FDTy->isDependentType() &&
  9263. RequireCompleteType(FD->getLocation(), FD->getType(),
  9264. diag::err_field_incomplete)) {
  9265. // Incomplete type
  9266. FD->setInvalidDecl();
  9267. EnclosingDecl->setInvalidDecl();
  9268. continue;
  9269. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  9270. if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
  9271. // If this is a member of a union, then entire union becomes "flexible".
  9272. if (Record && Record->isUnion()) {
  9273. Record->setHasFlexibleArrayMember(true);
  9274. } else {
  9275. // If this is a struct/class and this is not the last element, reject
  9276. // it. Note that GCC supports variable sized arrays in the middle of
  9277. // structures.
  9278. if (i + 1 != Fields.end())
  9279. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  9280. << FD->getDeclName() << FD->getType();
  9281. else {
  9282. // We support flexible arrays at the end of structs in
  9283. // other structs as an extension.
  9284. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  9285. << FD->getDeclName();
  9286. if (Record)
  9287. Record->setHasFlexibleArrayMember(true);
  9288. }
  9289. }
  9290. }
  9291. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  9292. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  9293. diag::err_abstract_type_in_decl,
  9294. AbstractIvarType)) {
  9295. // Ivars can not have abstract class types
  9296. FD->setInvalidDecl();
  9297. }
  9298. if (Record && FDTTy->getDecl()->hasObjectMember())
  9299. Record->setHasObjectMember(true);
  9300. if (Record && FDTTy->getDecl()->hasVolatileMember())
  9301. Record->setHasVolatileMember(true);
  9302. } else if (FDTy->isObjCObjectType()) {
  9303. /// A field cannot be an Objective-c object
  9304. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  9305. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  9306. QualType T = Context.getObjCObjectPointerType(FD->getType());
  9307. FD->setType(T);
  9308. } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
  9309. (!getLangOpts().CPlusPlus || Record->isUnion())) {
  9310. // It's an error in ARC if a field has lifetime.
  9311. // We don't want to report this in a system header, though,
  9312. // so we just make the field unavailable.
  9313. // FIXME: that's really not sufficient; we need to make the type
  9314. // itself invalid to, say, initialize or copy.
  9315. QualType T = FD->getType();
  9316. Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
  9317. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
  9318. SourceLocation loc = FD->getLocation();
  9319. if (getSourceManager().isInSystemHeader(loc)) {
  9320. if (!FD->hasAttr<UnavailableAttr>()) {
  9321. FD->addAttr(new (Context) UnavailableAttr(loc, Context,
  9322. "this system field has retaining ownership"));
  9323. }
  9324. } else {
  9325. Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
  9326. << T->isBlockPointerType() << Record->getTagKind();
  9327. }
  9328. ARCErrReported = true;
  9329. }
  9330. } else if (getLangOpts().ObjC1 &&
  9331. getLangOpts().getGC() != LangOptions::NonGC &&
  9332. Record && !Record->hasObjectMember()) {
  9333. if (FD->getType()->isObjCObjectPointerType() ||
  9334. FD->getType().isObjCGCStrong())
  9335. Record->setHasObjectMember(true);
  9336. else if (Context.getAsArrayType(FD->getType())) {
  9337. QualType BaseType = Context.getBaseElementType(FD->getType());
  9338. if (BaseType->isRecordType() &&
  9339. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  9340. Record->setHasObjectMember(true);
  9341. else if (BaseType->isObjCObjectPointerType() ||
  9342. BaseType.isObjCGCStrong())
  9343. Record->setHasObjectMember(true);
  9344. }
  9345. }
  9346. if (Record && FD->getType().isVolatileQualified())
  9347. Record->setHasVolatileMember(true);
  9348. // Keep track of the number of named members.
  9349. if (FD->getIdentifier())
  9350. ++NumNamedMembers;
  9351. }
  9352. // Okay, we successfully defined 'Record'.
  9353. if (Record) {
  9354. bool Completed = false;
  9355. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  9356. if (!CXXRecord->isInvalidDecl()) {
  9357. // Set access bits correctly on the directly-declared conversions.
  9358. for (CXXRecordDecl::conversion_iterator
  9359. I = CXXRecord->conversion_begin(),
  9360. E = CXXRecord->conversion_end(); I != E; ++I)
  9361. I.setAccess((*I)->getAccess());
  9362. if (!CXXRecord->isDependentType()) {
  9363. // Adjust user-defined destructor exception spec.
  9364. if (getLangOpts().CPlusPlus11 &&
  9365. CXXRecord->hasUserDeclaredDestructor())
  9366. AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
  9367. // Add any implicitly-declared members to this class.
  9368. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  9369. // If we have virtual base classes, we may end up finding multiple
  9370. // final overriders for a given virtual function. Check for this
  9371. // problem now.
  9372. if (CXXRecord->getNumVBases()) {
  9373. CXXFinalOverriderMap FinalOverriders;
  9374. CXXRecord->getFinalOverriders(FinalOverriders);
  9375. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  9376. MEnd = FinalOverriders.end();
  9377. M != MEnd; ++M) {
  9378. for (OverridingMethods::iterator SO = M->second.begin(),
  9379. SOEnd = M->second.end();
  9380. SO != SOEnd; ++SO) {
  9381. assert(SO->second.size() > 0 &&
  9382. "Virtual function without overridding functions?");
  9383. if (SO->second.size() == 1)
  9384. continue;
  9385. // C++ [class.virtual]p2:
  9386. // In a derived class, if a virtual member function of a base
  9387. // class subobject has more than one final overrider the
  9388. // program is ill-formed.
  9389. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  9390. << (const NamedDecl *)M->first << Record;
  9391. Diag(M->first->getLocation(),
  9392. diag::note_overridden_virtual_function);
  9393. for (OverridingMethods::overriding_iterator
  9394. OM = SO->second.begin(),
  9395. OMEnd = SO->second.end();
  9396. OM != OMEnd; ++OM)
  9397. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  9398. << (const NamedDecl *)M->first << OM->Method->getParent();
  9399. Record->setInvalidDecl();
  9400. }
  9401. }
  9402. CXXRecord->completeDefinition(&FinalOverriders);
  9403. Completed = true;
  9404. }
  9405. }
  9406. }
  9407. }
  9408. if (!Completed)
  9409. Record->completeDefinition();
  9410. if (Record->hasAttrs())
  9411. CheckAlignasUnderalignment(Record);
  9412. } else {
  9413. ObjCIvarDecl **ClsFields =
  9414. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  9415. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  9416. ID->setEndOfDefinitionLoc(RBrac);
  9417. // Add ivar's to class's DeclContext.
  9418. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  9419. ClsFields[i]->setLexicalDeclContext(ID);
  9420. ID->addDecl(ClsFields[i]);
  9421. }
  9422. // Must enforce the rule that ivars in the base classes may not be
  9423. // duplicates.
  9424. if (ID->getSuperClass())
  9425. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  9426. } else if (ObjCImplementationDecl *IMPDecl =
  9427. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  9428. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  9429. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  9430. // Ivar declared in @implementation never belongs to the implementation.
  9431. // Only it is in implementation's lexical context.
  9432. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  9433. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  9434. IMPDecl->setIvarLBraceLoc(LBrac);
  9435. IMPDecl->setIvarRBraceLoc(RBrac);
  9436. } else if (ObjCCategoryDecl *CDecl =
  9437. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  9438. // case of ivars in class extension; all other cases have been
  9439. // reported as errors elsewhere.
  9440. // FIXME. Class extension does not have a LocEnd field.
  9441. // CDecl->setLocEnd(RBrac);
  9442. // Add ivar's to class extension's DeclContext.
  9443. // Diagnose redeclaration of private ivars.
  9444. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  9445. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  9446. if (IDecl) {
  9447. if (const ObjCIvarDecl *ClsIvar =
  9448. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  9449. Diag(ClsFields[i]->getLocation(),
  9450. diag::err_duplicate_ivar_declaration);
  9451. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  9452. continue;
  9453. }
  9454. for (ObjCInterfaceDecl::known_extensions_iterator
  9455. Ext = IDecl->known_extensions_begin(),
  9456. ExtEnd = IDecl->known_extensions_end();
  9457. Ext != ExtEnd; ++Ext) {
  9458. if (const ObjCIvarDecl *ClsExtIvar
  9459. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  9460. Diag(ClsFields[i]->getLocation(),
  9461. diag::err_duplicate_ivar_declaration);
  9462. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  9463. continue;
  9464. }
  9465. }
  9466. }
  9467. ClsFields[i]->setLexicalDeclContext(CDecl);
  9468. CDecl->addDecl(ClsFields[i]);
  9469. }
  9470. CDecl->setIvarLBraceLoc(LBrac);
  9471. CDecl->setIvarRBraceLoc(RBrac);
  9472. }
  9473. }
  9474. if (Attr)
  9475. ProcessDeclAttributeList(S, Record, Attr);
  9476. }
  9477. /// \brief Determine whether the given integral value is representable within
  9478. /// the given type T.
  9479. static bool isRepresentableIntegerValue(ASTContext &Context,
  9480. llvm::APSInt &Value,
  9481. QualType T) {
  9482. assert(T->isIntegralType(Context) && "Integral type required!");
  9483. unsigned BitWidth = Context.getIntWidth(T);
  9484. if (Value.isUnsigned() || Value.isNonNegative()) {
  9485. if (T->isSignedIntegerOrEnumerationType())
  9486. --BitWidth;
  9487. return Value.getActiveBits() <= BitWidth;
  9488. }
  9489. return Value.getMinSignedBits() <= BitWidth;
  9490. }
  9491. // \brief Given an integral type, return the next larger integral type
  9492. // (or a NULL type of no such type exists).
  9493. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  9494. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  9495. // enum checking below.
  9496. assert(T->isIntegralType(Context) && "Integral type required!");
  9497. const unsigned NumTypes = 4;
  9498. QualType SignedIntegralTypes[NumTypes] = {
  9499. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  9500. };
  9501. QualType UnsignedIntegralTypes[NumTypes] = {
  9502. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  9503. Context.UnsignedLongLongTy
  9504. };
  9505. unsigned BitWidth = Context.getTypeSize(T);
  9506. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  9507. : UnsignedIntegralTypes;
  9508. for (unsigned I = 0; I != NumTypes; ++I)
  9509. if (Context.getTypeSize(Types[I]) > BitWidth)
  9510. return Types[I];
  9511. return QualType();
  9512. }
  9513. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  9514. EnumConstantDecl *LastEnumConst,
  9515. SourceLocation IdLoc,
  9516. IdentifierInfo *Id,
  9517. Expr *Val) {
  9518. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  9519. llvm::APSInt EnumVal(IntWidth);
  9520. QualType EltTy;
  9521. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  9522. Val = 0;
  9523. if (Val)
  9524. Val = DefaultLvalueConversion(Val).take();
  9525. if (Val) {
  9526. if (Enum->isDependentType() || Val->isTypeDependent())
  9527. EltTy = Context.DependentTy;
  9528. else {
  9529. SourceLocation ExpLoc;
  9530. if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
  9531. !getLangOpts().MicrosoftMode) {
  9532. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  9533. // constant-expression in the enumerator-definition shall be a converted
  9534. // constant expression of the underlying type.
  9535. EltTy = Enum->getIntegerType();
  9536. ExprResult Converted =
  9537. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  9538. CCEK_Enumerator);
  9539. if (Converted.isInvalid())
  9540. Val = 0;
  9541. else
  9542. Val = Converted.take();
  9543. } else if (!Val->isValueDependent() &&
  9544. !(Val = VerifyIntegerConstantExpression(Val,
  9545. &EnumVal).take())) {
  9546. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  9547. } else {
  9548. if (Enum->isFixed()) {
  9549. EltTy = Enum->getIntegerType();
  9550. // In Obj-C and Microsoft mode, require the enumeration value to be
  9551. // representable in the underlying type of the enumeration. In C++11,
  9552. // we perform a non-narrowing conversion as part of converted constant
  9553. // expression checking.
  9554. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  9555. if (getLangOpts().MicrosoftMode) {
  9556. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  9557. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
  9558. } else
  9559. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  9560. } else
  9561. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
  9562. } else if (getLangOpts().CPlusPlus) {
  9563. // C++11 [dcl.enum]p5:
  9564. // If the underlying type is not fixed, the type of each enumerator
  9565. // is the type of its initializing value:
  9566. // - If an initializer is specified for an enumerator, the
  9567. // initializing value has the same type as the expression.
  9568. EltTy = Val->getType();
  9569. } else {
  9570. // C99 6.7.2.2p2:
  9571. // The expression that defines the value of an enumeration constant
  9572. // shall be an integer constant expression that has a value
  9573. // representable as an int.
  9574. // Complain if the value is not representable in an int.
  9575. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  9576. Diag(IdLoc, diag::ext_enum_value_not_int)
  9577. << EnumVal.toString(10) << Val->getSourceRange()
  9578. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  9579. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  9580. // Force the type of the expression to 'int'.
  9581. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
  9582. }
  9583. EltTy = Val->getType();
  9584. }
  9585. }
  9586. }
  9587. }
  9588. if (!Val) {
  9589. if (Enum->isDependentType())
  9590. EltTy = Context.DependentTy;
  9591. else if (!LastEnumConst) {
  9592. // C++0x [dcl.enum]p5:
  9593. // If the underlying type is not fixed, the type of each enumerator
  9594. // is the type of its initializing value:
  9595. // - If no initializer is specified for the first enumerator, the
  9596. // initializing value has an unspecified integral type.
  9597. //
  9598. // GCC uses 'int' for its unspecified integral type, as does
  9599. // C99 6.7.2.2p3.
  9600. if (Enum->isFixed()) {
  9601. EltTy = Enum->getIntegerType();
  9602. }
  9603. else {
  9604. EltTy = Context.IntTy;
  9605. }
  9606. } else {
  9607. // Assign the last value + 1.
  9608. EnumVal = LastEnumConst->getInitVal();
  9609. ++EnumVal;
  9610. EltTy = LastEnumConst->getType();
  9611. // Check for overflow on increment.
  9612. if (EnumVal < LastEnumConst->getInitVal()) {
  9613. // C++0x [dcl.enum]p5:
  9614. // If the underlying type is not fixed, the type of each enumerator
  9615. // is the type of its initializing value:
  9616. //
  9617. // - Otherwise the type of the initializing value is the same as
  9618. // the type of the initializing value of the preceding enumerator
  9619. // unless the incremented value is not representable in that type,
  9620. // in which case the type is an unspecified integral type
  9621. // sufficient to contain the incremented value. If no such type
  9622. // exists, the program is ill-formed.
  9623. QualType T = getNextLargerIntegralType(Context, EltTy);
  9624. if (T.isNull() || Enum->isFixed()) {
  9625. // There is no integral type larger enough to represent this
  9626. // value. Complain, then allow the value to wrap around.
  9627. EnumVal = LastEnumConst->getInitVal();
  9628. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  9629. ++EnumVal;
  9630. if (Enum->isFixed())
  9631. // When the underlying type is fixed, this is ill-formed.
  9632. Diag(IdLoc, diag::err_enumerator_wrapped)
  9633. << EnumVal.toString(10)
  9634. << EltTy;
  9635. else
  9636. Diag(IdLoc, diag::warn_enumerator_too_large)
  9637. << EnumVal.toString(10);
  9638. } else {
  9639. EltTy = T;
  9640. }
  9641. // Retrieve the last enumerator's value, extent that type to the
  9642. // type that is supposed to be large enough to represent the incremented
  9643. // value, then increment.
  9644. EnumVal = LastEnumConst->getInitVal();
  9645. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  9646. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  9647. ++EnumVal;
  9648. // If we're not in C++, diagnose the overflow of enumerator values,
  9649. // which in C99 means that the enumerator value is not representable in
  9650. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  9651. // permits enumerator values that are representable in some larger
  9652. // integral type.
  9653. if (!getLangOpts().CPlusPlus && !T.isNull())
  9654. Diag(IdLoc, diag::warn_enum_value_overflow);
  9655. } else if (!getLangOpts().CPlusPlus &&
  9656. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  9657. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  9658. Diag(IdLoc, diag::ext_enum_value_not_int)
  9659. << EnumVal.toString(10) << 1;
  9660. }
  9661. }
  9662. }
  9663. if (!EltTy->isDependentType()) {
  9664. // Make the enumerator value match the signedness and size of the
  9665. // enumerator's type.
  9666. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  9667. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  9668. }
  9669. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  9670. Val, EnumVal);
  9671. }
  9672. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  9673. SourceLocation IdLoc, IdentifierInfo *Id,
  9674. AttributeList *Attr,
  9675. SourceLocation EqualLoc, Expr *Val) {
  9676. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  9677. EnumConstantDecl *LastEnumConst =
  9678. cast_or_null<EnumConstantDecl>(lastEnumConst);
  9679. // The scope passed in may not be a decl scope. Zip up the scope tree until
  9680. // we find one that is.
  9681. S = getNonFieldDeclScope(S);
  9682. // Verify that there isn't already something declared with this name in this
  9683. // scope.
  9684. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  9685. ForRedeclaration);
  9686. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  9687. // Maybe we will complain about the shadowed template parameter.
  9688. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  9689. // Just pretend that we didn't see the previous declaration.
  9690. PrevDecl = 0;
  9691. }
  9692. if (PrevDecl) {
  9693. // When in C++, we may get a TagDecl with the same name; in this case the
  9694. // enum constant will 'hide' the tag.
  9695. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  9696. "Received TagDecl when not in C++!");
  9697. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  9698. if (isa<EnumConstantDecl>(PrevDecl))
  9699. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  9700. else
  9701. Diag(IdLoc, diag::err_redefinition) << Id;
  9702. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  9703. return 0;
  9704. }
  9705. }
  9706. // C++ [class.mem]p15:
  9707. // If T is the name of a class, then each of the following shall have a name
  9708. // different from T:
  9709. // - every enumerator of every member of class T that is an unscoped
  9710. // enumerated type
  9711. if (CXXRecordDecl *Record
  9712. = dyn_cast<CXXRecordDecl>(
  9713. TheEnumDecl->getDeclContext()->getRedeclContext()))
  9714. if (!TheEnumDecl->isScoped() &&
  9715. Record->getIdentifier() && Record->getIdentifier() == Id)
  9716. Diag(IdLoc, diag::err_member_name_of_class) << Id;
  9717. EnumConstantDecl *New =
  9718. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  9719. if (New) {
  9720. // Process attributes.
  9721. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  9722. // Register this decl in the current scope stack.
  9723. New->setAccess(TheEnumDecl->getAccess());
  9724. PushOnScopeChains(New, S);
  9725. }
  9726. ActOnDocumentableDecl(New);
  9727. return New;
  9728. }
  9729. // Returns true when the enum initial expression does not trigger the
  9730. // duplicate enum warning. A few common cases are exempted as follows:
  9731. // Element2 = Element1
  9732. // Element2 = Element1 + 1
  9733. // Element2 = Element1 - 1
  9734. // Where Element2 and Element1 are from the same enum.
  9735. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  9736. Expr *InitExpr = ECD->getInitExpr();
  9737. if (!InitExpr)
  9738. return true;
  9739. InitExpr = InitExpr->IgnoreImpCasts();
  9740. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  9741. if (!BO->isAdditiveOp())
  9742. return true;
  9743. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  9744. if (!IL)
  9745. return true;
  9746. if (IL->getValue() != 1)
  9747. return true;
  9748. InitExpr = BO->getLHS();
  9749. }
  9750. // This checks if the elements are from the same enum.
  9751. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  9752. if (!DRE)
  9753. return true;
  9754. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  9755. if (!EnumConstant)
  9756. return true;
  9757. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  9758. Enum)
  9759. return true;
  9760. return false;
  9761. }
  9762. struct DupKey {
  9763. int64_t val;
  9764. bool isTombstoneOrEmptyKey;
  9765. DupKey(int64_t val, bool isTombstoneOrEmptyKey)
  9766. : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
  9767. };
  9768. static DupKey GetDupKey(const llvm::APSInt& Val) {
  9769. return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
  9770. false);
  9771. }
  9772. struct DenseMapInfoDupKey {
  9773. static DupKey getEmptyKey() { return DupKey(0, true); }
  9774. static DupKey getTombstoneKey() { return DupKey(1, true); }
  9775. static unsigned getHashValue(const DupKey Key) {
  9776. return (unsigned)(Key.val * 37);
  9777. }
  9778. static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
  9779. return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
  9780. LHS.val == RHS.val;
  9781. }
  9782. };
  9783. // Emits a warning when an element is implicitly set a value that
  9784. // a previous element has already been set to.
  9785. static void CheckForDuplicateEnumValues(Sema &S, Decl **Elements,
  9786. unsigned NumElements, EnumDecl *Enum,
  9787. QualType EnumType) {
  9788. if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
  9789. Enum->getLocation()) ==
  9790. DiagnosticsEngine::Ignored)
  9791. return;
  9792. // Avoid anonymous enums
  9793. if (!Enum->getIdentifier())
  9794. return;
  9795. // Only check for small enums.
  9796. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  9797. return;
  9798. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  9799. typedef SmallVector<ECDVector *, 3> DuplicatesVector;
  9800. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  9801. typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
  9802. ValueToVectorMap;
  9803. DuplicatesVector DupVector;
  9804. ValueToVectorMap EnumMap;
  9805. // Populate the EnumMap with all values represented by enum constants without
  9806. // an initialier.
  9807. for (unsigned i = 0; i < NumElements; ++i) {
  9808. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
  9809. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  9810. // this constant. Skip this enum since it may be ill-formed.
  9811. if (!ECD) {
  9812. return;
  9813. }
  9814. if (ECD->getInitExpr())
  9815. continue;
  9816. DupKey Key = GetDupKey(ECD->getInitVal());
  9817. DeclOrVector &Entry = EnumMap[Key];
  9818. // First time encountering this value.
  9819. if (Entry.isNull())
  9820. Entry = ECD;
  9821. }
  9822. // Create vectors for any values that has duplicates.
  9823. for (unsigned i = 0; i < NumElements; ++i) {
  9824. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
  9825. if (!ValidDuplicateEnum(ECD, Enum))
  9826. continue;
  9827. DupKey Key = GetDupKey(ECD->getInitVal());
  9828. DeclOrVector& Entry = EnumMap[Key];
  9829. if (Entry.isNull())
  9830. continue;
  9831. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  9832. // Ensure constants are different.
  9833. if (D == ECD)
  9834. continue;
  9835. // Create new vector and push values onto it.
  9836. ECDVector *Vec = new ECDVector();
  9837. Vec->push_back(D);
  9838. Vec->push_back(ECD);
  9839. // Update entry to point to the duplicates vector.
  9840. Entry = Vec;
  9841. // Store the vector somewhere we can consult later for quick emission of
  9842. // diagnostics.
  9843. DupVector.push_back(Vec);
  9844. continue;
  9845. }
  9846. ECDVector *Vec = Entry.get<ECDVector*>();
  9847. // Make sure constants are not added more than once.
  9848. if (*Vec->begin() == ECD)
  9849. continue;
  9850. Vec->push_back(ECD);
  9851. }
  9852. // Emit diagnostics.
  9853. for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
  9854. DupVectorEnd = DupVector.end();
  9855. DupVectorIter != DupVectorEnd; ++DupVectorIter) {
  9856. ECDVector *Vec = *DupVectorIter;
  9857. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  9858. // Emit warning for one enum constant.
  9859. ECDVector::iterator I = Vec->begin();
  9860. S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
  9861. << (*I)->getName() << (*I)->getInitVal().toString(10)
  9862. << (*I)->getSourceRange();
  9863. ++I;
  9864. // Emit one note for each of the remaining enum constants with
  9865. // the same value.
  9866. for (ECDVector::iterator E = Vec->end(); I != E; ++I)
  9867. S.Diag((*I)->getLocation(), diag::note_duplicate_element)
  9868. << (*I)->getName() << (*I)->getInitVal().toString(10)
  9869. << (*I)->getSourceRange();
  9870. delete Vec;
  9871. }
  9872. }
  9873. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
  9874. SourceLocation RBraceLoc, Decl *EnumDeclX,
  9875. Decl **Elements, unsigned NumElements,
  9876. Scope *S, AttributeList *Attr) {
  9877. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  9878. QualType EnumType = Context.getTypeDeclType(Enum);
  9879. if (Attr)
  9880. ProcessDeclAttributeList(S, Enum, Attr);
  9881. if (Enum->isDependentType()) {
  9882. for (unsigned i = 0; i != NumElements; ++i) {
  9883. EnumConstantDecl *ECD =
  9884. cast_or_null<EnumConstantDecl>(Elements[i]);
  9885. if (!ECD) continue;
  9886. ECD->setType(EnumType);
  9887. }
  9888. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  9889. return;
  9890. }
  9891. // TODO: If the result value doesn't fit in an int, it must be a long or long
  9892. // long value. ISO C does not support this, but GCC does as an extension,
  9893. // emit a warning.
  9894. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  9895. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  9896. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  9897. // Verify that all the values are okay, compute the size of the values, and
  9898. // reverse the list.
  9899. unsigned NumNegativeBits = 0;
  9900. unsigned NumPositiveBits = 0;
  9901. // Keep track of whether all elements have type int.
  9902. bool AllElementsInt = true;
  9903. for (unsigned i = 0; i != NumElements; ++i) {
  9904. EnumConstantDecl *ECD =
  9905. cast_or_null<EnumConstantDecl>(Elements[i]);
  9906. if (!ECD) continue; // Already issued a diagnostic.
  9907. const llvm::APSInt &InitVal = ECD->getInitVal();
  9908. // Keep track of the size of positive and negative values.
  9909. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  9910. NumPositiveBits = std::max(NumPositiveBits,
  9911. (unsigned)InitVal.getActiveBits());
  9912. else
  9913. NumNegativeBits = std::max(NumNegativeBits,
  9914. (unsigned)InitVal.getMinSignedBits());
  9915. // Keep track of whether every enum element has type int (very commmon).
  9916. if (AllElementsInt)
  9917. AllElementsInt = ECD->getType() == Context.IntTy;
  9918. }
  9919. // Figure out the type that should be used for this enum.
  9920. QualType BestType;
  9921. unsigned BestWidth;
  9922. // C++0x N3000 [conv.prom]p3:
  9923. // An rvalue of an unscoped enumeration type whose underlying
  9924. // type is not fixed can be converted to an rvalue of the first
  9925. // of the following types that can represent all the values of
  9926. // the enumeration: int, unsigned int, long int, unsigned long
  9927. // int, long long int, or unsigned long long int.
  9928. // C99 6.4.4.3p2:
  9929. // An identifier declared as an enumeration constant has type int.
  9930. // The C99 rule is modified by a gcc extension
  9931. QualType BestPromotionType;
  9932. bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
  9933. // -fshort-enums is the equivalent to specifying the packed attribute on all
  9934. // enum definitions.
  9935. if (LangOpts.ShortEnums)
  9936. Packed = true;
  9937. if (Enum->isFixed()) {
  9938. BestType = Enum->getIntegerType();
  9939. if (BestType->isPromotableIntegerType())
  9940. BestPromotionType = Context.getPromotedIntegerType(BestType);
  9941. else
  9942. BestPromotionType = BestType;
  9943. // We don't need to set BestWidth, because BestType is going to be the type
  9944. // of the enumerators, but we do anyway because otherwise some compilers
  9945. // warn that it might be used uninitialized.
  9946. BestWidth = CharWidth;
  9947. }
  9948. else if (NumNegativeBits) {
  9949. // If there is a negative value, figure out the smallest integer type (of
  9950. // int/long/longlong) that fits.
  9951. // If it's packed, check also if it fits a char or a short.
  9952. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  9953. BestType = Context.SignedCharTy;
  9954. BestWidth = CharWidth;
  9955. } else if (Packed && NumNegativeBits <= ShortWidth &&
  9956. NumPositiveBits < ShortWidth) {
  9957. BestType = Context.ShortTy;
  9958. BestWidth = ShortWidth;
  9959. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  9960. BestType = Context.IntTy;
  9961. BestWidth = IntWidth;
  9962. } else {
  9963. BestWidth = Context.getTargetInfo().getLongWidth();
  9964. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  9965. BestType = Context.LongTy;
  9966. } else {
  9967. BestWidth = Context.getTargetInfo().getLongLongWidth();
  9968. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  9969. Diag(Enum->getLocation(), diag::warn_enum_too_large);
  9970. BestType = Context.LongLongTy;
  9971. }
  9972. }
  9973. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  9974. } else {
  9975. // If there is no negative value, figure out the smallest type that fits
  9976. // all of the enumerator values.
  9977. // If it's packed, check also if it fits a char or a short.
  9978. if (Packed && NumPositiveBits <= CharWidth) {
  9979. BestType = Context.UnsignedCharTy;
  9980. BestPromotionType = Context.IntTy;
  9981. BestWidth = CharWidth;
  9982. } else if (Packed && NumPositiveBits <= ShortWidth) {
  9983. BestType = Context.UnsignedShortTy;
  9984. BestPromotionType = Context.IntTy;
  9985. BestWidth = ShortWidth;
  9986. } else if (NumPositiveBits <= IntWidth) {
  9987. BestType = Context.UnsignedIntTy;
  9988. BestWidth = IntWidth;
  9989. BestPromotionType
  9990. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  9991. ? Context.UnsignedIntTy : Context.IntTy;
  9992. } else if (NumPositiveBits <=
  9993. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  9994. BestType = Context.UnsignedLongTy;
  9995. BestPromotionType
  9996. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  9997. ? Context.UnsignedLongTy : Context.LongTy;
  9998. } else {
  9999. BestWidth = Context.getTargetInfo().getLongLongWidth();
  10000. assert(NumPositiveBits <= BestWidth &&
  10001. "How could an initializer get larger than ULL?");
  10002. BestType = Context.UnsignedLongLongTy;
  10003. BestPromotionType
  10004. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  10005. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  10006. }
  10007. }
  10008. // Loop over all of the enumerator constants, changing their types to match
  10009. // the type of the enum if needed.
  10010. for (unsigned i = 0; i != NumElements; ++i) {
  10011. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  10012. if (!ECD) continue; // Already issued a diagnostic.
  10013. // Standard C says the enumerators have int type, but we allow, as an
  10014. // extension, the enumerators to be larger than int size. If each
  10015. // enumerator value fits in an int, type it as an int, otherwise type it the
  10016. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  10017. // that X has type 'int', not 'unsigned'.
  10018. // Determine whether the value fits into an int.
  10019. llvm::APSInt InitVal = ECD->getInitVal();
  10020. // If it fits into an integer type, force it. Otherwise force it to match
  10021. // the enum decl type.
  10022. QualType NewTy;
  10023. unsigned NewWidth;
  10024. bool NewSign;
  10025. if (!getLangOpts().CPlusPlus &&
  10026. !Enum->isFixed() &&
  10027. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  10028. NewTy = Context.IntTy;
  10029. NewWidth = IntWidth;
  10030. NewSign = true;
  10031. } else if (ECD->getType() == BestType) {
  10032. // Already the right type!
  10033. if (getLangOpts().CPlusPlus)
  10034. // C++ [dcl.enum]p4: Following the closing brace of an
  10035. // enum-specifier, each enumerator has the type of its
  10036. // enumeration.
  10037. ECD->setType(EnumType);
  10038. continue;
  10039. } else {
  10040. NewTy = BestType;
  10041. NewWidth = BestWidth;
  10042. NewSign = BestType->isSignedIntegerOrEnumerationType();
  10043. }
  10044. // Adjust the APSInt value.
  10045. InitVal = InitVal.extOrTrunc(NewWidth);
  10046. InitVal.setIsSigned(NewSign);
  10047. ECD->setInitVal(InitVal);
  10048. // Adjust the Expr initializer and type.
  10049. if (ECD->getInitExpr() &&
  10050. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  10051. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  10052. CK_IntegralCast,
  10053. ECD->getInitExpr(),
  10054. /*base paths*/ 0,
  10055. VK_RValue));
  10056. if (getLangOpts().CPlusPlus)
  10057. // C++ [dcl.enum]p4: Following the closing brace of an
  10058. // enum-specifier, each enumerator has the type of its
  10059. // enumeration.
  10060. ECD->setType(EnumType);
  10061. else
  10062. ECD->setType(NewTy);
  10063. }
  10064. Enum->completeDefinition(BestType, BestPromotionType,
  10065. NumPositiveBits, NumNegativeBits);
  10066. // If we're declaring a function, ensure this decl isn't forgotten about -
  10067. // it needs to go into the function scope.
  10068. if (InFunctionDeclarator)
  10069. DeclsInPrototypeScope.push_back(Enum);
  10070. CheckForDuplicateEnumValues(*this, Elements, NumElements, Enum, EnumType);
  10071. // Now that the enum type is defined, ensure it's not been underaligned.
  10072. if (Enum->hasAttrs())
  10073. CheckAlignasUnderalignment(Enum);
  10074. }
  10075. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  10076. SourceLocation StartLoc,
  10077. SourceLocation EndLoc) {
  10078. StringLiteral *AsmString = cast<StringLiteral>(expr);
  10079. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  10080. AsmString, StartLoc,
  10081. EndLoc);
  10082. CurContext->addDecl(New);
  10083. return New;
  10084. }
  10085. DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
  10086. SourceLocation ImportLoc,
  10087. ModuleIdPath Path) {
  10088. Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
  10089. Module::AllVisible,
  10090. /*IsIncludeDirective=*/false);
  10091. if (!Mod)
  10092. return true;
  10093. SmallVector<SourceLocation, 2> IdentifierLocs;
  10094. Module *ModCheck = Mod;
  10095. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  10096. // If we've run out of module parents, just drop the remaining identifiers.
  10097. // We need the length to be consistent.
  10098. if (!ModCheck)
  10099. break;
  10100. ModCheck = ModCheck->Parent;
  10101. IdentifierLocs.push_back(Path[I].second);
  10102. }
  10103. ImportDecl *Import = ImportDecl::Create(Context,
  10104. Context.getTranslationUnitDecl(),
  10105. AtLoc.isValid()? AtLoc : ImportLoc,
  10106. Mod, IdentifierLocs);
  10107. Context.getTranslationUnitDecl()->addDecl(Import);
  10108. return Import;
  10109. }
  10110. void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
  10111. // Create the implicit import declaration.
  10112. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  10113. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  10114. Loc, Mod, Loc);
  10115. TU->addDecl(ImportD);
  10116. Consumer.HandleImplicitImportDecl(ImportD);
  10117. // Make the module visible.
  10118. PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
  10119. }
  10120. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  10121. IdentifierInfo* AliasName,
  10122. SourceLocation PragmaLoc,
  10123. SourceLocation NameLoc,
  10124. SourceLocation AliasNameLoc) {
  10125. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  10126. LookupOrdinaryName);
  10127. AsmLabelAttr *Attr =
  10128. ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
  10129. if (PrevDecl)
  10130. PrevDecl->addAttr(Attr);
  10131. else
  10132. (void)ExtnameUndeclaredIdentifiers.insert(
  10133. std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
  10134. }
  10135. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  10136. SourceLocation PragmaLoc,
  10137. SourceLocation NameLoc) {
  10138. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  10139. if (PrevDecl) {
  10140. PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
  10141. } else {
  10142. (void)WeakUndeclaredIdentifiers.insert(
  10143. std::pair<IdentifierInfo*,WeakInfo>
  10144. (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
  10145. }
  10146. }
  10147. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  10148. IdentifierInfo* AliasName,
  10149. SourceLocation PragmaLoc,
  10150. SourceLocation NameLoc,
  10151. SourceLocation AliasNameLoc) {
  10152. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  10153. LookupOrdinaryName);
  10154. WeakInfo W = WeakInfo(Name, NameLoc);
  10155. if (PrevDecl) {
  10156. if (!PrevDecl->hasAttr<AliasAttr>())
  10157. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  10158. DeclApplyPragmaWeak(TUScope, ND, W);
  10159. } else {
  10160. (void)WeakUndeclaredIdentifiers.insert(
  10161. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  10162. }
  10163. }
  10164. Decl *Sema::getObjCDeclContext() const {
  10165. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  10166. }
  10167. AvailabilityResult Sema::getCurContextAvailability() const {
  10168. const Decl *D = cast<Decl>(getCurObjCLexicalContext());
  10169. return D->getAvailability();
  10170. }